> ## Documentation Index
> Fetch the complete documentation index at: https://docs.peaq.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream Edge Agent

> The peaq_ros2_stream node: subscribe to ROS 2 topics, sign and encrypt machine data on the robot, chunk it, store it, anchor it on peaq, and serve it to buyers.

export const KeyTerms = ({all = {}, ids = [], title = "Key terms in this guide"}) => <details className="not-prose my-4 rounded-xl border border-zinc-200 px-4 py-3 dark:border-zinc-800">
    <summary className="cursor-pointer font-medium text-zinc-900 dark:text-zinc-100">
      {title}
    </summary>
    <div className="mt-3 space-y-2 text-sm text-zinc-700 dark:text-zinc-300">
      {ids.map(id => {
  const t = all[id] || ({});
  return <div key={id}>
            <strong>{t.term}.</strong> {t.def}
          </div>;
})}
    </div>
  </details>;

export const G = {
  onchain: {
    id: "onchain",
    cat: "chain-infra",
    term: "On-chain vs off-chain",
    def: "On-chain means written to the shared public ledger every machine agrees on: permanent and readable by anyone. Off-chain means kept on a normal private server instead."
  },
  blockchain: {
    id: "blockchain",
    cat: "chain-infra",
    term: "Chain / blockchain",
    def: "A shared, tamper-resistant public database maintained by a whole network of computers with no single owner. Different chains are separate such networks."
  },
  peaqChain: {
    id: "peaqChain",
    cat: "chain-infra",
    term: "peaq chain",
    def: "The machine-focused blockchain peaqOS uses as home base for identity and credit records."
  },
  transaction: {
    id: "transaction",
    cat: "chain-infra",
    term: "Transaction (tx) / tx hash",
    def: "A single signed request that changes the ledger. Its hash is a unique, receipt-like ID you can use to look it up later."
  },
  rpcUrl: {
    id: "rpcUrl",
    cat: "chain-infra",
    term: "RPC URL / endpoint",
    def: "The network address your code calls to read from or write to a chain, like the base URL of the chain's API server."
  },
  mainnet: {
    id: "mainnet",
    cat: "chain-infra",
    term: "Mainnet / testnet (agung)",
    def: "Mainnet is the real, live network where tokens have real value. Testnet is a free practice copy with worthless tokens; peaq's is called agung."
  },
  evm: {
    id: "evm",
    cat: "chain-infra",
    term: "EVM / EVM-compatible",
    def: "The Ethereum Virtual Machine: the standard runtime many chains share, so the same 0x... addresses and tools work across all of them. peaq is EVM-compatible."
  },
  node: {
    id: "node",
    cat: "chain-infra",
    term: "Node (RPC node)",
    def: "A server running the blockchain software that holds a copy of the ledger and answers queries. NOT a ROS 2 node, despite the shared word."
  },
  chainId: {
    id: "chainId",
    cat: "chain-infra",
    term: "Chain ID",
    def: "A number that uniquely labels a chain so software doesn't confuse networks (peaq is 3338, Base is 8453)."
  },
  precompile: {
    id: "precompile",
    cat: "chain-infra",
    term: "Precompile",
    def: "A built-in function baked into the chain at a fixed address that acts like a contract but runs as faster native code. The batch one bundles several actions into one all-or-nothing transaction."
  },
  dataHash: {
    id: "dataHash",
    cat: "chain-infra",
    term: "Data hash (keccak256)",
    def: "A short, fixed-length fingerprint of a file, stored on-chain instead of the file itself, so data can be verified later while the raw data stays off-chain."
  },
  wallet: {
    id: "wallet",
    cat: "wallet-keys",
    term: "Wallet",
    def: "An account on the chain, identified by a public address, that holds a machine's funds and approves its actions. Really just a pair of keys, not a place money is stored."
  },
  keypair: {
    id: "keypair",
    cat: "wallet-keys",
    term: "Keypair",
    def: "The two matched secrets behind a wallet: a public address you can share, and a private key you keep secret that signs actions."
  },
  privateKey: {
    id: "privateKey",
    cat: "wallet-keys",
    term: "Private key",
    def: "The secret string that proves you control a wallet. Anyone who has it has full control, like a master password that can never be reset."
  },
  sign: {
    id: "sign",
    cat: "wallet-keys",
    term: "Sign / signature",
    def: "Using your private key to produce a cryptographic stamp proving you approved a specific action, without ever revealing the key."
  },
  signer: {
    id: "signer",
    cat: "wallet-keys",
    term: "Signer / signing identity",
    def: "The wallet whose private key authorizes an action: the account the network treats as the one taking it. NOT a file or an app."
  },
  address: {
    id: "address",
    cat: "wallet-keys",
    term: "Address (0x...)",
    def: "The public 0x... identifier of a wallet or contract you can freely share so others can send to it or look it up, like an account number."
  },
  eoa: {
    id: "eoa",
    cat: "wallet-keys",
    term: "EOA (externally owned account)",
    def: "A plain wallet controlled directly by a private key, as opposed to one controlled by code. Here, the account that IS the machine."
  },
  ows: {
    id: "ows",
    cat: "wallet-keys",
    term: "OWS / wallet vault",
    def: "An open standard for storing wallet keys in an encrypted local file (a vault) with a backup phrase and an activity log, instead of a bare key in a text file."
  },
  passphrase: {
    id: "passphrase",
    cat: "wallet-keys",
    term: "Passphrase (OWS_PASSPHRASE)",
    def: "The password that unlocks the encrypted wallet vault so its key can be used to sign."
  },
  mnemonic: {
    id: "mnemonic",
    cat: "wallet-keys",
    term: "Mnemonic / seed phrase",
    def: "A list of 12 or 24 ordinary words that encodes a wallet's secret key, used to back it up and recover it. Whoever has the words controls the wallet."
  },
  derivation: {
    id: "derivation",
    cat: "wallet-keys",
    term: "Derivation path",
    def: "The deterministic recipe that turns one backup phrase into many specific keys and addresses, one per network or index."
  },
  challenge: {
    id: "challenge",
    cat: "wallet-keys",
    term: "Challenge (sign-to-prove)",
    def: "A login-style handshake: the server sends a random message, you sign it with your key, and the signature proves you control the account without sending the key."
  },
  eip191: {
    id: "eip191",
    cat: "wallet-keys",
    term: "EIP-191 / personal_sign",
    def: "A standard way to sign a plain message to prove you control an account, without sending any on-chain transaction."
  },
  did: {
    id: "did",
    cat: "identity",
    term: "DID / peaqID",
    def: "A globally unique, self-owned ID for a machine that lives on the chain and isn't issued by any single company. peaqID is peaq's version, written did:peaq:0x..."
  },
  register: {
    id: "register",
    cat: "identity",
    term: "Register a machine",
    def: "Putting a machine on the network for the first time, which gives it an ID, a DID, an ownership token, and a locked deposit. registerMachine is self-managed; registerFor is on someone else's behalf."
  },
  machineId: {
    id: "machineId",
    cat: "identity",
    term: "Machine ID",
    def: "The number the network assigns your machine when it registers, used as its handle in every later call."
  },
  ownerOperator: {
    id: "ownerOperator",
    cat: "identity",
    term: "Owner / operator",
    def: "The owner owns a machine; the operator runs it. They can be the same account (self-managed) or different (proxy-managed)."
  },
  proxyOperator: {
    id: "proxyOperator",
    cat: "identity",
    term: "Proxy operator",
    def: "One account that registers and manages many machines on behalf of their owners, so a fleet operator can handle a whole fleet from one wallet."
  },
  didAttributes: {
    id: "didAttributes",
    cat: "identity",
    term: "DID attributes",
    def: "Public name-value facts (a docs link, a data endpoint) attached to a machine's DID and stored on-chain for anyone to read. Writing them is a separate transaction from registration."
  },
  pairing: {
    id: "pairing",
    cat: "identity",
    term: "Pairing / pairing token",
    def: "The verified link between an AI agent and a machine, set up by signing a challenge. The pairing token is the signed credential the agent sends with each request, like a temporary access badge."
  },
  hardwareAttestation: {
    id: "hardwareAttestation",
    cat: "identity",
    term: "Hardware attestation",
    def: "A tamper-resistant chip on the machine cryptographically vouching that it's genuine hardware, so its identity can't be faked in software. This is the Verify layer."
  },
  gas: {
    id: "gas",
    cat: "tokens-economics",
    term: "Gas",
    def: "The small fee, paid in the chain's token, that every action writing to the ledger costs, like a per-write transaction cost."
  },
  peaqToken: {
    id: "peaqToken",
    cat: "tokens-economics",
    term: "PEAQ (token)",
    def: "The peaq network's own token, used to pay gas fees and to lock up as the deposit when registering a machine."
  },
  gasStation: {
    id: "gasStation",
    cat: "tokens-economics",
    term: "Gas Station / faucet",
    def: "A peaq service that hands a brand-new, empty wallet a tiny starting amount of tokens so it can afford its first network fees. Gated by 2FA."
  },
  bond: {
    id: "bond",
    cat: "tokens-economics",
    term: "Bond",
    def: "A refundable deposit (currently 1 PEAQ) you lock up to register a machine, proving skin in the game, like a security deposit. Bonded means the deposit is in place."
  },
  nft: {
    id: "nft",
    cat: "tokens-economics",
    term: "NFT",
    def: "A unique, one-of-a-kind ownership token recorded on the chain. Unlike a coin, no two are interchangeable."
  },
  mint: {
    id: "mint",
    cat: "tokens-economics",
    term: "Mint / minting",
    def: "Creating a brand-new token on the chain and assigning it to an owner, like stamping a fresh serial-numbered certificate into existence."
  },
  machineNft: {
    id: "machineNft",
    cat: "tokens-economics",
    term: "Machine NFT",
    def: "The unique token representing one specific physical machine and its financial profile. It can be sold or bridged on its own, separate from the machine's identity."
  },
  identityNft: {
    id: "identityNft",
    cat: "tokens-economics",
    term: "Identity NFT",
    def: "A non-transferable (soulbound) token minted automatically when a machine registers, representing its identity. Its token ID equals the machine ID."
  },
  tokenId: {
    id: "tokenId",
    cat: "tokens-economics",
    term: "Token ID",
    def: "The unique number identifying one specific token within a collection, like a serial number."
  },
  mcr: {
    id: "mcr",
    cat: "tokens-economics",
    term: "Machine Credit Rating (MCR)",
    def: "A creditworthiness score for a machine (a Moody's-style grade AAA down to NR, plus a 0-100 number) computed from its recorded earnings and activity. Like a credit score for a robot."
  },
  mcrApi: {
    id: "mcrApi",
    cat: "tokens-economics",
    term: "MCR API",
    def: "The public web service you call to fetch a machine's credit score and profile as JSON. No login needed."
  },
  provisioned: {
    id: "provisioned",
    cat: "tokens-economics",
    term: "Provisioned / NR (Not Rated)",
    def: "Early MCR statuses. Provisioned means registered and bonded but with too little history to score yet. NR means no grade, because the score is too low or the machine isn't bonded."
  },
  event: {
    id: "event",
    cat: "tokens-economics",
    term: "Event (revenue / activity)",
    def: "A recorded data point about a machine's work, submitted to the chain to feed its credit score. Revenue events report money earned; activity events report work with no money. NOT a ROS topic message."
  },
  trustLevel: {
    id: "trustLevel",
    cat: "tokens-economics",
    term: "Trust level",
    def: "A label on each submitted event saying how strongly its truth is backed: the machine's word (0), a checkable on-chain record (1), or tamper-proof hardware proof (2)."
  },
  escrow: {
    id: "escrow",
    cat: "tokens-economics",
    term: "Escrow",
    def: "Holding a buyer's payment in a neutral locked place until the service is delivered, then releasing it, so neither side has to trust the other first."
  },
  paymentRail: {
    id: "paymentRail",
    cat: "tokens-economics",
    term: "Payment rail",
    def: "The specific method or channel a payment moves through, like choosing card vs bank transfer vs a particular token."
  },
  x402: {
    id: "x402",
    cat: "tokens-economics",
    term: "x402",
    def: "A web payment standard where a server answers 'payment required' with exact instructions, and the buyer's wallet signs an authorization instead of sending a separate transaction — built for machines and agents paying per request."
  },
  usdt: {
    id: "usdt",
    cat: "tokens-economics",
    term: "USDT",
    def: "A stablecoin token meant to hold a value of one US dollar, used to pay service providers without price swings."
  },
  fractionalize: {
    id: "fractionalize",
    cat: "tokens-economics",
    term: "Fractionalize (ERC-3643)",
    def: "Splitting ownership of one machine into many small tradable shares so multiple people can each own a piece. ERC-3643 is the regulated-securities token standard used to do it."
  },
  smartContract: {
    id: "smartContract",
    cat: "smart-contracts",
    term: "Smart contract / contract address",
    def: "A program deployed on the chain that runs exactly as written and that anyone can call, identified by its own 0x... address."
  },
  registryContracts: {
    id: "registryContracts",
    cat: "smart-contracts",
    term: "Registry contracts",
    def: "On-chain programs that each keep an official, lookup-able list: IdentityRegistry tracks which machines exist, EventRegistry stores their events, IdentityStaking holds their deposits."
  },
  smartAccount: {
    id: "smartAccount",
    cat: "smart-contracts",
    term: "Smart account (ERC-4337)",
    def: "A programmable wallet controlled by code instead of a single key, so it can enforce rules like spending limits. Each machine gets one at activation."
  },
  submitEvent: {
    id: "submitEvent",
    cat: "smart-contracts",
    term: "submitEvent / batchSubmitEvents",
    def: "The calls that record one or many of a machine's revenue or activity entries onto the chain."
  },
  revert: {
    id: "revert",
    cat: "smart-contracts",
    term: "Revert",
    def: "When an on-chain call is rejected and fully undone because a rule was broken, leaving no changes and usually a named error."
  },
  soulbound: {
    id: "soulbound",
    cat: "smart-contracts",
    term: "Soulbound",
    def: "A token that can never be transferred or sold and stays permanently attached to one owner. The Identity NFT is soulbound."
  },
  bridge: {
    id: "bridge",
    cat: "cross-chain",
    term: "Bridge / bridging",
    def: "Moving a token from one chain to another, so the same Machine NFT can exist on a different chain. peaq and Base are live today; bridging is mainnet-only."
  },
  base: {
    id: "base",
    cat: "cross-chain",
    term: "Base",
    def: "Another blockchain network (built by Coinbase) that peaqOS can move Machine NFTs to and from. Paying fees on Base needs Base ETH."
  },
  omniChain: {
    id: "omniChain",
    cat: "cross-chain",
    term: "Omni-chain / cross-chain",
    def: "Working across many separate chains at once, so a machine's identity and credit created on peaq can be read or used on other chains."
  },
  homeChain: {
    id: "homeChain",
    cat: "cross-chain",
    term: "Home chain",
    def: "The chain where a record's canonical, authoritative copy lives. For peaqOS that is peaq chain; every other chain holds a mirror."
  },
  satelliteChain: {
    id: "satelliteChain",
    cat: "cross-chain",
    term: "Satellite chain",
    def: "A chain carrying a read-only, automatically synced mirror of home-chain records, so apps there can use them without crossing back to the home chain."
  },
  sourceChainId: {
    id: "sourceChainId",
    cat: "cross-chain",
    term: "sourceChainId / sourceTxHash",
    def: "Two fields recording which chain an action happened on and its hash there, so a cross-chain event can be traced back and verified."
  },
  machineAgent: {
    id: "machineAgent",
    cat: "general-web3",
    term: "Machine Agent",
    def: "A third-party AI program (Claude, OpenAI, a custom bot) paired to a machine and given limited permission to find, buy, and pay for services on its behalf."
  },
  delegationPolicy: {
    id: "delegationPolicy",
    cat: "general-web3",
    term: "Delegation policy",
    def: "The rules an owner gives an AI agent that cap how much it can spend per transaction and per day and which services it may use, so it transacts within guardrails."
  },
  machineMarkets: {
    id: "machineMarkets",
    cat: "general-web3",
    term: "Machine Markets / Service Registry",
    def: "peaqOS's marketplace where machines list services they offer (Service Registry) and where agents discover, order, pay for, and run services from others."
  },
  sdk: {
    id: "sdk",
    cat: "general-web3",
    term: "SDK (peaq-os-sdk)",
    def: "peaq's code library (Python and JS) you install to call all this functionality without writing low-level blockchain calls yourself."
  },
  stream: {
    id: "stream",
    cat: "data-stream",
    term: "Stream (Data-as-a-Service)",
    def: "The peaqOS function where a machine sells the data it generates: it signs the data, encrypts what's sensitive, and grants buyers access. Selling data, as opposed to selling services (that's Monetize)."
  },
  edgeAgent: {
    id: "edgeAgent",
    cat: "data-stream",
    term: "peaqOS Edge Agent",
    def: "Software that runs on the machine itself (as a ROS 2 node) and signs, encrypts, and ships the data it produces. The on-machine half of Stream."
  },
  dataPackage: {
    id: "dataPackage",
    cat: "data-stream",
    term: "Signed data package",
    def: "A bundle of machine data stamped with the machine's identity (DID, timestamp, sequence number) and a signature, so anyone can prove which machine produced it and that it wasn't altered."
  },
  dataEventMap: {
    id: "dataEventMap",
    cat: "data-stream",
    term: "Data Event Map",
    def: "The policy file a machine owner writes to control what streams out: which topics to read, which fields to keep, drop, or encrypt, and where the signed data goes."
  },
  chunk: {
    id: "chunk",
    cat: "data-stream",
    term: "Chunk",
    def: "A bounded, individually encrypted slice of a data stream (by time window or size). The unit a buyer actually purchases and decrypts."
  },
  chunkChain: {
    id: "chunkChain",
    cat: "data-stream",
    term: "Chunk chain",
    def: "A run of chunks linked in order, each referencing the one before it, so missing, reordered, or edited chunks are detectable. Tamper-evidence for a continuous stream."
  },
  manifest: {
    id: "manifest",
    cat: "data-stream",
    term: "Manifest",
    def: "A signed record describing a chunk or dataset — its hashes, storage location, and encryption details — without the data itself. Buyers verify the manifest before trusting or buying."
  },
  dataset: {
    id: "dataset",
    cat: "data-stream",
    term: "Dataset",
    def: "A group of chunks for one topic and time range, packaged for sale with a single fingerprint (a Merkle root) that covers every chunk in it."
  },
  merkleRoot: {
    id: "merkleRoot",
    cat: "data-stream",
    term: "Merkle root",
    def: "One short hash that stands in for a whole set of items, letting you later prove a specific chunk belongs to a dataset without revealing the rest."
  },
  envelopeEncryption: {
    id: "envelopeEncryption",
    cat: "data-stream",
    term: "Envelope encryption / key wrapping",
    def: "Encrypt the data once with a random key, then lock that key separately for each authorized reader. Granting a buyer access re-locks the key to their public key — the data itself is never re-encrypted."
  },
  accessGrant: {
    id: "accessGrant",
    cat: "data-stream",
    term: "Access grant",
    def: "What a buyer receives after paying: the chunk keys they bought, each locked to their public key. They unlock with their private key and decrypt only those chunks."
  },
  contextProvider: {
    id: "contextProvider",
    cat: "data-stream",
    term: "Context Provider",
    def: "A third party that buys machine data, normalizes it into datasets, and serves or resells it (for example, for AI training). The buyer side of Stream, such as DataHive."
  },
  walrus: {
    id: "walrus",
    cat: "chain-infra",
    term: "Walrus",
    def: "A decentralized storage network where encrypted data chunks can be parked, referenced by walrus:// links. The data stays off the blockchain; only its reference and fingerprint are tracked on-chain."
  },
  solana: {
    id: "solana",
    cat: "cross-chain",
    term: "Solana",
    def: "A high-throughput blockchain. peaqOS wallets can hold a Solana account and sign Solana transactions, and machine-economy payments can settle there."
  }
};

