bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 34쪽
a handshake that reveals the recipient was contacted (see [Tagging secret strategy](#tagging-secret-strategy))
```
// Minting to an arbitrary recipient - must guarantee delivery
self.storage.balances.at(recipient).add(amount)
.deliver(MessageDelivery::onchain_constrained());
```
## Choosing a delivery mode[](#choosing-a-delivery-mode "Direct link to Choosing a delivery mode")
Ask yourself: **"Is the sender incentivized to deliver this note correctly?"**
* **Yes, and they can contact the recipient offchain** Use offchain delivery
* **Yes, but they cannot or prefer not to contact them offchain or you don't want to implement offchain delivery** Use unconstrained delivery
* **No, the sender might not deliver correctly** Use constrained delivery
## Tagging secret strategy[](#tagging-secret-strategy "Direct link to Tagging secret strategy")
Onchain delivery tags every message so the recipient can find it efficiently (see [note discovery](#note-discovery-and-the-sender) below). Computing a tag requires a secret shared between sender and recipient, and there is more than one way for the two parties to come to share it. The derivation is decided in this order:
1. A contract can fix it itself at the point of delivery (see [overriding the strategy from the contract](#overriding-the-strategy-from-the-contract)).
2. Otherwise, when an onchain handshake has been registered for the pair, the secret derived from it is reused directly.
3. Otherwise, the wallet decides how to proceed, since it knows which secrets it holds and how it wants to reach the recipient.
The wallet's answer is a **tagging secret strategy**: it expresses *which* secret to use, and if necessary, PXE performs a [Diffie-Hellman key exchange](https://www.geeksforgeeks.org/computer-networks/diffie-hellman-key-exchange-and-perfect-forward-secrecy/) and/or app-siloing before handing the ready-to-use secret to the contract. Wallets therefore never reimplement that derivation. There are four strategies today:
* **Non-interactive handshake**: the secret comes from a handshake published onchain that the recipient can derive. A non-recipient can at most learn that a sender did a handshake with the recipient, not the message itself, but the recipient discovers it without any prior coordination. Works for both constrained and unconstrained delivery.
* **Interactive handshake**: the secret comes from a handshake the recipient authorizes with a signature, which the registry requests through the custom request oracle and verifies in-circuit. Nothing announcing the handshake is published onchain (the recipient learns the secret while signing), but the recipient must be reachable to answer the request, or the send fails. Works for both constrained and unconstrained delivery.
* **Address-derived secret**: the PXE derives the secret from the sender's and recipient's address keys via Diffie-Hellman. The wallet supplies no material, only the choice. It leaves no onchain trace, but the recipient only finds the message if they registered the sender in their PXE. Unconstrained delivery only.
* **Arbitrary secret**: a raw secret point the two parties already share offchain, having coordinated out of band to agree on it. The wallet supplies the point and the PXE app-silos it. It leaves no onchain trace, but no onchain handshake backs the secret. Unconstrained delivery only.
| | Non-interactive handshake | Interactive handshake | Address-derived secret | Arbitrary secret |
| ----------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------- | --------------------------------------------- | --------------------------------------------- |
| Onchain footprint when establishing | A handshake revealing information about the recipient | None | None | None |
| Who provides the material | The onchain registry | The onchain registry, with the recipient's signed authorization | Nobody (PXE computes it) | The wallet (a raw point) |
| Recipient coordination | None | The recipient must answer the signature request | The recipient must have registered the sender | Agreed out of band |
| Constrained delivery | Supported | Supported | Not sound: not backed by an onchain handshake | Not sound: not backed by an onchain handshake |
### Defaults[](#defaults "Direct link to Defaults")
When no `resolveTaggingSecretStrategy` hook is configured, the PXE applies a default:
* **Unconstrained delivery**: a non-interactive handshake when the recipient is external, so the recipient discovers the message without having registered the sender in advance. When the recipient is one of the wallet's own accounts (a self-send), an address-derived secret is used instead: the wallet holds both sides' keys, so no handshake is needed and nothing is revealed onchain.
* **Constrained delivery**: a non-interactive handshake (constrained delivery must be backed by a handshake).
An interactive handshake is never the default, since it fails when the recipient cannot be reached: a wallet opts in through the hook when it knows how to reach them.
### Configuring the strategy[](#configuring-the-strategy "Direct link to Configuring the strategy")
Wallets provide the strategy through the `resolveTaggingSecretStrategy` [execution hook](/developers/testnet/docs/foundational-topics/pxe/execution_hooks.md) when creating their PXE. The hook receives the message context (executing contract, sender, recipient and delivery mode), so a wallet can answer per message instead of with a fixed value. That page also covers how to configure a strategy in Noir tests.
### Overriding the strategy from the contract[](#overriding-the-strategy-from-the-contract "Direct link to Overriding the strategy from the contract")
A contract can fix the derivation at the point of delivery with the builder's `via_*` methods. When it does, the wallet is not consulted at all; otherwise the wallet resolves the strategy as usual:
```
MessageDelivery::onchain_unconstrained().via_address_derived_secret()
```
Unconstrained delivery exposes `via_non_interactive_handshake()`, `via_interactive_handshake()` and `via_address_derived_secret()`. Constrained delivery exposes only `via_non_interactive_handshake()` and `via_interactive_handshake()`, since an address-derived secret cannot back constrained delivery.
## Note discovery and the sender[](#note-discovery-and-the-sender "Direct link to Note discovery and the sender")
When a note is delivered, recipients need to discover it among all the encrypted logs on the network. Aztec.nr uses a **tagging system** that requires computing a shared secret between the sender and recipient.
### Who is the "sender"?[](#who-is-the-sender "Direct link to Who is the \"sender\"?")
The "sender" for note discovery is **not the contract calling `.deliver()`**. Instead, it's the **account contract** that initiated the transaction.
When your wallet submits a transaction, it tells PXE which address to use as the sender for tags (typically the originating account). Recipients compute the tag to find their notes from a secret shared between the sender and recipient, and there is [more than one way to establish that secret](#tagging-secret-strategy), chosen by the wallet. Contracts can override the sender at message delivery via the `with_sender` builder method, which works for both constrained and unconstrained delivery, e.g. `MessageDelivery::onchain_constrained().with_sender(address)`. They can similarly override how the tag secret is derived via the builder's `via_*` methods; see [overriding the strategy from the contract](#overriding-the-strategy-from-the-contract).
**Example:** If Alice uses her account contract to call a token contract that mints tokens to Bob, the "sender for tags" is Alice's account contract address, not the token contract address.
### Discovering notes from unknown senders[](#discovering-notes-from-unknown-senders "Direct link to Discovering notes from unknown senders")
When the tag is derived from an address-based shared secret, you cannot compute it for a sender you haven't registered in advance, so you cannot receive those notes from an unknown sender. Handshake protocols let the two parties agree on the secret another way and lift this restriction.
See [You cannot receive address-derived tagged notes from an unknown sender](/developers/testnet/docs/foundational-topics/advanced/storage/note_discovery.md#you-cannot-receive-address-derived-tagged-notes-from-an-unknown-sender) in the note discovery documentation for the approaches and workarounds.
## Delivering to someone other than the note owner[](#delivering-to-someone-other-than-the-note-owner "Direct link to Delivering to someone other than the note owner")
You can deliver a note to an address other than the note's owner using `.deliver_to()`:
```
// Create a note owned by `owner` but deliver it to `auditor`
self.storage.balances.at(owner).add(amount)
.deliver_to(auditor, MessageDelivery::onchain_constrained());
```
**Important:** The recipient (e.g. an `auditor`) can see the note was created but **cannot use it** - only the owner can spend the note (this is authorized by the contract logic). The recipient also cannot see when/if the note is nullified.
**Use cases:**
* Traditional finance model of compliance where the third party sees all the activity (e.g. a bank)
* Game servers that track all note creation and then quickly serve you the game state (results in better UX)
* Analytics or monitoring services
## Code examples[](#code-examples "Direct link to Code examples")
### Private token transfer[](#private-token-transfer "Direct link to Private token transfer")
```
#[external("private")]
fn transfer(amount: u128, sender: AztecAddress, recipient: AztecAddress) {
// Subtract from sender - unconstrained since sender is the caller
self.storage.balances.at(sender)
.sub(amount)
.deliver(MessageDelivery::onchain_unconstrained());
// Add to recipient - constrained delivery for untrusted sender
self.storage.balances.at(recipient)
.add(amount)
.deliver(MessageDelivery::onchain_constrained());
}
```
### Admin initialization[](#admin-initialization "Direct link to Admin initialization")
```
#[external("private")]
#[initializer]
fn constructor(admin: AztecAddress) {
// Admin is the owner of the note and is motivated to receive it
// Use unconstrained delivery since we don't know if deployer is incentivized
self.storage.admin
.initialize(AddressNote { address: admin }, admin)
.deliver(MessageDelivery::onchain_constrained());
}
```
---
# Offchain message delivery
Offchain message delivery lets you send notes and events to recipients without posting any data onchain. The encrypted message is returned to the sender's application, which transports it to the recipient through its own channel: a link, a QR code, a direct message, or any other medium. This eliminates data availability (DA) costs and adds zero proving time, at the cost of the application handling transport itself.
This page walks through the complete workflow. For guidance on when offchain delivery is the right choice compared to the onchain modes, see [Note delivery](/developers/testnet/docs/aztec-nr/framework-description/note_delivery.md).
## Overview[](#overview "Direct link to Overview")
An offchain-delivered message goes through five stages:
1. **Emission**: The contract delivers a note or event with `MessageDelivery::offchain()`. The message is encrypted to the recipient and emitted as an offchain effect, which is part of the transaction's execution output but never posted onchain.
2. **Extraction**: After sending the transaction, the sender's application reads the emitted messages from the send result (`offchainMessages`).
3. **Transport**: The application delivers each message to its recipient through a channel of its choosing. This step is entirely the application's responsibility.
4. **Receipt**: The recipient hands the message to their wallet by calling the `offchain_receive` utility function on the contract that emitted it. This function is generated automatically by the `#[aztec]` macro, so every Aztec.nr contract has it.
5. **Processing**: The message sits in a local inbox until the transaction that emitted it is found onchain. During private state sync, the wallet decrypts the message, validates the resulting notes and events against onchain data, and adds them to its database.
Because processing validates the message against the onchain transaction, a malformed or dishonest message cannot trick the recipient: a message that cannot be decrypted or validated is simply ignored.
## Emitting offchain messages from a contract[](#emitting-offchain-messages-from-a-contract "Direct link to Emitting offchain messages from a contract")
Choose offchain delivery by passing `MessageDelivery::offchain()` to `.deliver()` (for notes) or `.deliver_to()` (for events). The token contract's `transfer_in_private_with_offchain_delivery` function delivers both resulting balance notes and a `Transfer` event offchain:
transfer\_in\_private\_with\_offchain\_delivery
```
/// Mirrors `transfer_in_private` but delivers the resulting notes via offchain messages.
///
/// Offchain messages are returned to the caller as encrypted payloads. The sender is responsible for getting the
/// recipient's note to them (typically by encoding it into a link, QR code, or direct message). The recipient
/// ingests it by calling `offchain_receive` on their environment.
///
/// A `Transfer` event is also emitted to be delivered offchain.
#[authorize_once("from", "authwit_nonce")]
#[external("private")]
fn transfer_in_private_with_offchain_delivery(
from: AztecAddress,
to: AztecAddress,
amount: u128,
authwit_nonce: Field,
) {
self.storage.balances.at(from).sub(amount).deliver(MessageDelivery::offchain());
self.storage.balances.at(to).add(amount).deliver(MessageDelivery::offchain());
self.emit(Transfer { from, to, amount }).deliver_to(to, MessageDelivery::offchain());
}
```
> [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L293-L314](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L293-L314)
Nothing else changes in the contract: the same notes and events are created, only their delivery mechanism differs.
Under the hood, `MessageDelivery::offchain()` encrypts the message without constraints and emits it via the [`deliver_offchain_message`](/aztec-nr-api/testnet/noir_aztec/messages/offchain_messages/fn.deliver_offchain_message) function. See the [`MessageDelivery`](/aztec-nr-api/testnet/noir_aztec/messages/delivery/struct.MessageDelivery) API reference for details on guarantees, costs, and privacy.
## Extracting messages on the sender side[](#extracting-messages-on-the-sender-side "Direct link to Extracting messages on the sender side")
In `aztec.js`, the result of sending a transaction includes the offchain messages emitted during execution. Each message carries the encrypted `payload`, the `recipient` address, the emitting `contractAddress`, and the `anchorBlockTimestamp` of the transaction:
```
const { receipt, offchainMessages } = await token.methods
.transfer_in_private_with_offchain_delivery(alice, bob, amount, 0)
.send({ from: alice });
// Find the message addressed to the recipient
const messageForBob = offchainMessages.find((msg) => msg.recipient.equals(bob));
```
If you manage proving manually, you can extract the messages from a proven transaction's offchain effects with `extractOffchainOutput`:
```
import { extractOffchainOutput } from "@aztec-labs/aztec.js/contracts";
const { offchainMessages } = extractOffchainOutput(
provenTx.offchainEffects,
provenTx.data.constants.anchorBlockHeader.globalVariables.timestamp,
);
```
## Transporting messages to the recipient[](#transporting-messages-to-the-recipient "Direct link to Transporting messages to the recipient")
The recipient needs four pieces of information to receive a message:
* the message payload (ciphertext)
* the recipient address
* the hash of the transaction that emitted the message
* the anchor block timestamp
How you get these to the recipient is up to your application. Common patterns include encoding them into a claim link or QR code that the recipient opens, sending them through a messaging service, or storing them where the recipient can fetch them.
Back up your messages
Offchain messages are not stored onchain, so they cannot be recovered from the network. Until the recipient has processed a message, losing it means the recipient cannot decrypt the corresponding note contents (the note itself still exists onchain).
## Receiving messages[](#receiving-messages "Direct link to Receiving messages")
The recipient calls the auto-generated `offchain_receive` utility function on the contract that emitted the message. Utility functions run locally and do not create a transaction, so this call is free:
```
await token.methods
.offchain_receive([
{
ciphertext: messageForBob.payload,
recipient: bob,
tx_hash: receipt.txHash.hash,
anchor_block_timestamp: messageForBob.anchorBlockTimestamp,
},
])
.simulate({ from: bob });
```
`offchain_receive` accepts up to 16 messages per call. It stores them in a persistent inbox scoped to each message's recipient; processing happens later, during sync.
## How messages are processed[](#how-messages-are-processed "Direct link to How messages are processed")
Once received, messages are managed by an inbox that the wallet syncs against (see [`receive`](/aztec-nr-api/testnet/noir_aztec/messages/processing/offchain/fn.receive) in the API reference):
* **Transaction resolution**: A message is only processed once the transaction identified by its `tx_hash` is found onchain. This provides the context needed to validate the notes and events the message contains. Until then, the message waits in the inbox.
* **Reorg safety**: Messages remain in the inbox even after processing. If a reorg reverts the transaction that emitted a message, its effects are rolled back; when the transaction is mined again, the message is reprocessed automatically without needing to be delivered again.
* **Expiry**: Messages are evicted from the inbox once they expire, which happens 26 hours after their anchor block timestamp (the maximum transaction lifetime of 24 hours plus a 2 hour tolerance). A transaction can no longer be included after that point, so an unresolved message can never become processable.
## Current limitations[](#current-limitations "Direct link to Current limitations")
* **Senders must self-deliver their own messages.** Messages addressed to the sender (such as the change note in a token transfer) are not processed automatically yet. Call `offchain_receive` for them just like you would on the recipient side.
* **Messages must be bound to a transaction.** Messages without an associated transaction hash are not processed in the current version; they sit in the inbox until they expire.
* **Batch size**: A single `offchain_receive` call accepts at most 16 messages. Split larger sets into multiple calls.
## Testing offchain delivery from Noir[](#testing-offchain-delivery-from-noir "Direct link to Testing offchain delivery from Noir")
The TXE test environment buffers offchain messages emitted during calls and exposes them via `env.offchain_messages()`. Feed them back through `offchain_receive` to complete the delivery loop inside a test:
token\_transfer\_offchain\_delivery\_test
```
#[test]
unconstrained fn transfer_in_private_with_offchain_delivery_updates_both_balances() {
let (env, token_contract_address, owner, recipient, mint_amount) =
utils::setup_and_mint_to_private(/* with_account_contracts */ false);
let transfer_amount = 1000 as u128;
let transfer_call = Token::at(token_contr프로젝트로 돌아가기