Protocol Spec Architecture Getting Started Live Demo ↗ Postman Protocol Spec GitHub
X402-BSV-PROOF/1  ·  Spec Frozen

Stateless Settlement-Gated HTTP

Per-request micropayment-gated API access using Bitcoin SV settlement. No accounts. No sessions. No trust. Every request produces cryptographic proof of consumption — independently verifiable, on-chain, and immutable.

Client
GET /api
402
Gatekeeper
challenge
Build Partial Tx
partial tx
Fee Delegator
signed tx
BSV Network
proof + retry
200
Verified ✓

What is x402-BSV

Cryptographically verifiable usage metering for HTTP APIs and machine-to-machine systems, using BSV settlement.

x402-BSV is a Stateless Settlement-Gated HTTP Protocol. It integrates settlement directly into the HTTP request lifecycle through a structured 402 challenge → proof → retry flow. Every API call produces an independently verifiable on-chain record. The blockchain is used as a proof layer, not a checkout system — commercial billing remains contractual and off-chain, exactly like AWS or any other cloud provider.

The Problem

⚖️

Trust-Based Reconciliation

Providers meter usage internally. Customers must trust the provider's accounting. No independent verification. Disputes require manual audit.

🔑

Account Friction

Registration, API keys, rate limits, subscription lock-in, pre-funded accounts. Every integration starts with overhead.

🔄

Replay Vulnerability

No cryptographic single-use guarantees. Rate limiting relies on IP or session state. Bypassed with proxies. Stateful servers create bottlenecks.

📋

Dispute Failure

Usage records aren't independently verifiable. Logs diverge. No cryptographic proof of consumption. Small disputes are unviable to resolve.

The x402-BSV Model

An unpaid request receives a deterministic payment challenge. The client constructs a partial transaction spending a nonce UTXO issued in the challenge. A delegator hydrates fees, signs, and returns the completed transaction. The client broadcasts to the network, then resubmits the request with cryptographic proof of settlement. The gatekeeper verifies binding, nonce consumption, and settlement acceptance before delivering the asset.

This preserves HTTP semantics while embedding payment as a deterministic precondition to execution. Every usage event is recorded on-chain — independently auditable by both parties.

What It Is — and Isn't

This Is

Cryptographically verifiable usage metering
Per-request on-chain settlement proof
Stateless HTTP middleware
Network-enforced replay protection
Infrastructure — like a utility meter

This Is Not

A wallet system
User-paid crypto payments
A fintech or billing platform
A multi-chain abstraction
Token economics or speculation

Why BSV

The protocol design is blockchain-agnostic at the specification level. It requires deterministic per-request settlement, extremely low fees, high throughput, no mempool games, stateless verification, and unbounded scaling without L2 coordination.

Today, only BSV satisfies these constraints without compromises. Other chains can simulate parts of this model by adding layers of trust and batching. BSV is the only chain that runs it natively — predictable fees (1–50 sats), massive throughput, UTXO proofs mapping directly to usage events, and simple, legally intelligible transactions.

Correct framing: BSV is not a branding choice — it is a physical constraint satisfaction. If another chain ever meets the same constraints, the design still holds. Reality picks the winner, not ideology.

Wire Protocol Specification

X402-BSV-PROOF/1 — the exact wire-level protocol for x402-BSV settlement. FROZEN
View full protocol specification on GitHub ↗

HTTP Flow

The protocol operates as a six-step cycle within standard HTTP semantics.

Step 1 — Client Makes Unpaid Request

HTTP Request
GET /api/expensive-resource HTTP/1.1
Host: api.example.com
Accept: application/json

No payment headers. No authentication.

Step 2 — Server Responds with 402 Challenge

HTTP Response
HTTP/1.1 402 Payment Required
X402-Challenge: <base64url(JSON)>
X402-Accept: bsv-tx-v1
Cache-Control: no-store

Challenge JSON