The **Stream Edge Agent** is the on-machine half of [Stream](/peaqos/functions/stream). It is a ROS 2 node (`stream_agent_node`, package `peaq_ros2_stream`) that subscribes to the topics you allow, applies <Tooltip tip={G.dataEventMap.def}>Data Event Map</Tooltip> field rules, then signs, encrypts, and <Tooltip tip={G.chunk.def}>chunks</Tooltip> each message, stores the ciphertext, posts a signed <Tooltip tip={G.manifest.def}>manifest</Tooltip> to the Stream backend, anchors the payload hash on peaq, and serves purchased chunks to buyers. Keys never leave the machine in the clear, and the agent publishes no ROS topics.

It runs alongside the [`peaqos_node` runtime](/peaqos/sdk-reference/ros2/overview): the runtime provides the machine's identity and the `events/submit` service the agent calls to anchor data on-chain. For the trust model behind the chunks, see [Data streams](/peaqos/concepts/data-streams).

<KeyTerms all={G} ids={["edgeAgent", "dataEventMap", "dataPackage", "chunk", "chunkChain", "manifest", "envelopeEncryption", "accessGrant", "walrus", "did"]} />

## How it works

```mermaid theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
flowchart LR
  Topics["ROS 2 topics"] -->|subscribe| Agent["stream_agent_node"]
  Policy["Data Event Map<br/>(YAML)"] -->|configures| Agent
  Agent -->|field rules + sign<br/>+ encrypt + chunk| Store["Storage adapter<br/>local / Walrus / S3 / Drive"]
  Agent -->|signed manifest| Backend["Stream backend"]
  Agent -->|payload hash| Node["peaqos_node<br/>events/submit → peaq"]
  Backend -->|paid order| Agent
  Agent -->|re-wrap keys + serve| Buyer["Buyer"]
```

