Metadata-Version: 2.4
Name: swarm-provenance-cli
Version: 0.13.0
Summary: A CLI toolkit for wrapping data and uploading to Swarm.
License-Expression: MIT
Project-URL: Homepage, https://github.com/datafund/swarm_provenance_CLI
Project-URL: Repository, https://github.com/datafund/swarm_provenance_CLI
Project-URL: Issues, https://github.com/datafund/swarm_provenance_CLI/issues
Project-URL: Documentation, https://github.com/datafund/swarm_provenance_CLI#readme
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: typer<0.23,>=0.12
Requires-Dist: click<8.2.0,>=8.1.0
Requires-Dist: pydantic>=2.5.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: requests>=2.31.0
Provides-Extra: testing
Requires-Dist: pytest>=7.4; extra == "testing"
Requires-Dist: pytest-mock>=3.12; extra == "testing"
Requires-Dist: requests-mock>=1.11; extra == "testing"
Provides-Extra: x402
Requires-Dist: eth-account>=0.13.5; extra == "x402"
Requires-Dist: web3<9,>=7.0.0; extra == "x402"
Provides-Extra: blockchain
Requires-Dist: web3<9,>=7.0.0; extra == "blockchain"
Requires-Dist: eth-account>=0.13.5; extra == "blockchain"
Dynamic: license-file

# Swarm Provenance Uploader