Challenge payload (before base64url encoding)
{
  "v": "1",
  "scheme": "bsv-tx-v1",
  "nonce_utxo": {
    "txid": "hex_string",
    "vout": 0,
    "satoshis": 1,
    "locking_script_hex": "hex_string"
  },
  "amount_sats": 37,
  "payee_locking_script_hex": "hex_string",
  "expires_at": 1735689600,
  "domain": "api.example.com",
  "method": "GET",
  "path": "/api/expensive-resource",
  "query": "",
  "req_headers_sha256": "hex_string",
  "req_body_sha256": "hex_string",
  "require_mempool_accept": true,
  "confirmations_required": 0
}
v stringProtocol version — always "1"
scheme stringPayment scheme — "bsv-tx-v1"
nonce_utxo object1-sat UTXO that must be spent in payment tx. Gateway-issued. Single-use.
amount_sats numberMinimum payment amount in satoshis
payee_locking_script_hex stringService address locking script (hex)
expires_at numberUNIX timestamp (seconds) after which proof is invalid
domain stringRequest domain — for binding
method / path / query stringHTTP request parameters — bound to challenge
req_headers_sha256 stringSHA-256 of canonical headers (see Canonical Hashing)
req_body_sha256 stringSHA-256 of raw body bytes
require_mempool_accept booleanIf true, server requires mempool acceptance before gating response
confirmations_required numberBlock confirmations required (0 for 0-conf)
Nonce Issuance Invariant: Nonce UTXOs MUST be issued by the gateway. Client-supplied nonces are invalid. Replay protection is enforced exclusively through UTXO single-spend semantics at consensus — servers MUST NOT rely on persistent nonce tracking.

Step 3 — Client Constructs Partial Transaction

The client builds a partial transaction with one input (spending the nonce_utxo) and one output (paying ≥ amount_sats to payee_locking_script_hex). Miner fee inputs and signatures are missing — these are added by the delegator.

Step 4 — Client Submits to Fee Delegator

POST /delegate/x402
{
  "partial_tx": "<hex>",
  "nonce_utxo": { "txid": "...", "vout": 0 },
  "challenge_sha256": "hex_string"
}

The delegator validates, adds fee inputs, signs its own inputs, and returns the completed transaction. The client then broadcasts to the BSV network.

Step 5 — Client Retries with Proof

HTTP Request with proof
GET /api/expensive-resource HTTP/1.1
Host: api.example.com
X402-Proof: <base64url(JSON)>
X402-Tx: <base64(rawtx)>

Proof JSON

Proof payload (before base64url encoding)
{
  "v": "1",
  "scheme": "bsv-tx-v1",
  "txid": "hex_string",
  "rawtx_b64": "base64_string",
  "challenge_sha256": "hex_string",
  "request": {
    "domain": "api.example.com",
    "method": "GET",
    "path": "/api/expensive-resource",
    "query": "",
    "req_headers_sha256": "hex_string",
    "req_body_sha256": "hex_string"
  }
}

Step 6 — Server Verifies and Responds

The gatekeeper executes a deterministic 16-step verification sequence:

  1. Base64url decode proof JSON
  2. Validate v and scheme
  3. Recompute req_body_sha256 from actual request body
  4. Recompute req_headers_sha256 from actual request headers
  5. Validate request hashes match proof.request.*
  6. Recompute challenge_sha256 from stored challenge
  7. Validate challenge_sha256 matches proof
  8. Validate domain/method/path/query match challenge
  9. Validate now ≤ expires_at
  10. Decode rawtx_b64, compute txid, compare to proof.txid
  11. Confirm tx includes input spending nonce_utxo
  12. Confirm tx includes output paying ≥ amount_sats
  13. Query mempool acceptance
  14. Verify client_sig (optional, v1.1)
  15. If all pass → 200 OK
  16. If tx valid but not in mempool → 409 Conflict or 202 Accepted

Canonical Hashing Rules

Header Hash (req_headers_sha256)