Per inbound message: **capture → field transform → sign → encrypt → chunk → store → post manifest → anchor on-chain**. When an order is paid, the agent re-wraps that buyer's chunk keys and serves the encrypted chunks from a local delivery server.

## Install and run

The agent lives in `peaq_ros2_stream` and depends on `peaq_ros2_interfaces` (for the `PeaqosSubmitEvent` service). ROS 2 Humble (Docker image) or Jazzy (native host) are both supported.

<Note>
  `peaq_ros2_stream` currently ships on the `feature/peaqos-ros2-runtime` branch and merges to the default branch shortly, so the clone below checks that branch out. Once it lands on the default branch, the `git checkout` step is no longer needed.
</Note>

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
git clone https://github.com/peaqnetwork/peaq-robotics-ros2.git
cd peaq-robotics-ros2
git checkout feature/peaqos-ros2-runtime   # Stream package lives here until it merges to the default branch

source /opt/ros/jazzy/setup.bash
# Use /opt/ros/humble/setup.bash inside the Docker image.

colcon build --packages-select peaq_ros2_interfaces peaq_ros2_stream
source install/setup.bash
```

Start it with the launch file (which declares the `config_yaml` argument):

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
ros2 launch peaq_ros2_stream stream_agent.launch.py \
  config_yaml:=/path/to/stream_config.yaml
```