[![CI](https://github.com/datafund/swarm_provenance_CLI/actions/workflows/ci.yml/badge.svg)](https://github.com/datafund/swarm_provenance_CLI/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.txt)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)

A CLI toolkit to wrap data files within a metadata structure
and upload them to the Swarm decentralized storage network.

> **Alpha software.** It comes with no guarantees, and refunds should not be expected. Spend small amounts, and test on the staging gateway or the free tier (`--free`) first. **The default gateway charges real USDC on Base mainnet** for paid requests (see [x402 payment mode](#x402-payment-mode-optional)). Send feedback to info@datafund.io.

**For AI agents:** read [AGENTS.md](AGENTS.md) and the skill in [skills/swarm-provenance-cli/SKILL.md](skills/swarm-provenance-cli/SKILL.md).

**Supports two backends:**
- **Gateway** (default): Uses `provenance-gateway.datafund.io` - no local Bee node required
- **Local**: Direct Bee node communication for development/self-hosted setups

## Quick start

```bash
# Install from PyPI (published from 0.13.0). Alpha software: for paid requests,
# the default gateway charges real USDC on Base mainnet (see the note above).
pip install swarm-provenance-cli

# With extras: [x402] for payments, [blockchain] for on-chain anchoring
pip install "swarm-provenance-cli[x402,blockchain]"

# Or from a release tag (v0.13.0 or later; earlier tags have the old
# distribution name) or a commit SHA, without PyPI
pip install "swarm-provenance-cli[x402] @ git+https://github.com/datafund/swarm_provenance_CLI@<release-tag>"

# Or, for development, from a clone of this repository
pip install -e .

# Check version
swarm-prov-upload --version

# Check connectivity
swarm-prov-upload health

# The default gateway charges for stamps and uploads (real USDC on Base mainnet).
# These examples use the free tier (--free, rate-limited) or FREE_TIER=true; leave
# X402_AUTO_PAY unset. With x402 enabled, a payment request that the gateway sends
# instead is handled like any other: the CLI asks, or with auto-pay pays without a
# prompt when the amount is within your auto-pay limit (on Base mainnet, a limit
# set with --max-pay or X402_MAX_AUTO_PAY_USD). Or pay with test USDC on the
# staging gateway (see "x402 payment mode" below).

# Upload data (purchases stamp with 25 hour validity)
swarm-prov-upload --free upload --file /path/to/data.txt

# Upload using pooled stamp (faster, ~5s vs >1min)
swarm-prov-upload --free upload --file /path/to/data.txt --usePool

# Upload with custom duration (hours)
swarm-prov-upload --free upload --file /path/to/data.txt --duration 48

# Upload with size preset (small, medium, large)
swarm-prov-upload --free upload --file /path/to/data.txt --size medium

# Upload with existing stamp (skip purchase)
swarm-prov-upload --free upload --file /path/to/data.txt --stamp-id <existing_stamp_id>

# Upload to a stamp your x402 wallet bought, without paying again
swarm-prov-upload --free upload --file /path/to/data.txt --stamp-id <your_stamp_id> --owner-proof

# Download (checks content hash and notary signature)
swarm-prov-upload download <swarm_hash> --output-dir ./downloads

# Upload with notary signing (gateway only)
swarm-prov-upload --free upload --file /path/to/data.txt --sign notary

# Download (a notary signature that does not verify fails the download)
swarm-prov-upload download <swarm_hash> --output-dir ./downloads

# Also fail if the document carries no notary signature, and pin the notary
swarm-prov-upload download <swarm_hash> --output-dir ./downloads --require-signature --notary-address 0x...

# Download without signature verification
swarm-prov-upload download <swarm_hash> --output-dir ./downloads --no-verify
```

The distribution was named `swarm-provenance-uploader` before 0.13.0 and was never published on PyPI under that name. The import package (`swarm_provenance_uploader`) and the command (`swarm-prov-upload`) are unchanged.

## Setup

1. Create and activate a virtual environment.
   ```bash
   python -m venv .venv
   source .venv/bin/activate
   # Or on Windows: .\venv\Scripts\activate
   ```
2. Copy `.env.example` to `.env` and adjust values if needed.
   ```bash
   cp .env.example .env
   ```
   The CLI reads the `.env` of the folder you run it in. If there is none, it uses the nearest `.env` in a parent folder (up to the root, including your home folder). The folder the package is installed in does not matter. Variables already set in your environment take precedence over `.env`. Versions up to 0.12.0 searched from the folder the package was installed in, so with an editable install the repository's `.env` applied everywhere. If you relied on that, copy the `.env` to the folder you work in, or export the variables. When a `.env` is found, every command prints its path on stderr (`Loaded settings from <path>`), followed by the names, never the values, of any payment, gateway or key-selecting settings it supplied (`Payment settings taken from that file: ...`; these are `X402_ENABLED`, `X402_AUTO_PAY`, `X402_MAX_AUTO_PAY_USD`, `X402_NETWORK`, `X402_EXPECTED_PAY_TO`, `PROVENANCE_GATEWAY_URL`, `X402_RPC_URL`, `X402_PRIVATE_KEY_ENV`, `CHAIN_WALLET_KEY_ENV`, `X402_PRIVATE_KEY`, `SWARM_X402_PRIVATE_KEY` and `PROVENANCE_WALLET_KEY`, plus the variable that `X402_PRIVATE_KEY_ENV` or `CHAIN_WALLET_KEY_ENV` names when the file supplies it); a setting already set in your environment is not listed. The notice also appears before a subcommand's `--help`, but not before `swarm-prov-upload --help`.
3. Install in editable mode, including testing dependencies:
   ```bash
   pip install -e .[testing]
   ```

## Backend configuration

### Gateway backend (default)
No local Bee node required. Uses the Datafund provenance gateway.

The default gateway charges for stamps and uploads in real USDC on Base mainnet. The examples below use the free tier (`--free`); you can also set `FREE_TIER=true`. Leave `X402_AUTO_PAY` unset: with x402 enabled, a payment request that the gateway sends instead of serving the free tier is handled like any other: the CLI asks, or with auto-pay pays it without a prompt when the amount is within your auto-pay limit (on Base mainnet, a limit set with `--max-pay` or `X402_MAX_AUTO_PAY_USD`). You can also pay with `--x402` (see [x402 payment mode](#x402-payment-mode-optional)), or test with test USDC on the staging gateway (`--gateway-url https://provenance-gateway.dev.datafund.io --x402`).

```bash
# Uses gateway by default
swarm-prov-upload --free upload --file data.txt

# Or explicitly
swarm-prov-upload --backend gateway --free upload --file data.txt

# Custom gateway URL
swarm-prov-upload --gateway-url https://custom.gateway.io upload --file data.txt
```

### Local backend
For development or self-hosted Swarm nodes.

```bash
# Use local Bee node
swarm-prov-upload --backend local upload --file data.txt

# Custom Bee URL
swarm-prov-upload --backend local upload --file data.txt --bee-url http://localhost:1633
```

### Uploading to a stamp you own

A stamp bought with an x402 payment belongs to the wallet that paid for it, and the gateway accepts uploads to it only from that wallet. To upload to it without paying again, add `--owner-proof` with `--stamp-id` to `upload` or `upload-collection`:

```bash
swarm-prov-upload upload --file data.txt --stamp-id <your_stamp_id> --owner-proof
swarm-prov-upload upload-collection ./mydir --stamp-id <your_stamp_id> --owner-proof
```

- The CLI signs an owner proof with the x402 key: the key in `X402_PRIVATE_KEY`, in the variable named by `X402_PRIVATE_KEY_ENV`, or in the legacy `SWARM_X402_PRIVATE_KEY`, the same lookup as for payments. `--x402` is not needed. The CLI reads and checks the key before its first request to the gateway (the stamp check): with no key, or a key that is not valid, the command exits with an error and sends nothing. It signs the proof later, just before the upload.
- The upload goes on the free tier (`X-Payment-Mode: free`, with the free tier's rate limit) and is never paid, also with `--x402`. If the gateway asks for a payment anyway, the command stops: no payment is signed or made.
- The proof is valid for 5 minutes from the gateway's clock and covers one upload. The CLI signs a new one for each command, just before the upload.
- The proof lets whoever holds it make one upload to your stamp, so the CLI sends it only to the configured gateway: never over plain `http`, except to this machine (`localhost`, a `127.x.x.x` address or `::1`), and not along a redirect. Over plain `http` to this machine, it ignores proxy settings such as `HTTP_PROXY`, so the proof does not pass through a proxy in cleartext. It never prints the signature.
- Requires `eth-account` (included in the `x402` extra).

If the gateway refuses the proof, the CLI prints its code and message with a hint:

```
ERROR: Owner proof refused: HTTP 401 OWNER_PROOF_INVALID: Owner proof rejected: timestamp is stale or in the future
Check this computer's clock: the gateway accepts an owner proof only within 5 minutes of its own clock ...
ERROR: Upload refused: HTTP 403 STAMP_OWNERSHIP_DENIED: Access denied: stamp owned by 0x12345678..., not accessible to wallet 0xabcdef01...
The x402 wallet 0x... does not own this stamp. A stamp belongs to the wallet that paid for it: set the x402 key of that wallet.
```

If the gateway answers `OWNER_PROOF_INVALID` for any other reason (for example "signature is not valid"), it could not read the proof: something on the way, such as a proxy, may have changed or dropped the `X-Owner-*` headers. Run the command again to sign a new proof. A proof signed with the wrong key is still valid; the gateway answers it with `STAMP_OWNERSHIP_DENIED`.

The hint for `STAMP_OWNERSHIP_DENIED` depends on the gateway's reason:

- "stamp owned by ...": with `--owner-proof`, the hint names the x402 wallet that signed and says that the stamp belongs to the wallet that paid for it. Without `--owner-proof`, on an unpaid upload (`--free`, or x402 off), the hint suggests `--owner-proof`; a paid upload gets no hint, because the payment already identifies the wallet.
- "stamp belongs to the gateway pool": the stamp is pool inventory that nobody owns yet. Take a stamp with `--usePool` instead of `--stamp-id`.
- "stamp is not registered to any owner": no wallet owns the stamp on this gateway, for example because it expired or was bought through another gateway. Use a stamp the gateway lists for your wallet (`stamps list --wallet <address>`), or buy a new one.
- Any other reason: with `--owner-proof`, the hint names the signing wallet; without it, the CLI prints only the gateway's code and message.

With `upload-collection --json`, a refusal by the gateway is `{"error": "upload_failed", "step": "upload", "code": ..., "status": ..., "message": ...}`, for example `"code": "OWNER_PROOF_INVALID", "status": 401`. `status` is also given for an error page the gateway did not write, such as a proxy's 502, and for a refused redirect; `code` is left out when the gateway sent none. The document also has `hint` when the CLI gives one.

### Gateway errors

When the gateway refuses a request, the CLI prints the gateway's error code and message, and the wait time when the gateway sends a `Retry-After` header:

```
ERROR: Failed uploading data: Failed to upload data: HTTP 403 STAMP_OWNERSHIP_DENIED: <message>
ERROR: Failed to list stamps: Failed to list stamps: HTTP 429 RATE_LIMIT_EXCEEDED: Too many requests. Try again in 42 seconds. Retry after 42 s.
```

The code tells you what went wrong (for example `EXTENSION_TOO_SMALL`, `DAILY_STAMP_ALLOWANCE_EXHAUSTED` or `FILE_TOO_LARGE`). Run the command with `--verbose` to also see the request URL. A response the gateway could not explain (for example an HTML error page from a proxy) is shown as the plain HTTP error.

If a request needs payment and x402 is not enabled, the CLI says so: `Use --free for the free tier.`, followed by `Paying with --x402 instead spends real USDC on Base mainnet.` when the gateway's offer is on Base mainnet, or `Paying with --x402 instead spends USDC; on Base mainnet that is real money.` otherwise. When the gateway gives its own reason for the 402, the CLI prints its code and message. If the free daily pool allowance is used up (`DAILY_STAMP_ALLOWANCE_EXHAUSTED` or `DAILY_STAMP_ALLOWANCE_PER_CLIENT_EXHAUSTED`), `--free` does not help with `--usePool`: the pool acquire ignores the free-tier header, and every unpaid acquire counts against that allowance. A direct purchase (without `--usePool`) is not drawn from the pool allowance. When the free tier cannot get past a 402, the CLI lists what you can do instead: wait until the allowance resets (the time the gateway gives), buy a stamp directly without `--usePool` (for a spent pool allowance only; with `--free` when the command did not use it, because an unpaid direct purchase needs the free tier), or test on the staging gateway. It ends with the same real-money line about `--x402`. With `--json`, the `payment_required` document's `message` is that text, and the document also has the gateway's `code` and `resets_at` when the gateway sent them. Where paying would not bypass the allowance (x402 off on the gateway, or a testnet such as the staging gateway), the gateway refuses `--usePool` with HTTP 429 instead. `upload` and `upload-collection` then print the gateway's error and the same list of alternatives, and with `--json` the `upload_failed` document also has `code` and `resets_at`.

### Environment variables

```bash
PROVENANCE_BACKEND=gateway           # gateway (default) or local
PROVENANCE_GATEWAY_URL=https://provenance-gateway.datafund.io
BEE_GATEWAY_URL=http://localhost:1633
DEFAULT_POSTAGE_DEPTH=17
DEFAULT_POSTAGE_DURATION_HOURS=25    # Stamp validity in hours (gateway only, min 24)
DEFAULT_POSTAGE_AMOUNT=1000000000    # Legacy: for local backend
```

## Free tier mode (optional)

For development and testing, use the gateway free tier — no wallet or payment configuration needed. Rate-limited to 3 requests/minute.

```bash
# Upload with free tier
swarm-prov-upload --free upload --file data.txt --std "PROV-STD-V1"

# Health check with free tier
swarm-prov-upload --free health

# Enable via environment variable
export FREE_TIER=true
swarm-prov-upload upload --file data.txt
```

| Environment Variable | Description | Default |
|---------------------|-------------|---------|
| `FREE_TIER` | Use gateway free tier (rate-limited) | `false` |

## x402 payment mode (optional)

x402 enables pay-per-request payments using USDC on Base chain. When the gateway requires payment (HTTP 402), the CLI automatically handles the payment flow.

> **Warning: the default gateway (`https://provenance-gateway.datafund.io`) charges real USDC on Base mainnet.** When `X402_NETWORK` and `--x402-network` are not set, the network follows the gateway: `base` (real USDC) for the default gateway, and `base-sepolia` (test USDC) for the staging gateway and for any other gateway URL. For a custom gateway that charges on Base mainnet, set `X402_NETWORK=base`. A network you set always wins.
> - **To test** without real money, use the staging gateway, which takes test USDC on Base Sepolia: `--gateway-url https://provenance-gateway.dev.datafund.io`. Or use the free tier (`--free`, 3 requests per minute and 3 free small pooled stamps per client per day on the default gateway, no wallet).
>
> The software is alpha: refunds should not be expected. The payer needs USDC but no ETH; the facilitator pays the gas.

### Pay on production (real USDC)

The minimum steps to pay on the default gateway:

1. Install the x402 extra: `pip install -e .[x402]`.
2. Set the wallet key in `X402_PRIVATE_KEY`, read from your password manager for each command (see [docs/x402-setup.md](docs/x402-setup.md#private-key)). Fund the wallet with USDC on Base mainnet.
3. Add `--x402` to the command: `swarm-prov-upload --x402 upload --file data.txt`.
4. Either answer the prompt, or use `--auto-pay` together with `--max-pay`:
   - Without auto-pay, the CLI asks before every payment, whatever the amount, and warns that it pays real USDC. Check the amount before you confirm.
   - With auto-pay, set the per-payment limit explicitly and keep it small: `swarm-prov-upload --x402 --auto-pay --max-pay 0.05 upload --file data.txt`. On Base mainnet, auto-pay is refused before anything is signed unless `--max-pay` or `X402_MAX_AUTO_PAY_USD` is set to a value above 0; the built-in limit of 1.00 does not count.

`swarm-prov-upload x402 status` shows the network in use and where it came from.

### Quick start (staging gateway, test USDC)

```bash
# Install with x402 support
pip install -e .[x402]

# Configure wallet (test USDC on Base Sepolia)
# X402_PRIVATE_KEY: read it from your password manager for each command,
# never export it in your shell (see docs/x402-setup.md#private-key)
export X402_ENABLED=true
# No X402_NETWORK needed: the staging gateway gets base-sepolia (test USDC)

# Check x402 status
swarm-prov-upload x402 status

# Check USDC balance
swarm-prov-upload x402 balance

# Upload through the staging gateway (prompts for payment confirmation)
swarm-prov-upload --gateway-url https://provenance-gateway.dev.datafund.io --x402 upload --file data.txt

# Upload with auto-pay (no prompts, up to $0.05 per payment)
swarm-prov-upload --gateway-url https://provenance-gateway.dev.datafund.io --x402 --auto-pay --max-pay 0.05 upload --file data.txt
```

On the default gateway (real USDC), the same upload is `swarm-prov-upload --x402 upload --file data.txt`: the network follows the gateway, so it pays on `base`. It asks before every payment; check the amount in the prompt before you confirm. See [Pay on production](#pay-on-production-real-usdc).

### x402 commands

```bash
# Show configuration status, including the x402 versions the gateway accepts
swarm-prov-upload x402 status

# Check wallet USDC balance
swarm-prov-upload x402 balance

# Show setup instructions
swarm-prov-upload x402 info
```

### x402 configuration

| Environment Variable | Description | Default |
|---------------------|-------------|---------|
| `X402_ENABLED` | Enable x402 payments | `false` |
| `X402_PRIVATE_KEY` | Wallet private key (keep secret!) | - |
| `X402_PRIVATE_KEY_ENV` | Name of the variable that holds the key. When set to another name, only that variable is read. A value that is not a valid variable name, or that looks like a key, is rejected and not printed | `X402_PRIVATE_KEY` |
| `X402_NETWORK` | `base-sepolia` (test USDC, the staging gateway) or `base` (Base mainnet: what the default production gateway charges, in real USDC). The CAIP-2 ids `eip155:84532` and `eip155:8453` also work | Follows the gateway: `base` for the default gateway, `base-sepolia` for the staging gateway and any other URL |
| `X402_PROTOCOL` | x402 version to pay with: `auto` (x402 v2 when the gateway offers it, else v1), `v1` (`X-PAYMENT` only) or `v2` (`PAYMENT-SIGNATURE` only). A payment request that does not offer the chosen version is refused before anything is signed. The global option `--x402-protocol` overrides it | `auto` |
| `X402_AUTO_PAY` | Auto-pay without prompts | `false` |
| `X402_MAX_AUTO_PAY_USD` | Maximum auto-pay amount per payment, used only with auto-pay. A finite number of 0 or more; `inf`, `nan`, negative and non-numeric values are rejected. On Base mainnet, auto-pay needs this or `--max-pay` set above 0 | `1.00` (counts only on Base Sepolia) |
| `X402_EXPECTED_PAY_TO` | Only pay this recipient address (optional) | not set |
| `X402_RPC_URL` | Custom RPC URL for the USDC balance and EIP-712 domain checks (optional). Like `CHAIN_RPC_URLS`, applies whichever `X402_NETWORK` is selected | Uses the network preset |

The signing key and `x402 status` use the same lookup: the variable named by `X402_PRIVATE_KEY_ENV` if that is set to another name (and nothing else), otherwise `X402_PRIVATE_KEY`, then the legacy `SWARM_X402_PRIVATE_KEY`.

### Global flags

| Flag | Description |
|------|-------------|
| `--free` / `--no-free` | Enable/disable free tier mode |
| `--x402` / `--no-x402` | Enable/disable x402 for this command |
| `--auto-pay` / `--no-auto-pay` | Enable/disable auto-pay |
| `--max-pay FLOAT` | Maximum auto-pay amount in USD per payment, used only with auto-pay (`--auto-pay` or `X402_AUTO_PAY=true`). A finite number of 0 or more; `inf` is rejected. Required, above 0, for auto-pay on Base mainnet (or `X402_MAX_AUTO_PAY_USD`) |
| `--x402-network TEXT` | Network: `base-sepolia` or `base` (or the CAIP-2 ids `eip155:84532` and `eip155:8453`). Overrides `X402_NETWORK`; without either, the network follows the gateway |
| `--idempotency-key TEXT` | Idempotency-Key for this command's paid requests; pass the key printed by a failed run to repeat it without paying twice (on a gateway that supports it) |

### Testnet setup (staging gateway)

Test USDC works only with the staging gateway, `https://provenance-gateway.dev.datafund.io` (pass it with `--gateway-url` or `PROVENANCE_GATEWAY_URL`). The default gateway charges real USDC on Base mainnet. The staging gateway stores on the real Swarm network and is meant for integration testing only.

1. **Get testnet USDC**: https://faucet.circle.com/ (Base Sepolia). No ETH is needed: the facilitator pays the gas.
2. **Configure wallet**: Set `X402_PRIVATE_KEY` with your wallet's private key
3. **Point the CLI at staging**: `--gateway-url https://provenance-gateway.dev.datafund.io`. With `X402_NETWORK` not set, the network follows the gateway and is `base-sepolia`

See [docs/x402-setup.md](docs/x402-setup.md) for detailed setup instructions.

## Blockchain anchoring (optional)

On-chain provenance anchoring registers Swarm hashes on the DataProvenance smart contract (Base chain), providing immutable proof of data registration, ownership, and transformation lineage.

### Quick start

```bash
# Install with blockchain support
pip install -e .[blockchain]

# Configure wallet
# PROVENANCE_WALLET_KEY: read it from your password manager for each command,
# never export it in your shell (see docs/chain-setup.md#private-key)
export CHAIN_NAME=base-sepolia      # Testnet (default)

# Check wallet balance
swarm-prov-upload chain balance

# Anchor a Swarm hash on-chain
swarm-prov-upload chain anchor <swarm_hash>

# Get the on-chain provenance record
swarm-prov-upload chain get <swarm_hash>

# Verify a hash is anchored
swarm-prov-upload chain verify <swarm_hash>
```

### Chain commands

```bash
# Wallet balance and chain info
swarm-prov-upload chain balance
swarm-prov-upload chain balance --json

# Anchor a Swarm hash on-chain
swarm-prov-upload chain anchor <swarm_hash>
swarm-prov-upload chain anchor <swarm_hash> --type "dataset"
swarm-prov-upload chain anchor <swarm_hash> --owner <address>  # anchor as delegate
swarm-prov-upload chain anchor <swarm_hash> --storage-ref <ref>  # anchor with Swarm storage reference
swarm-prov-upload chain anchor <swarm_hash> --gas 500000      # explicit gas limit, at least 21000; a transaction that would revert is still sent (see CHAIN_GAS_LIMIT below)

# Record data access
swarm-prov-upload chain access <swarm_hash>

# Record a data transformation (original must be anchored first)
swarm-prov-upload chain transform <original_hash> <new_hash> --description "Anonymized PII"
swarm-prov-upload chain transform <orig> <new> --restrict-original  # restrict original after transform

# Record an N-to-1 merge transformation (all sources must be anchored; needs contract v2 or later)
swarm-prov-upload chain merge <hash1> <hash2> [<hash3>...] <new_hash> --description "Merged datasets"

# Get full provenance record
swarm-prov-upload chain get <swarm_hash>
swarm-prov-upload chain get <swarm_hash> --json
swarm-prov-upload chain get <swarm_hash> --follow           # walk transformation chain
swarm-prov-upload chain get <swarm_hash> --follow --depth 3 # limit traversal depth (1-50, default 10; new in v0.13.0)

# Verify a hash is registered on-chain (exit code 0=yes, 1=no); prints its status and owner
swarm-prov-upload chain verify <swarm_hash>
swarm-prov-upload chain verify <swarm_hash> --require-active   # exit 1 if RESTRICTED or DELETED
swarm-prov-upload chain verify <swarm_hash> --owner <address>  # exit 1 if another address owns it

# Query or set data status
swarm-prov-upload chain status <swarm_hash>                 # show current status
swarm-prov-upload chain status <swarm_hash> --set restricted  # set status (active|restricted|deleted)

# Transfer ownership
swarm-prov-upload chain transfer <swarm_hash> --to <new_owner_address>

# Authorize or revoke a delegate
swarm-prov-upload chain delegate <address> --authorize
swarm-prov-upload chain delegate <address> --revoke

# Protect: composite workflow (transform + restrict original)
# Equivalent to: verify ACTIVE → optionally anchor → transform → restrict
swarm-prov-upload chain protect <original_hash> <new_hash> --description "Removed PII"
swarm-prov-upload chain protect <orig> <new> --anchor-new --description "Redacted"  # anchor new hash first

# Set the storage reference for an anchored hash (set-once: it cannot be changed later)
swarm-prov-upload chain set-storage-ref <data_hash> <storage_ref>

# Look up data hash by storage reference
swarm-prov-upload chain lookup <storage_ref>

# Wait for a sent transaction, after a write reported "Not confirmed yet" or "Outcome unknown" (exit 3)
swarm-prov-upload chain wait <tx_hash> --event DataRegistered
swarm-prov-upload chain wait <tx_hash> --timeout 300 --json

# Walk transformation chain (follow lineage)
swarm-prov-upload chain get <hash> --follow               # full chain
swarm-prov-upload chain get <hash> --follow --depth 2     # limit depth
swarm-prov-upload chain get <hash> --follow --json        # JSON output
```

For a step-by-step walkthrough of `chain transform` and `chain get --follow`, see [Transformation lineage](docs/chain-workflows.md#transformation-lineage) in docs/chain-workflows.md. The same file also covers `chain merge` and `chain protect`. Which lineage functions a contract has depends on its version, v1 to v4; see [Contract versions](docs/chain-setup.md#contract-versions). Use contract v3 or v4 with this CLI; the base-sepolia preset is v4. On contract v1 and v2, the commands that read a record do not work: `chain get`, `chain get --follow`, `chain verify`, `chain lookup`, `chain status` without `--set`, `chain protect` and `chain anchor` ([#281](https://github.com/datafund/swarm_provenance_CLI/issues/281)).

> **`--json`**: stdout carries exactly one JSON document, for a success or an error (`{"error": "<code>", "message": ...}`), so the output can be piped to `jq`. Progress, warnings, hints and `-v` debug lines go to stderr, and the exit codes do not change. See [docs/chain-setup.md](docs/chain-setup.md#json-output-for-scripting) for the error codes.

> **Exit code 3: may still be mined**: when a write sent its transaction but no receipt arrived within 120 seconds, the command exits 3 and prints the transaction hash. It also exits 3 with "Outcome unknown" when the connection to the RPC fails while or after the transaction is sent; when the RPC answers the send with "already known", "Known transaction" or "nonce too low", which a node gives when it already has the transaction or a transaction with its nonce is mined; or when, after the send, the RPC answers the receipt lookup with a JSON-RPC error, such as a rate limit (-32005). Do not run the write again: wait with the printed `chain wait` command, or check the transaction in the explorer. A transaction that another one with the same nonce replaced is reported as "Replaced" (exit 1). See [docs/chain-workflows.md](docs/chain-workflows.md#exit-codes) for all exit codes.

> **`chain get --follow` fails closed**: if any read fails during the walk, the command prints an error and exits with code 1 instead of printing a partial chain. In `--json` output, each record has a `parents` list (`null` for records at the depth limit). The fail-closed walk and the `parents` list are new in v0.13.0.

> **`chain protect` vs separate commands**: `chain protect` combines verify + anchor + transform + restrict into one command. If the restrict step fails, the command lists the steps that were recorded (the transform transaction), prints the error and the command to restrict the original manually, and exits 1, or 3 when the restrict transaction may still be mined (exit code 3 is new in v0.13.0). The JSON output then has `partial_failure: true` and `failed_step: "restrict"`. Use `chain transform --restrict-original` for the two-step version without the pre-flight ACTIVE check.

### Global flags

| Flag | Description |
|------|-------------|
| `--chain TEXT` | Blockchain: `base-sepolia` (testnet) or `base` (mainnet) |
| `--chain-rpc TEXT` | Custom RPC URL for blockchain connection |

### Blockchain configuration

| Environment Variable | Description | Default |
|---------------------|-------------|---------|
| `CHAIN_NAME` | `base-sepolia` (testnet), `base` (mainnet), or `localhost` (local development node; takes the chain ID the node reports) | `base-sepolia` |
| `PROVENANCE_WALLET_KEY` | Wallet private key (keep secret!) | - |
| `CHAIN_RPC_URL` | Custom RPC URL (optional). With `base` or `base-sepolia`, it must report the preset chain ID | Uses preset |
| `CHAIN_CONTRACT` | Custom contract address (optional) | Uses preset |
| `CHAIN_DEPLOY_BLOCK` | Block the contract was deployed in, where event scans start (optional, a non-negative integer). A custom `CHAIN_CONTRACT` does not use the preset's deploy block. The value must not be later than the block the contract was deployed in: events before it are not read. A value above the chain head is an error. New in v0.13.0 | Preset's, for the preset contract only |
| `CHAIN_EXPLORER_URL` | Custom block explorer URL (optional) | Uses preset |
| `CHAIN_GAS_LIMIT` | Explicit gas limit (optional, skips RPC estimation, so a transaction that would revert is still sent and costs gas). A whole number of at least 21000, like `--gas`; a chain write exits 1 with an error for another value | Auto-estimated |
| `CHAIN_RPC_URLS` | Comma-separated fallback RPC URLs, tried in order after the main RPC (optional, replaces the preset fallbacks). Like `CHAIN_RPC_URL`, applies whatever chain is selected | Uses preset fallbacks |

When the RPC in use cannot be reached, times out, or does not answer with JSON-RPC, reads and the steps of a write before the transaction is sent (chain ID and contract code checks, gas estimate, nonce, gas price, balance check) move to the next fallback RPC that reports the same chain ID. Sending the transaction never moves to a fallback, so a write is never sent twice; waiting for the receipt may move to a fallback for the same transaction hash. See [docs/chain-setup.md](docs/chain-setup.md#which-operations-use-the-fallback-rpcs).

### Testnet setup

1. **Get testnet ETH** (for gas): https://www.alchemy.com/faucets/base-sepolia
2. **Get testnet USDC** (staging gateway only): https://faucet.circle.com/. Test USDC works only with the staging gateway (`--gateway-url https://provenance-gateway.dev.datafund.io`); the default gateway charges real USDC on Base mainnet
3. **Configure wallet**: Set `PROVENANCE_WALLET_KEY` with your wallet's private key. Only commands that write to the chain, and `chain balance`, need it. `chain get`, `verify`, `lookup` and `status` (without `--set`) work without a key

See [docs/chain-setup.md](docs/chain-setup.md) for detailed setup instructions and [docs/chain-workflows.md](docs/chain-workflows.md) for workflow diagrams.

### ChainClient Python API

```python
from swarm_provenance_uploader.core.chain_client import ChainClient

client = ChainClient(chain="base-sepolia")
result = client.anchor(swarm_hash="<64-char-hex>", data_type="swarm-provenance")
print(f"TX: {result.explorer_url}")
```

**Write operations** (require wallet + gas):
- `anchor(swarm_hash, data_type, storage_ref)` - Register a hash on-chain (optional storage reference)
- `anchor_for(swarm_hash, owner, data_type)` - Register on behalf of another owner
- `batch_anchor(swarm_hashes, data_types)` - Batch register multiple hashes
- `transform(original_hash, new_hash, description)` - Record data transformation
- `merge_transform(source_hashes, new_hash, description)` - Record N-to-1 merge (contract v2 and later)
- `access(swarm_hash)` - Record data access
- `batch_access(swarm_hashes)` - Batch record access
- `set_status(swarm_hash, status)` - Change data status (ACTIVE/RESTRICTED/DELETED)
- `transfer_ownership(swarm_hash, new_owner)` - Transfer data ownership
- `set_delegate(delegate, authorized)` - Authorize/revoke a delegate
- `set_storage_ref(swarm_hash, storage_ref)` - Set the storage reference for an anchored hash (set-once)

`ChainClient(gas_limit=N)` sets an explicit gas limit for every write and skips gas estimation, so a transaction that would revert is still sent and costs gas. `N` must be an `int` of at least 21000; another value (including `True`, `1.5` or `"50000"`) raises `ChainConfigurationError`.

To read without a wallet key, create the client with `ChainClient(require_wallet=False)`. The key is then read on first use, so write operations, `balance()` and `address` raise `ChainConfigurationError` if no key is configured.

**Read operations** (no gas required):
- `get(swarm_hash)` - Get full provenance record
- `verify(swarm_hash)` - Check if hash is registered
- `get_provenance_chain(swarm_hash)` - Follow transformation lineage
- `get_by_storage_ref(storage_ref)` - Look up data hash by storage reference
- `balance()` - Get wallet balance and chain info (needs the wallet key)
- `health_check()` - Check RPC connectivity

## Run tests

### Unit tests (mocked)

Unit tests use mocks and do not require a live Bee node or gateway.

```bash
# Run all tests (unit + integration)
pytest

# Run only unit tests (skip integration)
pytest --ignore=tests/test_integration.py
```

### Integration tests (real backends)

Integration tests hit real services. They auto-skip if backends are unavailable.

The gateway tests and the live example demos (`RUN_LIVE_TESTS=1 pytest tests/test_examples.py -m integration`) buy stamps and upload data. They use the gateway in `INTEGRATION_GATEWAY_URL`, else the one in `PROVENANCE_GATEWAY_URL`, else the staging gateway, `https://provenance-gateway.dev.datafund.io`. They refuse the production gateway, `https://provenance-gateway.datafund.io`, and skip with a message, unless you also set `ALLOW_PRODUCTION_TESTS=1`.

The CI integration job (a manual run of `.github/workflows/ci.yml`) sets `PROVENANCE_GATEWAY_URL` from the `GATEWAY_URL` secret. Set that secret to a staging URL, or leave it unset to use staging. If it holds the production URL, the job also needs `ALLOW_PRODUCTION_TESTS=1`, or the gateway tests and the live demos skip. The job prints the skip reasons (`pytest -rs`).

```bash
# Run only integration tests
pytest tests/test_integration.py -v

# Run only local Bee tests
pytest -m local_bee

# Run only gateway tests
pytest -m gateway

# Run blockchain tests (local Hardhat)
pytest -m blockchain

# Run blockchain tests on Base Sepolia (uses testnet gas)
pytest -m "blockchain and slow"
```

**Requirements:**
- Local Bee: Running at `http://localhost:1633`
- Gateway: Available at `https://provenance-gateway.datafund.io`
- Local Hardhat: Running at `http://localhost:8545` with DataProvenance deployed
- Base Sepolia: `PROVENANCE_WALLET_KEY` set with funded wallet

## Usage

### Data operations

```bash
# Upload data to Swarm (default: 25 hour stamp validity)
swarm-prov-upload upload --file /path/to/data.txt --std "PROV-STD-V1" --verbose

# Upload with custom duration (hours, min 24)
swarm-prov-upload upload --file /path/to/data.txt --duration 168  # 7 days

# Upload with size preset (small, medium, large)
swarm-prov-upload upload --file /path/to/data.txt --size large

# Upload with existing stamp (cost savings, faster)
swarm-prov-upload upload --file /path/to/data.txt --stamp-id <existing_stamp_id>

# Upload using pooled stamp (instant ~5s vs >1min for purchase)
swarm-prov-upload upload --file /path/to/data.txt --usePool

# Download data (checks content hash and notary signature)
swarm-prov-upload download <swarm_hash> --output-dir ./downloads --verbose
```

### Collection upload (gateway only)

Upload a directory as a Swarm manifest. Files are accessible via path-based URLs (`bzz/<reference>/path/to/file`).

```bash
# Upload a directory as a collection
swarm-prov-upload upload-collection /path/to/directory

# With provenance standard and custom stamp duration
swarm-prov-upload upload-collection /path/to/directory --std "PROV-STD-V1" --duration 168

# Using pooled stamp (faster)
swarm-prov-upload upload-collection /path/to/directory --usePool

# JSON output with provenance metadata
# (if the gateway uploaded and charged but could not return the result, swarm_reference is null,
#  status is "delivered_not_stored", and transaction identifies the payment)
swarm-prov-upload upload-collection /path/to/directory --json

# With existing stamp, deferred upload, and redundancy level 3
swarm-prov-upload upload-collection /path/to/directory --stamp-id <id> --deferred --redundancy 3
```

**Collection Options:**
| Option | Description |
|--------|-------------|
| `--std` | Provenance standard identifier |
| `--duration`, `-d` | Stamp validity in hours (min 24) |
| `--size` | Stamp size preset: `small`, `medium`, `large` |
| `--stamp-id`, `-s` | Use existing stamp (skip purchase) |
| `--usePool` | Acquire stamp from pool (faster) |
| `--owner-proof` | Upload to a stamp your x402 wallet bought, on the free tier with a signed owner proof instead of a payment. Needs `--stamp-id` (see [Uploading to a stamp you own](#uploading-to-a-stamp-you-own)) |
| `--deferred` | Deferred upload — the gateway returns immediately and processes the upload in the background. Useful for large collections. |
| `--redundancy` | Erasure coding level from 0 to 4: `0` none, `1` medium, `2` strong, `3` insane, `4` paranoid. A higher level keeps the data retrievable when more chunks are lost, and uses more of the stamp. Without this option, the gateway uses level 2. |
| `--stamp-retries` | Number of times to check that the stamp is usable before the upload (default: 12) |
| `--stamp-interval` | Seconds between stamp usability checks (default: 20) |
| `--json` | Output result as JSON (see example below). stdout then carries only the JSON document; progress and the payment prompt go to stderr. An error is a JSON object too, for example `{"error": "stamp_not_usable", "message": ...}` (other codes: `invalid_input`, `configuration_error`, `payment_required`, `payment_outcome_unknown`, `delivered_not_stored`, `upload_failed`, `interrupted`, `aborted`). After the command bought a stamp or took one from the pool, an error document has `unused_stamp_id` |

**Example Output (text):**
```
Processing directory: my_dataset/ (3 files)...
Purchasing postage stamp...
Postage stamp purchased (ID: a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3)
Uploading collection to Swarm...

SUCCESS! Collection uploaded.
Swarm Manifest Reference:
b5d4ea763a1396676771151158461f73678f1676166acd06a0a18600b85de8a4

Files (3):
  readme.txt (42 bytes)
  data/values.csv (128 bytes)
  data/metadata.json (256 bytes)

Total size: 426 bytes
Collection hash: 9f86d08...

Access files at:
  bzz/b5d4ea76.../readme.txt
  bzz/b5d4ea76.../data/values.csv
  bzz/b5d4ea76.../data/metadata.json
```

**Example Output (JSON with `--json`):**
```json
{
  "collection_hash": "9f86d081884c7d659a2feaa0c55ad015...",
  "files": [
    {"path": "readme.txt", "size": 42, "content_hash": "a1b2c3..."},
    {"path": "data/values.csv", "size": 128, "content_hash": "d4e5f6..."}
  ],
  "total_size": 170,
  "file_count": 2,
  "stamp_id": "a3a3a3a3...",
  "swarm_reference": "b5d4ea763a...",
  "provenance_standard": "PROV-STD-V1"
}
```

**Accessing files from a manifest:**

After uploading, individual files are accessible via Swarm's `bzz` protocol using the manifest reference and the file path:

```
https://gateway.ethswarm.org/bzz/<reference>/path/to/file
```

For example, if the reference is `b5d4ea76...` and the file is `data/values.csv`:
```
https://gateway.ethswarm.org/bzz/b5d4ea76.../data/values.csv
```

You can also use any Swarm gateway or a local Bee node to access the files.

**Notes:**
- Symlinks are skipped (not included in the archive) to avoid circular reference issues
- Hidden files (dotfiles like `.gitignore`) are included
- The `collection_hash` is a SHA-256 of the sorted concatenation of all individual file hashes, providing a deterministic fingerprint for the entire collection

**Upload Options:**
| Option | Description |
|--------|-------------|
| `--duration`, `-d` | Stamp validity in hours (min 24, gateway only) |
| `--size` | Size preset: `small`, `medium`, `large` (gateway only) |
| `--depth` | Technical depth parameter (16-32) |
| `--stamp-id`, `-s` | Use existing stamp (skip purchase) |
| `--usePool` | Acquire stamp from pool instead of purchasing (gateway only, faster) |
| `--sign` | Sign document with notary service (value: `notary`, gateway only) |
| `--owner-proof` | Upload to a stamp your x402 wallet bought, on the free tier with a signed owner proof instead of a payment. Needs `--stamp-id`, gateway only (see [Uploading to a stamp you own](#uploading-to-a-stamp-you-own)) |
| `--amount` | Legacy: PLUR amount (local backend) |

**How long data stays on Swarm:** an upload stays available only while its postage stamp is valid. Without `--duration`, the gateway buys a 25-hour stamp, so the data can expire about a day after the upload. The gateway buys its pool stamps (`--usePool`) for 169 hours, counted from when the pool bought them. To keep data longer, pass `--duration <hours>` or extend the stamp with `stamps extend --duration-hours <hours>`, which the gateway charges for like a purchase (a stamp you bought needs `--x402` from the same wallet).

### Stamp management (gateway only)

```bash
# List all stamps
swarm-prov-upload stamps list

# Full IDs (to pass to --stamp-id) and labels; only the stamps your x402 wallet bought
swarm-prov-upload stamps list --full --wallet 0xYourPayerAddress

# Get stamp details
swarm-prov-upload stamps info <stamp_id>

# Extend stamp TTL by 48 hours (paid; a stamp you bought needs --x402 from the same wallet)
# Prints the batch ID and the expiry the gateway reports: an estimate read right after the top-up,
# which may not include the extension yet (check it with stamps info).
# On the default gateway (real USDC on Base mainnet):
swarm-prov-upload --x402 stamps extend <stamp_id> --duration-hours 48
# On the staging gateway (test USDC on Base Sepolia, the network that gateway gets):
swarm-prov-upload --gateway-url https://provenance-gateway.dev.datafund.io --x402 stamps extend <stamp_id> --duration-hours 48

# Check stamp health (can it be used for uploads?)
swarm-prov-upload stamps check <stamp_id>

# View stamp pool status
swarm-prov-upload stamps pool-status
```

#### Stamp health check

The `stamps check` command performs a detailed health check on a stamp:

```bash
swarm-prov-upload stamps check <stamp_id>
```

**Output example:**
```
Stamp Health Check:
--------------------------------------------------
  Stamp ID:   13be53a5...fc0d3c80
  Can upload: Yes

  Warnings:
    [LOW_TTL] TTL is below 24 hours
```

**Possible issues:**

| Code | Type | Meaning |
|------|------|---------|
| `EXPIRED` | Error | Stamp has expired, cannot upload |
| `NOT_USABLE` | Error | Stamp exists but is not usable |
| `NOT_FOUND` | Error | Stamp does not exist |
| `LOW_TTL` | Warning | TTL below 24 hours, consider extending |
| `HIGH_UTILIZATION` | Warning | Stamp is nearly full |

Use `-v` (verbose) for detailed metrics including TTL, utilization percentage, and expiration date.

### Stamp pool (gateway only)

#### What is a stamp pool?

Normally, purchasing a postage stamp on Swarm takes >1 minute because the transaction must be confirmed on-chain and the stamp must sync across the network. The gateway maintains a **pool of pre-purchased stamps** that can be acquired instantly (~5 seconds).

#### When to use `--usePool`

| Scenario | Recommendation |
|----------|----------------|
| Quick uploads, testing, demos | Use `--usePool` |
| Production with predictable volume | Use `--usePool` |
| Pool is empty (check with `stamps pool-status`) | Use regular purchase (omit `--usePool`) |
| Need specific stamp configuration | Use regular purchase with `--duration`/`--depth` |

#### Size presets

Stamps come in three sizes based on storage capacity:

| Size | Depth | Typical Use |
|------|-------|-------------|
| `small` (default) | 17 | Small files (<1MB) |
| `medium` | 20 | Medium files (1-100MB) |
| `large` | 22 | Large files (>100MB) |

#### Usage examples

```bash
# Upload using a pooled stamp (uses 'small' size by default)
swarm-prov-upload upload --file data.txt --usePool

# Upload with specific size from pool
swarm-prov-upload upload --file data.txt --usePool --size medium

# Check pool availability before uploading
swarm-prov-upload stamps pool-status
```

#### Pool status output

```
Stamp Pool Status:
--------------------------------------------------
  Status:       Enabled
  Total stamps: 3

  Availability by size:
    small    (depth 17): 1 available / 1 total (target: 1)
    medium   (depth 20): 2 available / 2 total (target: 1)
```

- **Enabled/Disabled**: Whether the pool feature is active on this gateway
- **Available**: Stamps ready for immediate acquisition
- **Total**: All stamps in pool (including recently acquired ones being replenished)
- **Target**: The gateway's target reserve level for each size

#### Error handling

If the pool is empty or unavailable, the CLI provides helpful guidance:

```
ERROR: No stamps available in pool for requested size/depth.
Try again later, use a different size, or use regular purchase (without --usePool).
```

**Fallback behavior**: If your requested size isn't available but a larger size is, the pool will automatically substitute a larger stamp and notify you.

#### Benefits

- **Speed**: ~5 seconds vs >1 minute for regular purchase
- **No waiting**: Pooled stamps are already usable (no sync delay)
- **Automatic fallback**: Larger stamps substituted if exact size unavailable
- **Same pricing**: x402 costs are identical to regular purchases

### Notary signing (gateway only)

The notary service adds cryptographic signatures to uploaded data, providing proof of authenticity and integrity.

#### How it works

When you upload with `--sign notary`, the gateway's notary service:
1. Receives your data payload
2. Signs a hash of the data + timestamp using EIP-191 (Ethereum signed messages)
3. Adds the signature to a `signatures` array in the document
4. Stores the signed document on Swarm and returns its reference

The signature can be verified locally using standard Ethereum signature recovery. After a signed upload, the CLI reads the stored record back (a plain download: no payment and no free-tier request), checks the signature against the gateway's notary address, and prints the signer and time. If it cannot confirm the signature, it prints a warning and the upload still succeeds.

#### Usage

```bash
# Upload with notary signing
swarm-prov-upload upload --file data.txt --sign notary

# Check notary service status
swarm-prov-upload notary info

# Quick status check
swarm-prov-upload notary status

# Verify a signed document file
swarm-prov-upload notary verify --file signed_document.json
```

#### Verification on download

Signature verification is enabled by default when downloading signed documents. A signature that does not verify, or cannot be checked, fails the download (exit 1) and nothing is saved:

```bash
# Download with automatic verification (default)
swarm-prov-upload download <swarm_hash> --output-dir ./downloads

# Also fail when the document has no notary signature
swarm-prov-upload download <swarm_hash> --output-dir ./downloads --require-signature

# Pin the expected notary instead of asking the gateway that served the document
swarm-prov-upload download <swarm_hash> --notary-address 0x...   # or NOTARY_ADDRESS=0x...

# Skip verification
swarm-prov-upload download <swarm_hash> --output-dir ./downloads --no-verify
```

What `download` checks: the decoded data against the document's own `content_hash`, and the notary signature when there is one.

`download` reads both record formats. In a base64 record, `data` is a string holding the original bytes in base64; this is what the CLI uploads. In a raw record, `data` is a JSON value; this is what the SDK uploads with `raw: true`. For a raw record, `content_hash` is the SHA-256 of the canonical JSON of `data`: keys sorted at every level, `,` and `:` as separators with no spaces, and every character outside ASCII written as `\uXXXX`, the same form the gateway hashes for the notary signature. The CLI saves that canonical JSON as `<hash>.data`, so its SHA-256 is `content_hash`. String `data` is read as base64 when its decoded bytes match `content_hash`, and as a raw record holding a JSON string when the string's canonical JSON matches.

Against the Swarm reference itself:
- **Local backend (`--backend local`):** the content is checked against the reference, chunk by chunk. Every chunk fetched from your Bee node (`GET /chunks/{address}`) is checked against its address, the manifest is followed to the file entry, and the file is rebuilt from its verified chunks and compared with the download. A mismatch exits 1 and saves nothing; `--no-verify-reference` skips the check.
- **Gateway backend:** not checked, because the gateway serves only the file content, not the chunks this needs. The gateway that serves it is trusted for that. A notary signature does not close that gap, even with a pinned `--notary-address`: it covers only the document's `data`, and the gateway's notary signs whatever an uploader sends with `--sign notary`. So a hostile gateway could serve a different, genuinely signed document for your reference. Pinning protects against a gateway that names a notary key of its own, not against substituted content. To be sure of the content, compare it with a hash you obtained independently (for example the original file's, or one anchored on-chain).

The expected signer comes from `GET /api/v1/notary/info` on the same gateway, so a gateway serving forged documents could also name its own key; pin the notary address you trust with `--notary-address` or `NOTARY_ADDRESS`. The saved `<hash>.meta.json` is the document as downloaded, signatures included, so it can be checked again later with `swarm-prov-upload notary verify --file <hash>.meta.json`. `--strict` is kept as an alias of `--require-signature`.

#### Signature structure

The notary adds a signature entry in the following format:

```json
{
  "data": { ... },
  "signatures": [
    {
      "type": "notary",
      "signer": "0x...",
      "timestamp": "2026-01-21T16:30:00+00:00",
      "data_hash": "sha256...",
      "signature": "0x...",
      "hashed_fields": ["data"],
      "signed_message_format": "{data_hash}|{timestamp}"
    }
  ]
}
```

| Field | Description |
|-------|-------------|
| `type` | Always `notary` |
| `signer` | Ethereum address of the notary |
| `timestamp` | ISO 8601 timestamp when signed (gateway's witness time) |
| `data_hash` | SHA256 hash of canonical JSON of `data` field |
| `signature` | EIP-191 signature of `{data_hash}|{timestamp}` |
| `hashed_fields` | Fields whose values were hashed (typically `["data"]`) |
| `signed_message_format` | Format pattern of the signed message |

#### Verifying signatures manually

The signature can be verified with any Ethereum library:

1. Compute canonical JSON of `data` field (sorted keys, no whitespace)
2. Hash with SHA256
3. Construct message: `{data_hash}|{timestamp}`
4. Verify EIP-191 signature recovers to expected address

```python
# Example using eth-account
from eth_account import Account
from eth_account.messages import encode_defunct
import json, hashlib

data_json = json.dumps(document["data"], sort_keys=True, separators=(",", ":"))
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
message = f"{data_hash}|{signature['timestamp']}"
signable = encode_defunct(text=message)
recovered = Account.recover_message(signable, signature=signature["signature"])
assert recovered.lower() == expected_address.lower()
```

### Information commands

```bash
# Check backend health
swarm-prov-upload health

# Wallet info (gateway only)
swarm-prov-upload wallet

# Chequebook info (gateway only)
swarm-prov-upload chequebook
```

Use `swarm-prov-upload --help` for all options.

## Examples

The [`examples/`](examples/) directory contains real-world usage demos with shell scripts, Python scripts, and sample data:

| # | Example | Description |
|---|---------|-------------|
| [01](examples/01-basic-upload-download/) | **Basic Upload/Download** | Upload a file, download it back, verify integrity |
| [02](examples/02-audit-trail/) | **Audit Trail** | Tamper-evident compliance records with `--std "AUDIT-LOG-V1"` |
| [03](examples/03-scientific-data/) | **Scientific Data** | Research archival with `--std "PROV-O"` and `--duration 720` |
| [04](examples/04-batch-processing/) | **Batch Processing** | Stamp reuse across multiple uploads with `--stamp-id` |
| [05](examples/05-encrypted-data/) | **Encrypted Data** | Pre-encrypt, upload with `--enc "AES-256-CBC-PBKDF2"`, decrypt |
| [06](examples/06-market-memory/) | **Market Memory** | Canonical hashing, prediction-to-outcome linking |
| [07](examples/07-stamp-management/) | **Stamp Management** | Full stamp lifecycle: list, info, check, extend, pool-status |
| [08](examples/08-ci-cd-integration/) | **CI/CD Integration** | Archive build artifacts with GitHub Actions / GitLab CI |
| [09](examples/09-verification/) | **Verification & Integrity** | Tamper detection, SHA-256 verification, `--verify` flag |

See [examples/README.md](examples/README.md) for the full guide with walkthroughs.

## Architecture & features

```
┌─────────────────────────────────────────────────────────────────────────────────┐
│                           SWARM PROVENANCE UPLOADER                            │
│                              Architecture Diagram                               │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                                CLI INTERFACE                                    │
│  ┌─────────────────┐  ┌──────────────────┐  ┌─────────────────────────────────┐ │
│  │ GLOBAL OPTIONS  │  │ DATA COMMANDS    │  │ INFO COMMANDS                   │ │
│  │                 │  │                  │  │                                 │ │
│  │ --backend       │  │ upload           │  │ health                          │ │
│  │   gateway|local │  │ upload-collection│  │ wallet (gateway)                │ │
│  │                 │  │ download         │  │                                 │ │
│  │ --gateway-url   │  │                  │  │ chequebook (gateway)            │ │
│  │ --x402          │  ├──────────────────┤  │                                 │ │
│  │ --auto-pay      │  │ STAMPS COMMANDS  │  ├─────────────────────────────────┤ │
│  │ --max-pay       │  │ (gateway only)   │  │ NOTARY COMMANDS (gateway only)  │ │
│  │ --chain         │  │ stamps list      │  │ notary info                     │ │
│  │ --chain-rpc     │  │ stamps info      │  │ notary status                   │ │
│  │ --usePool       │  │ stamps extend    │  │ notary verify                   │ │
│  │ --sign          │  │ stamps check     │  │                                 │ │
│  │ --verify        │  │ stamps pool-stat │  ├─────────────────────────────────┤ │
│  │                 │  │                  │  │ x402 status                     │ │
│  │ Built with:     │  ├──────────────────┤  │ x402 balance                    │ │
│  │ • Rich output   │  │ CHAIN COMMANDS   │  │ x402 info                       │ │
│  │                 │  │ (optional)       │  │                                 │ │
│  │                 │  │ chain balance    │  │                                 │ │
│  │                 │  │ chain anchor     │  │                                 │ │
│  │                 │  │ chain get        │  │                                 │ │
│  │                 │  │ chain verify     │  │                                 │ │
│  │                 │  │ chain access     │  │                                 │ │
│  │                 │  │ chain transform  │  │                                 │ │
│  │                 │  │ chain status     │  │                                 │ │
│  │                 │  │ chain transfer   │  │                                 │ │
│  │                 │  │ chain delegate   │  │                                 │ │
│  │                 │  │ chain protect    │  │                                 │ │
│  │ chain set-stor.. │  │                                 │ │
│  │ chain lookup     │  │                                 │ │
│  └─────────────────┘  └──────────────────┘  └─────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
                                        │
                                        ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                              CORE BUSINESS LOGIC                               │
│  ┌───────────────────┐  ┌─────────────────┐  ┌──────────────────────────────┐  │
│  │ FILE_UTILS.PY     │  │ METADATA_       │  │ BACKEND CLIENTS              │  │
│  │                   │  │ BUILDER.PY      │  │                              │  │
│  │ • File I/O        │  │                 │  │ gateway_client.py (default)  │  │
│  │ • SHA256 hashing  │  │ • Pydantic      │  │ • Gateway API wrapper        │  │
│  │ • Base64 encode   │  │   validation    │  │ • Full feature support       │  │
│  │ • Base64 decode   │  │ • JSON          │  │ • x402 payment integration   │  │
│  │ • Size calculation│  │   serialization │  │ • Manifest/collection upload │  │
│  │ • TAR archiving   │  │ • Metadata      │  │                              │  │
│  │ • Dir hashing     │  │   wrapping      │  │ swarm_client.py (local)      │  │
│  │                   │  │   wrapping      │  │ • Direct Bee API             │  │
│  ├───────────────────┤  │                 │  │ • Local/self-hosted          │  │
│  │ X402_CLIENT.PY    │  │                 │  │                              │  │
│  │ (optional)        │  │                 │  │ chain_client.py (optional)   │  │
│  │ • EIP-712 signing │  │                 │  │ • On-chain anchoring         │  │
│  │ • USDC on Base    │  │                 │  │ • DataProvenance contract    │  │
│  │ • 402 handling    │  │                 │  │ • Provenance chain tracking  │  │
│  └───────────────────┘  └─────────────────┘  └──────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────┘
                                        │
                                        ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                             DATA MODELS & CONFIG                               │
│  ┌─────────────────────────────────┐  ┌─────────────────────────────────────┐  │
│  │ MODELS.PY                       │  │ CONFIG.PY                           │  │
│  │                                 │  │                                     │  │
│  │ ProvenanceMetadata (Pydantic):  │  │ Environment Configuration:          │  │
│  │ ┌─────────────────────────────┐ │  │ • PROVENANCE_BACKEND               │  │
│  │ │ • data: str (Base64)        │ │  │ • PROVENANCE_GATEWAY_URL           │  │
│  │ │ • content_hash: str (SHA256)│ │  │ • BEE_GATEWAY_URL                  │  │
│  │ │ • stamp_id: str (64 hex)    │ │  │ • DEFAULT_POSTAGE_DEPTH            │  │
│  │ │ • provenance_standard: str? │ │  │ • DEFAULT_POSTAGE_AMOUNT           │  │
│  │ │ • encryption: str?          │ │  │ • .env file support                │  │
│  │ └─────────────────────────────┘ │  │                                     │  │
│  │                                 │  │ Free Tier:                          │  │
│  │                                 │  │ • FREE_TIER                         │  │
│  │                                 │  │                                     │  │
│  │                                 │  │ x402 Configuration:                 │  │
│  │ x402 Payment Models:            │  │ • X402_ENABLED                      │  │
│  │ • X402PaymentOption             │  │ • X402_PRIVATE_KEY            │  │
│  │ • X402PaymentRequirements       │  │ • X402_NETWORK                      │  │
│  │ • X402PaymentPayload            │  │ • X402_AUTO_PAY                     │  │
│  │                                 │  │ • X402_MAX_AUTO_PAY_USD             │  │
│  │ Chain Models:                   │  │                                     │  │
│  │ • ChainProvenanceRecord         │  │ Chain Configuration:                │  │
│  │ • AnchorResult                  │  │ • CHAIN_NAME                        │  │
│  │ • TransformResult               │  │ • PROVENANCE_WALLET_KEY             │  │
│  │ • MergeTransformResult          │  │ • CHAIN_RPC_URL                     │  │
│  │ • AccessResult                  │  │ • CHAIN_RPC_URLS (fallbacks)        │  │
│  │ • ChainWalletInfo               │  │ • CHAIN_EXPLORER_URL                │  │
│  │                                 │  │                                     │  │
│  └─────────────────────────────────┘  └─────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────┘
                                        │
                                        ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                                UPLOAD WORKFLOW                                 │
│                                                                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │ 1. READ     │───▶│ 2. HASH &   │───▶│ 3. PURCHASE │───▶│ 4. WRAP &   │     │
│  │    FILE     │    │    ENCODE   │    │    STAMP    │    │    UPLOAD   │     │
│  │             │    │             │    │             │    │             │     │
│  │ • File I/O  │    │ • SHA256    │    │ • HTTP POST │    │ • Metadata  │     │
│  │ • Validate  │    │ • Base64    │    │ • Wait loop │    │ • JSON wrap │     │
│  │ • Read raw  │    │ • Size calc │    │ • Retry     │    │ • HTTP POST │     │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘     │
│                                                                                 │
│                              ┌─────────────────┐                               │
│                              │ 5. RETURN HASH  │                               │
│                              │                 │                               │
│                              │ • Swarm ref     │                               │
│                              │ • 64-char hex   │                               │
│                              │ • Success msg   │                               │
│                              └─────────────────┘                               │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                             x402 PAYMENT FLOW (Optional)                        │
│                                                                                 │
│  When gateway returns HTTP 402 Payment Required:                               │
│                                                                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │ 1. RECEIVE  │───▶│ 2. PARSE    │───▶│ 3. CONFIRM  │───▶│ 4. SIGN &   │     │
│  │    402      │    │    OPTIONS  │    │    PAYMENT  │    │    RETRY    │     │
│  │             │    │             │    │             │    │             │     │
│  │ • HTTP 402  │    │ • Extract   │    │ • Auto-pay  │    │ • EIP-712   │     │
│  │ • JSON body │    │   accepts[] │    │   or prompt │    │ • X-PAYMENT │     │
│  │ • x402 hdr  │    │ • Match net │    │ • Check bal │    │ • Retry req │     │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘     │
│                                                                                 │
│  Networks: Base Sepolia (testnet) | Base (mainnet)                             │
│  Payment: USDC stablecoin via the gateway's x402 facilitator                   │
│           (protocol: https://x402.org)                                         │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                               DOWNLOAD WORKFLOW                                │
│                                                                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │ 1. FETCH    │───▶│ 2. PARSE &  │───▶│ 3. DECODE & │───▶│ 4. VERIFY & │     │
│  │    METADATA │    │    VALIDATE │    │    EXTRACT  │    │    SAVE     │     │
│  │             │    │             │    │             │    │             │     │
│  │ • HTTP GET  │    │ • JSON      │    │ • Base64    │    │ • SHA256    │     │
│  │ • Error     │    │ • Pydantic  │    │ • Extract   │    │ • Compare   │     │
│  │   handling  │    │ • Schema    │    │ • Raw bytes │    │ • Save both │     │
│  └─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘     │
│                                                                                 │
│                              ┌─────────────────┐                               │
│                              │ 5. SUCCESS      │                               │
│                              │                 │                               │
│                              │ • .data file    │                               │
│                              │ • .meta.json    │                               │
│                              │ • Verification  │                               │
│                              └─────────────────┘                               │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                              SWARM NETWORK LAYER                               │
│  ┌─────────────────────────────────┐  ┌─────────────────────────────────────┐  │
│  │ GATEWAY (DEFAULT)               │  │ SWARM NETWORK                       │  │
│  │                                 │  │                                     │  │
│  │ provenance-gateway.datafund.io  │  │ • Decentralized storage             │  │
│  │ API Endpoints:                  │  │ • Content-addressable               │  │
│  │ • /api/v1/stamps/ - CRUD        │  │ • Kept while stamp valid            │  │
│  │ • /api/v1/data/ - Upload/DL     │  │ • Cryptographic integrity           │  │
│  │ • /api/v1/wallet - Balance      │  │ • Economic incentives               │  │
│  │ • /api/v1/chequebook            │  │ • Censorship resistant              │  │
│  │                                 │  │                                     │  │
│  │ No local node required!         │  │                                     │  │
│  ├─────────────────────────────────┤  │                                     │  │
│  │ LOCAL BEE (--backend local)     │  │                                     │  │
│  │ Direct /bzz, /stamps endpoints  │  │                                     │  │
│  │ Requires running Bee node       │  │                                     │  │
│  └─────────────────────────────────┘  └─────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                                KEY FEATURES                                    │
│                                                                                 │
│  🔒 SECURITY & INTEGRITY           📦 DATA PROCESSING                          │
│  • SHA256 content verification    • Base64 encoding/decoding                  │
│  • Cryptographic hashing          • JSON metadata wrapping                    │
│  • Content-addressed data         • Pydantic data validation                  │
│  • Tamper detection               • Type-safe operations                      │
│                                                                                 │
│  🌐 DECENTRALIZED STORAGE          ⚙️  OPERATIONAL                             │
│  • Swarm network integration      • Verbose/concise modes                     │
│  • Content-addressable            • Comprehensive error handling              │
│  • Censorship resistant           • Retry logic with backoff                  │
│  • Kept while stamp valid         • Environment configuration                 │
│  • Collection/manifest upload     • JSON output for automation                │
│                                                                                 │
│  🏷️  PROVENANCE METADATA           🧪 TESTING & RELIABILITY                   │
│  • Standard identifier support    • Mock-based test suite                     │
│  • Optional encryption details    • No live node required for tests           │
│  • Bidirectional operations       • Comprehensive CLI testing                 │
│  • Metadata preservation          • CI/CD ready                               │
│                                                                                 │
│  🔗 POSTAGE STAMP SYSTEM           📊 MONITORING & DEBUGGING                   │
│  • Economic spam prevention       • Detailed verbose output                   │
│  • TTL-based data persistence     • HTTP request/response logging             │
│  • Automatic stamp validation     • Progress indicators                       │
│  • Configurable parameters        • Error context & suggestions               │
│                                                                                 │
│  🔀 DUAL BACKEND SUPPORT           🚀 GATEWAY FEATURES                         │
│  • Gateway backend (default)      • stamps list - View all stamps             │
│  • Local Bee backend option       • stamps extend - Add TTL                   │
│  • Seamless switching             • wallet - View BZZ balance                 │
│  • Same CLI for both              • chequebook - View chequebook              │
│                                                                                 │
│  💳 x402 PAYMENTS (Optional)       🔏 NOTARY SIGNING (Gateway only)            │
│  • USDC on Base chain             • EIP-191 message signatures                │
│  • Auto-pay mode                  • Cryptographic proof of authenticity       │
│  • Payment confirmation           • Verifiable timestamps                     │
│  • Lazy dependency loading        • Local signature verification              │
│  • Balance checking               • Ethereum address recovery                 │
│                                                                                 │
│  ⛓️  BLOCKCHAIN ANCHORING (Optional)                                           │
│  • DataProvenance smart contract  • On-chain data registration                │
│  • Transformation lineage         • Access tracking                           │
│  • Ownership transfer             • Delegate authorization                    │
│  • Storage reference mapping      • Reverse lookup by storageRef             │
│  • Base Sepolia / Base mainnet    • Lazy dependency loading                   │
└─────────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────────┐
│                               TECHNOLOGY STACK                                 │
│                                                                                 │
│  🐍 CORE TECHNOLOGIES              📚 KEY LIBRARIES                            │
│  • Python 3.9+                    • Typer - CLI framework                     │
│  • Modular architecture           • Pydantic v2 - Data validation             │
│  • Type hints throughout          • Requests - HTTP client                    │
│  • Async-ready design             • Python-dotenv - Config management         │
│                                   • eth-account - Ethereum signing (optional) │
│                                   • web3 - Blockchain interaction (optional)  │
│                                                                                 │
│  🔧 DEVELOPMENT TOOLS              🧪 TESTING FRAMEWORK                        │
│  • Virtual environment            • Pytest - Test runner                      │
│  • Editable installation          • Pytest-mock - Mocking utilities           │
│  • Environment configuration      • Requests-mock - HTTP mocking              │
│  • Rich CLI output                • No external dependencies for tests        │
└─────────────────────────────────────────────────────────────────────────────────┘
```

This architecture diagram shows the **Swarm Provenance Uploader** as a layered system that:

1. **CLI Layer**: Provides user-friendly commands with rich help and validation
2. **Core Logic**: Handles file processing, metadata creation, and Swarm communication
3. **Data Models**: Ensures type safety and validation with Pydantic schemas
4. **Network Layer**: Interfaces with Bee nodes and the Swarm decentralized network

**Key Strengths**:
- ✅ **Dual backend support** (gateway default, local Bee optional)
- ✅ **Bidirectional operations** (upload/download)
- ✅ **Integrity verification** (SHA256 hashing)
- ✅ **Metadata preservation** (provenance standards)
- ✅ **Decentralized storage** (Swarm network)
- ✅ **Production ready** (error handling, retries, logging)

## Project directory structure

```
swarm_provenance_uploader/
├── .env.example
├── .gitignore
├── pyproject.toml
├── README.md
├── CLAUDE.md
├── docs/
│   └── x402-setup.md            # x402 payment setup guide
├── swarm_provenance_uploader/
│   ├── __init__.py
│   ├── cli.py
│   ├── config.py
│   ├── constants.py             # Constants without side effects (MIN_GAS_LIMIT)
│   ├── exceptions.py            # Custom exception classes
│   ├── models.py
│   ├── chain/                   # Blockchain subpackage (optional)
│   │   ├── __init__.py
│   │   ├── provider.py          # Web3 connection management
│   │   ├── wallet.py            # Transaction signing
│   │   ├── contract.py          # DataProvenance contract wrapper
│   │   ├── event_cache.py       # Transformation event cache (v1 fallback)
│   │   ├── exceptions.py        # Chain-specific exception hierarchy
│   │   └── abi/
│   │       └── DataProvenance.json  # Contract ABI
│   └── core/
│       ├── __init__.py
│       ├── chain_client.py      # High-level chain facade (optional)
│       ├── file_utils.py
│       ├── gateway_client.py    # Gateway API client (default)
│       ├── metadata_builder.py
│       ├── notary_utils.py      # Notary signature verification
│       ├── swarm_client.py      # Local Bee API client
│       └── x402_client.py       # x402 payment client (optional)
└── tests/
    ├── __init__.py
    ├── test_chain_client.py     # Chain client unit tests (mocked)
    ├── test_cli.py              # CLI unit tests (mocked)
    ├── test_gateway_client.py   # GatewayClient unit tests (mocked)
    ├── test_integration.py      # Integration tests (real backends)
    ├── live_gateway.py          # Gateway selection for the live tests
    ├── test_notary_utils.py     # Notary utils unit tests (mocked)
    └── test_x402_client.py      # x402 unit tests (mocked)
```