Allowlist (default): accept, content-type, content-length, x402-idempotency-key, x402-client.

  1. Lowercase header names
  2. Trim surrounding whitespace in values
  3. Collapse internal runs of whitespace to single space
  4. Sort by header name (lexicographic)
  5. Join as: name:value\n for each header
  6. Compute: SHA256(utf8(canonical_headers_string)) → hex

Body Hash (req_body_sha256)

SHA256(raw_body_bytes) → hex. If no body: SHA256("") → hex.

Challenge Hash (challenge_sha256)

Serialize challenge JSON using RFC 8785 (JSON Canonicalization Scheme, JCS). Sort object keys lexicographically, no whitespace, deterministic encoding. SHA256(canonical_json_bytes) → hex.

Transaction Constraints

For scheme = "bsv-tx-v1", the transaction must contain:

  1. Nonce spend — one input spending nonce_utxo from challenge
  2. Payee output — one output with locking script matching payee_locking_script_hex, amount ≥ amount_sats
  3. Optional change output(s) — as needed

If require_mempool_accept is true, the gatekeeper verifies mempool visibility independently. Broadcast origin is irrelevant to correctness. No confirmations required by default.

Acceptance Matrix

ConditionHTTP StatusHeaders
Valid proof, mempool accepted200 OKX402-Receipt: <hash>
Valid proof, mempool pending202 AcceptedX402-Status: pending
Expired challenge402 Payment RequiredNew X402-Challenge
Invalid proof format400 Bad Request
Wrong endpoint/path403 Forbidden
Double-spend (nonce already spent)409 ConflictX402-Status: double-spend
Invalid transaction402 Payment RequiredNew X402-Challenge
Mempool rejection402 Payment RequiredNew X402-Challenge
Insufficient amount402 Payment RequiredNew X402-Challenge

Error Codes

CodeDescription
invalid_versionProtocol version not supported
invalid_schemePayment scheme not supported
invalid_nonceNonce UTXO invalid or already spent
invalid_payeePayee output doesn't match challenge
insufficient_amountPayment amount below minimum
expired_challengeChallenge past expiry time
mempool_rejectedTransaction rejected by mempool
invalid_bindingRequest binding doesn't match
double_spendNonce already spent in different tx

Architecture

Five strictly separated layers. Each with non-negotiable boundaries. No responsibility blurring.

Layer 4
Commercial & Legal Layer
Monthly billing · SLAs · Enterprise contracts · Cost-plus pricing · Audit trails
│ commercial agreements ▼
Layer 3
Service & API Products
Paid APIs · Metered AI inference · Data access · Voting / attestations
│ HTTP requests ▼
Layer 2
x402 Protocol Semantics — Gatekeeper
402 challenge generation · Request binding · Pricing logic · Proof verification · Response gating
│ partial tx for finalization ▼
Layer 1
Fee Delegator — The Economic Kernel
Fee sponsorship · UTXO lifecycle · Policy enforcement · Transaction signing · Returns signed tx (no broadcast)
│ raw transactions ▼
Layer 0
Settlement Substrate — BSV Network
UTXO single-spend enforcement · Mempool acceptance · Global replay protection · Deterministic settlement

Component Boundaries

The Gatekeeper handles HTTP semantics and proof validation — it never signs transactions, manages UTXOs, or holds private keys. The Fee Delegator handles transaction construction and fee sponsorship — it never parses HTTP, evaluates expiry timestamps, or performs business logic. The BSV Network enforces UTXO single-spend globally — it knows nothing about x402.

The Fee Delegator is not a helper service. It is the foundational settlement primitive — the keystone that makes the entire x402 model real. It answers one question: "Is this transaction safe for me to sponsor?"

Trust Boundaries

BoundaryTypeDescription
Client ↔ NetworkSettlementClient broadcasts completed transaction. Client is the settlement actor.
Delegator ↔ ClientConstructionDelegator validates partial tx, adds fee inputs, signs, returns completed tx.
Gatekeeper ↔ NetworkVerificationGatekeeper verifies mempool visibility independently. Broadcast origin irrelevant.