Or run the node directly:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
ros2 run peaq_ros2_stream stream_agent_node --ros-args \
  -p config.yaml_path:=/path/to/stream_config.yaml
```

Python dependencies (installed by `rosdep` or `pip`): `PyNaCl`, `PyYAML`, `boto3`, `google-api-python-client`, `google-auth`, `requests`. The agent is inert until `stream_agent.enabled` is `true`.

<Note>
  Configuration resolves in this order, last wins: built-in defaults → the `config_yaml` file → `PEAQOS_STREAM_*` environment variables → ROS parameters → an optional standalone `policy_path` file.
</Note>

## Configure: the Data Event Map

The agent reads one YAML block, `stream_agent` (the alias `stream` also works; keys accept snake\_case or camelCase). This is the [Data Event Map](/peaqos/concepts/data-streams): what to read, how to protect each field, where ciphertext goes, and who can decrypt.

```yaml stream_config.yaml theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
stream_agent:
  enabled: true                                  # inert unless true

  # Identity + backend (all four required when enabled)
  machine_id: "mach_01HXYZ"
  agent_id: "agent_ros2_stream"
  agent_token: "stk_live_xxx"                     # per-agent secret — prefer env/policy file
  identity_ref: "did:peaq:0xMACHINE"              # written into every manifest signature
  api_base_url: "https://stream.peaq.network"     # default http://127.0.0.1:8000
  api_key: ""                                     # optional; sent as Bearer

  # Topic subscriptions + per-field rules
  topics:
    - topic: "/battery_state"
      message_type: "sensor_msgs/msg/BatteryState"
      qos_preset: "sensor_data"                   # default | sensor_data | reliable
      field_rules:                                # ordered
        - { path: "voltage",        action: "include" }
        - { path: "serial_number",  action: "hash" }
        - { path: "location",       action: "anonymize" }
        - { path: "raw_cells",      action: "exclude" }
        - { path: "operator_note",  action: "encrypt", public_key_hex: "aa11…(32 bytes)" }
    - topic: "/cmd_vel"
      message_type: "geometry_msgs/msg/Twist"
      qos_preset: "reliable"

  # Who can unwrap each chunk's key (≥1 required; buyers are added later, on purchase)
  key_recipients:
    - { recipient_id: "owner-1",    recipient_type: "owner",    public_key_hex: "11…(32 bytes)" }
    - { recipient_id: "operator-1", recipient_type: "operator", public_key_hex: "22…(32 bytes)" }
    - { recipient_id: "mach_01",    recipient_type: "machine",  public_key_hex: "33…(32 bytes)" }

  # Where encrypted chunks go (a local copy is always written first)
  storage:
    backend: "walrus"                             # local | walrus | s3 | google-drive
    walrus:
      publisher_url:  "https://walrus-publisher.example"
      aggregator_url: "https://walrus-aggregator.example"
      epochs: 5
      permanent: true

  # Anchor each payload hash on peaq via the peaqos_node runtime
  peaqos_event:
    enabled: true
    node_name: "peaqos_node"                      # → /peaqos_node/events/submit
    machine_id: 42                                # on-chain machine id (uint64)
    trust_level: 0

  # Local HTTP server that serves purchased chunks to buyers
  delivery:
    enabled: true
    host: "127.0.0.1"
    port: 8765
    token: "deliver_xxx"                          # required when delivery.enabled
```

Validation is strict: when `enabled`, `machine_id` / `agent_id` / `agent_token` / `identity_ref` and at least one topic and one key recipient are required; `recipient_type` is `machine` / `owner` / `operator`; each `public_key_hex` is a 32-byte (64-hex) x25519 key; `storage.backend` outside the known set falls back to `local`; `delivery.token` is required if delivery is on.

Local state defaults under `~/.peaq_robot/` (signing key, sequence counters, chunk `.bin` files, manifests, the SQLite catalog and key store) and is configurable per path. An offline `buffer` (SQLite) holds envelopes when the backend is unreachable and drains on a retry timer.

## Field rules

Rules run **before** signing, so protected fields never leave the machine in the clear while the package stays verifiable. Rules are ordered; if any `include` rule is present the agent starts from an allow-list, otherwise from the full message.

| Action      | Effect                                                                                               |
| :---------- | :--------------------------------------------------------------------------------------------------- |
| `include`   | Keep the field as-is (and, if used, allow-list it).                                                  |
| `exclude`   | Drop the field entirely.                                                                             |
| `hash`      | Replace the value with `sha256:<hex>`.                                                               |
| `anonymize` | Replace the value with `{ "redacted": true }`.                                                       |
| `encrypt`   | Seal the value to the rule's `public_key_hex` (x25519 sealed box); only that key holder can read it. |

## How a message becomes a sellable chunk

1. **Capture.** The subscription fires; the ROS message is converted to a canonical ordered dict.
2. **Transform.** Field rules apply (above).
3. **Sequence.** A monotonic per-(machine, topic, policy version) number is assigned.
4. **Sign.** The agent builds a `peaqos-stream-envelope@v1` carrying the `payloadHash` and signs it with the machine's **Ed25519** key (`signature.keyId`, `algorithm: "ed25519"`).
5. **Encrypt.** The transformed payload is encrypted with a fresh per-chunk **XChaCha20-Poly1305** key (32-byte key, 24-byte nonce), yielding `plaintextHash`, `encryptedDataHash`, and a `keyCommitment`.
6. **Chunk ID.** A deterministic `sha256:` id is computed over `{ schemaVersion, previousChunkId, index, plaintextHash, encryptedDataHash }`, forming a hash <Tooltip tip={G.chunkChain.def}>chain</Tooltip>.
7. **Store.** The chosen adapter writes the ciphertext and returns a `storageRef`.
8. **Manifest.** A `peaq.stream.chunks.v1` manifest wraps the chunk key to every `key_recipient` (x25519 sealed box) and is Ed25519-signed over `encryptedDataHash`, then `POST`ed to `/api/v1/stream/chunks`. The envelope is `POST`ed to `/api/v1/stream/events`, returning a receipt.
9. **Anchor.** If `peaqos_event.enabled`, the agent calls `/peaqos_node/events/submit` (`PeaqosSubmitEvent`) with the payload hash as `raw_data_hex` and `{ streamReceiptId, policyId, policyVersion }` as `metadata_hex`, then patches the receipt with the returned `txHash`.

On startup the agent syncs its policy to the backend and registers its Ed25519 **public** key (`keyId = {agent_id}-stream-ed25519`).

## Storage adapters

Every adapter writes the local `.bin` first (so the delivery server always has a copy), then pushes to the remote.

| Backend        | Required config                                       | `storageRef`                      |
| :------------- | :---------------------------------------------------- | :-------------------------------- |
| `local`        | `chunk_storage_path`                                  | `file://<abs-path>`               |
| `walrus`       | `walrus.publisher_url` (+ `aggregator_url` for reads) | `walrus://<blobId>`               |
| `s3`           | `s3.bucket` (+ region / endpoint / creds)             | `s3://<bucket>/<prefix>/<id>.bin` |
| `google-drive` | `google_drive.folder_id` + `credentials_path`         | `gdrive://<fileId>`               |