Economics & Security

Operationally survivable by design — bounded costs, layered abuse prevention, deterministic failure modes.

Per-Request Cost Breakdown

ComponentCostNotes
Nonce UTXO1 satOne-time, can be reclaimed if unused
Miner fee1–50 satsTypical BSV fees
Mempool queryNegligibleLocal node
Total per request~2–51 sats~$0.0001–$0.005

Infrastructure costs: $50–500/month depending on scale (node + servers).

Funding Modes

The protocol is invariant across modes. Only the funding source changes.

ComponentMode 1: Self-FundedMode 2: Sponsored
Nonce UTXOGatewayGateway
Miner feeClientDelegator
Service outputClientDelegator
Use caseEnd state — fully atomicOnboarding — zero client friction
Sponsorship is adoption strategy, not invariant. Migration from Sponsored to Self-Funded requires no protocol changes — only configuration.

Threat Model

🛡️

Replay Attacks

Nonce UTXO can only be spent once (network-enforced). Request binding ensures proof matches exact parameters. Cross-endpoint reuse fails validation.

Abuse / DoS

Rate limiting per IP/endpoint. Fee caps per transaction. Nonce pool size limits. Daily delegation budgets. Worst case at 1M requests: ~$500.

🔀

Mempool Uncertainty

Two-node quorum acceptance (recommended). First-seen LRU cache (TTL minutes). Conflicting nonce spends rejected immediately.

🔧

Operator Misbehaviour

Gatekeeper cannot sign transactions. Delegator doesn't understand HTTP. All proofs are independently verifiable on-chain. Boundaries prevent manipulation.

⏱️

Expiry Races

Checked at both challenge generation and proof verification. Reasonable expiry windows (minutes, not seconds). Client can request new challenge.

🔗

Binding Bypass

Canonical header hashing (deterministic). Body hash included. Method, path, query bound. Verification recomputes from actual request.

Abuse Prevention Controls

ControlMechanismDefault
Rate limitingPer IP/endpoint, burst allowance60–100 req/min
Fee capsPer transaction + daily/weekly budgets100 sats/tx, 10M sats/day
Nonce poolPre-mint pool with auto-replenish100K–1M nonces
Dynamic pricingAbuse detection increases price2x at 1K req, 10x at 10K
Budget exhaustion503 Service Unavailable + Retry-AfterHard stop at daily cap

Getting Started

Run the reference implementation locally in under five minutes.

Prerequisites

Quick Start

Terminal
# Clone the reference implementation
git clone https://github.com/merkleworks/x402-bsv.git
cd x402-bsv

# Generate keys and configure
make setup

# Start the gateway (gatekeeper + delegator + demo API)
make demo

# In another terminal — make a paid request
make client

make setup generates BSV keypairs and creates a .env file. make demo starts the full stack on localhost. make client executes the complete 402 challenge → proof → response cycle.

Client SDK (TypeScript/Node.js)

The @merkleworks/x402-client package is a drop-in fetch() replacement that handles the x402 flow transparently. It performs the original request, intercepts 402 responses, forwards the challenge to the gateway, and retries with proof — in a single call.

Install
npm install @merkleworks/x402-client
Usage — TypeScript
import { X402Client } from '@merkleworks/x402-client';

const client = new X402Client({
  gatewayUrl: 'https://gateway.example.com',
});

// Drop-in fetch replacement — handles 402 transparently
const response = await client.fetch('https://api.example.com/expensive-resource');
const data = await response.json();
The client does NOT construct transactions or manage wallets. It forwards the challenge to the gateway, which handles transaction construction, signing, and returns the completed tx. The client then broadcasts and retries with proof.

Configuration Reference