## On-chain anchoring

Anchoring is optional and runs through the `peaqos_node` runtime, so that node must be up with `events/submit` available. The agent submits only the **payload hash** plus non-secret metadata — never raw data or keys — producing a tamper-evident on-chain record that links each Stream receipt to a peaq <Tooltip tip={G.transaction.def}>transaction</Tooltip>.

## Selling and delivery

The agent polls the backend for orders. When an order is `paid`, it looks up each purchased chunk's symmetric key from the local key store, re-wraps it to the buyer's public key (x25519 sealed box, `peaq.stream.buyer-access.v1`), and submits the <Tooltip tip={G.accessGrant.def}>access grant</Tooltip>. The chunk data is never re-encrypted.

If `delivery.enabled`, a token-gated local HTTP server serves the encrypted chunks:

| Route                       | Returns                                      |
| :-------------------------- | :------------------------------------------- |
| `GET /health`               | `{ ok: true }`                               |
| `GET /chunks`               | Catalog list (filter by topic, time, status) |
| `GET /chunks/{id}/manifest` | The `peaq.stream.chunks.v1` manifest         |
| `GET /chunks/{id}/data`     | Raw encrypted bytes (supports HTTP Range)    |

## Environment variables

Every config field has a `PEAQOS_STREAM_*` override (applied above the YAML file, below ROS params) — use them to keep secrets out of committed YAML. The essentials:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
export PEAQOS_STREAM_ENABLED=true
export PEAQOS_STREAM_API_BASE_URL=https://stream.peaq.network
export PEAQOS_STREAM_MACHINE_ID=mach_01HXYZ
export PEAQOS_STREAM_AGENT_ID=agent_ros2_stream
export PEAQOS_STREAM_AGENT_TOKEN=stk_live_xxx
export PEAQOS_STREAM_IDENTITY_REF=did:peaq:0xMACHINE
export PEAQOS_STREAM_STORAGE_BACKEND=walrus
```

Storage credentials also accept the standard vendor variables: Walrus (`WALRUS_PUBLISHER_URL`, …), S3 (`AWS_ACCESS_KEY_ID`, `AWS_REGION`, `AWS_ENDPOINT_URL_S3`, …), and Google Drive (`GOOGLE_APPLICATION_CREDENTIALS`, `GOOGLE_DRIVE_FOLDER_ID`).

## Security

* The **Ed25519 signing key** is generated on first run, written to `signing_key_path` (`0600`), and never sent or logged — only the public key is registered and embedded in manifests.
* **Per-chunk symmetric keys** live only in the local SQLite key store and travel only as sealed-box-wrapped blobs (to recipients, then to the buyer). Plaintext keys never appear in ROS messages, manifests, the backend payload, or logs.
* **No secrets cross ROS.** The agent publishes no topics; its only ROS egress is the `events/submit` service call, which carries a hash and non-secret metadata.
* The delivery server silences request logging and gates every route except `/health` behind `delivery.token`. Keep `agent_token`, `api_key`, `delivery.token`, and storage credentials in environment variables, not committed YAML.

## Related

* [Stream function](/peaqos/functions/stream)
* [Data streams concept](/peaqos/concepts/data-streams)
* [ROS 2 overview](/peaqos/sdk-reference/ros2/overview)
* [Stream SDK reference](/peaqos/sdk-reference/stream)
* [peaqOS CLI: `peaqos stream`](/peaqos/cli#peaqos-stream)