VariableDescriptionDefault
X402_LISTEN_ADDRGateway HTTP listen address:8402
X402_HD_SEEDBIP32 HD wallet seed (hex)Generated by setup
X402_NONCE_POOL_SIZEPre-minted nonce pool target1000
X402_FEE_CAP_SATSMaximum fee per transaction100
X402_DAILY_BUDGET_SATSDaily delegation budget10000000
X402_BROADCASTERBroadcast backend (arc, woc, mock)arc
X402_REDIS_URLRedis connection string (optional)In-memory pools
X402_CHALLENGE_TTLChallenge expiry duration300s

Docker Deployment

Terminal
# Build and run with Docker Compose
docker compose up -d

# Or build individual images
docker build -t x402-gateway -f Dockerfile.server .
docker build -t x402-delegator -f Dockerfile.delegator .

API Reference

Endpoints exposed by the gateway and delegator.

Protected Endpoints (any path behind the gatekeeper middleware)

Any endpoint behind the x402 middleware returns 402 Payment Required with X402-Challenge header on unpaid requests. Paid requests include X402-Proof and X402-Tx headers.

Fee Delegator

MethodPathDescription
POST/delegate/x402Submit partial tx for fee delegation and signing

Dashboard API

MethodPathDescription
GET/api/v1/statsPool statistics, request counts, revenue
GET/api/v1/events/streamSSE stream of real-time gateway events
GET/api/v1/treasuryTreasury UTXO state and settlement tracking
GET/api/v1/broadcast/healthBroadcaster backend health status
GET/api/v1/configCurrent gateway configuration

Project Structure

Go monorepo with TypeScript client SDK and React dashboard.

Repository layout
x402-bsv/
├── cmd/
│   ├── server/        # Main gateway binary
│   ├── delegator/     # Standalone fee delegator
│   ├── keygen/        # Key generation utility
│   ├── setup/         # Initial setup tool
│   └── client/        # CLI test client
├── internal/
│   ├── gatekeeper/    # 402 middleware, challenge gen, proof verification
│   ├── delegator/     # Partial tx validation, fee injection, signing
│   ├── broadcast/     # Multi-backend tx broadcaster (ARC, WoC, Mock)
│   ├── pool/          # UTXO pool management (nonce, fee, payment)
│   ├── challenge/     # Challenge building, canonical hashing
│   ├── treasury/      # Treasury watcher, fanout, sweep, refill
│   ├── replay/        # LRU + TTL replay detection cache
│   ├── hdwallet/      # BIP32 HD key derivation
│   ├── pricing/       # Pluggable pricing (fixed, per-byte)
│   └── dashboard/     # Dashboard API handlers
├── client-js/         # @merkleworks/x402-client (TypeScript)
│   └── src/
│       ├── client.ts      # X402Client — drop-in fetch replacement
│       ├── challenge.ts   # Challenge parsing, canonical hashing
│       ├── transaction.ts # Partial transaction building
│       ├── proof.ts       # Proof header generation
│       ├── delegator.ts   # Gateway communication
│       └── broadcaster.ts # ARC broadcast integration
├── dashboard/         # React + TypeScript + Vite
│   └── src/
│       ├── MonitorTab.tsx
│       ├── TreasuryTab.tsx
│       ├── AnalyticsTab.tsx
│       └── SettingsTab.tsx
├── docs/              # Additional documentation
├── Dockerfile.server
├── Dockerfile.delegator
├── docker-compose.yml
├── Makefile
└── go.mod

Governance

Authority hierarchy for specification and implementation.

TierDocumentAuthority
0North Star / Constitutional StatementFoundational vision. Invariants. Non-negotiable boundaries.
0.5Adoption DoctrineFunding mode definitions. Economic narrative.
1Protocol Spec (Wire-Level)Normative wire contract. Scheme, challenge, proof, hashing, verification.
2Implementation SpecReference implementation mapping. Delegator contract.
3Architecture / ModelsLayer separation. Threat model. Economic model.
4+External / EditorialWhitepapers, READMEs, marketing. Descriptive only.
In case of conflict on wire behavior, Tier 1 (Protocol Spec) prevails. Tier 0 constitutional documents remain authoritative for invariants and governance. Changes to Tier 0 or Tier 1 require explicit version increment.