Kyle Luecke

technical note 01 · cryptographic protocols & wire formats

Deterministic JSON Canonicalization and Fifteen-State Verification Precedence in paxiom.receipt.v0

Why HTTP 200 OK plus an on-chain payment header fails to bind delivered payload bytes, how recursive UTF-16 key canonicalization and strict base64 decoding eliminate malleability, and why autonomous callers need an ordered fifteen-state verification lattice rather than a boolean flag.

Kyle W. Luecke 2026-11-15 11 min read Source: standards/receipts/v0 ↗

1. The Protocol Binding Gap in Paid HTTP Exchanges

In HTTP-native micropayment flows such as x402, a client receives an HTTP 402 Payment Required challenge, signs an EIP-3009 TransferWithAuthorization payload (or submits a pre-funded authorization header), and retries the request. When the server responds with HTTP 200 OK and a base64-encoded PAYMENT-RESPONSE header citing an EVM transaction hash, two facts are established independently:

  1. An ERC-20 Transfer(from, to, value) event either settled or was broadcast on the target chain (for example, Circle USDC on Base Mainnet, eip155:8453).
  2. A TLS session delivered a sequence of HTTP response bytes to the caller.

What is missing is a cryptographic commitment linking the two. EIP-3009's typed EIP-712 struct commits to (from, to, value, validAfter, validBefore, nonce), where nonce is typically a random 32-byte value chosen prior to response generation. Once TLS terminates at a gateway, reverse proxy, or client process, nothing in the on-chain transaction log proves which HTTP resource was queried, what request body was sent, or whether the JSON response body was truncated, substituted, or an upstream error envelope delivered after payment capture.

On-chain log: Transfer(payer, payTo, amount) [commits funds movement only]
Receipt input: Ed25519.Sign_sk( UTF8( JCS({ receiptVersion, payload }) ) )
where payload binds: requestHash || paymentRequirementsHash || paymentPayloadHash || txHash || outputHash

Closing that gap without requiring synchronous on-chain calldata bloat on every API call requires a transport-level receipt header (Payment-Receipt, with X-Paxiom-Receipt backward compatibility) whose signature covers canonical digests of the request, the payment negotiation, and the delivered output — and whose verifier refuses to conflate signature validity with signer authorization or settlement finality.

2. Canonical JSON Serialization Hazards Across Runtimes

Signing raw HTTP wire bytes works until a receipt or JSON payload crosses an API gateway, structured logger, message queue, or cross-language SDK boundary (Node.js/V8 to Python 3.10+) that parses and re-serializes JSON objects. Object key insertion order, insignificant whitespace, and numeric formatting vary across serializers unless pinned to an explicit canonical profile (RFC 8785 JSON Canonicalization Scheme, JCS).

In paxiom.receipt.v0, both the Ed25519 signing preimage and every JSON SHA-256 digest (outputHash, bodyHash, requestHash, paymentRequirementsHash, paymentPayloadHash) pass through a strict recursive canonicalizer before UTF-8 encoding:

export const MAX_DEPTH = 256;

export function canonicalize(value, depth = 0) {
  if (depth > MAX_DEPTH) {
    throw new RangeError(`canonicalize: nesting exceeds max depth ${MAX_DEPTH}`);
  }
  if (value === undefined) {
    throw new TypeError('canonicalize: undefined is not representable');
  }
  const t = typeof value;
  if (t === 'function' || t === 'symbol' || t === 'bigint') {
    throw new TypeError(`canonicalize: ${t} is not representable in canonical JSON`);
  }
  if (t === 'number' && !Number.isFinite(value)) {
    throw new TypeError('canonicalize: non-finite numbers (NaN, Infinity) are not representable');
  }
  if (value === null || t !== 'object') return JSON.stringify(value);
  if (typeof value.toJSON === 'function') {
    return canonicalize(value.toJSON(), depth + 1);
  }
  if (value instanceof Map || value instanceof Set || value instanceof RegExp) {
    throw new TypeError('canonicalize: Map, Set, and RegExp instances are not representable');
  }
  if (Array.isArray(value)) {
    return '[' + value.map((v) => canonicalize(v, depth + 1)).join(',') + ']';
  }
  return '{' + Object.keys(value).sort()
    .map((k) => JSON.stringify(k) + ':' + canonicalize(value[k], depth + 1))
    .join(',') + '}';
}

Several subtle cross-runtime failure modes motivate each guard in those twenty-five lines:

  • Silent NaN / Infinity / undefined coercion in JSON.stringify: Standard JavaScript JSON.stringify({ a: NaN, b: undefined }) silently emits {"a":null} instead of throwing, while Python's default json.dumps emits invalid JSON literal NaN unless allow_nan=False is set. Allowing silent coercion lets an upstream bug sign null where a numeric measurement was expected. Explicit TypeError rejection forces both runtimes to fail closed.
  • Map, Set, and RegExp empty-object collapse: In V8, typeof new Map() === 'object' and Object.keys(new Map()) is [], so a naive recursive serializer without prototype checks silently canonicalizes any non-empty Map or Set to "{}", causing distinct objects to collide under the same SHA-256 outputHash.
  • UTF-16 code-unit key ordering vs. Unicode scalar ordering: JavaScript's Array.prototype.sort() orders strings by UTF-16 code units, matching RFC 8785 §3.2.3. In Python, str comparison orders by Unicode code points, which agrees with UTF-16 code-unit order across the entire Basic Multilingual Plane except when a key in U+E000..U+FFFF is compared against a supplementary plane character (> U+FFFF, encoded as a UTF-16 surrogate pair in 0xD800..0xDBFF). Cross-language SDK parity therefore requires sorting Python keys by k.encode('utf-16-be') rather than raw code-point order.
  • IEEE-754 negative zero and atomic integer strings: Under ECMAScript Number::toString (and RFC 8785), JSON.stringify(-0) deterministically yields "0". For token quantities where 53-bit IEEE-754 mantissas overflow (2^53 - 1 is ~9e15 wei, less than 0.01 ETH), paxiom.receipt.v0 forbids JSON numbers altogether and schemas amountAtomic as a base-10 integer string (^[0-9]+$).
  • Bounded recursion depth (MAX_DEPTH = 256): An adversarial caller submitting {"a":{"a":...}} nested 20,000 levels deep to an offline verifier would otherwise trigger an uncaught V8 Maximum call stack size exceeded crash. Catching RangeError inside verifyReceipt maps pathological outputs cleanly to trustState: "error" without terminating the verifier process.

3. Non-Malleable Base64 Decoding on Keys and Signatures

Node.js's built-in Buffer.from(str, 'base64') is deliberately forgiving: it strips whitespace and non-alphabet characters, accepts missing = padding, and ignores non-zero trailing pad bits. If a verifier decodes signature.publicKey (32 bytes) or signature.value (64 bytes) permissively, two distinct receipt JSON strings can verify against the same canonical signing input while producing different envelope hashes or bypassing naive string-set key lookups.

To prevent representation malleability, verify.mjs enforces a canonical round-trip byte check before passing key or signature buffers to OpenSSL / RFC 8032 Ed25519 verification:

const STRICT_BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;

function strictDecodeBase64(value, expectedByteLength, label) {
  if (
    typeof value !== 'string' ||
    value.length === 0 ||
    value.length % 4 !== 0 ||
    !STRICT_BASE64_RE.test(value)
  ) {
    throw new Error(`${label} must be canonical base64`);
  }
  const raw = Buffer.from(value, 'base64');
  if (raw.length !== expectedByteLength || raw.toString('base64') !== value) {
    throw new Error(`${label} must decode to ${expectedByteLength} canonical bytes`);
  }
  return raw;
}

The condition raw.toString('base64') === value rejects non-zero pad bits in the final quantum (for instance, modifying the last character of a 44-character base64 string where 2 low bits are unused by 32 decoded bytes), ensuring a 1-to-1 bijection between valid 32-byte Ed25519 public keys and strings in trustedPaxiomPublicKeys.

4. Why Boolean Verification Is Unsafe: The 15-State Precedence Lattice

Suppose a seller signs a syntactically valid receipt asserting payment.settlement.status = "verified_settled" and transactionHash = "0xabc...". An offline verifier running inside an agent process has no RPC connection to Base Mainnet. If that offline verifier returns { valid: true } simply because the seller's Ed25519 signature and outputHash match, a malicious seller can fabricate an arbitrary 32-byte hex string as a "settled" transaction hash and pass offline verification. Conversely, if the offline verifier returns { valid: false } with no structured distinction, callers cannot tell a forged signature apart from an unverified on-chain claim that merely needs live log confirmation.

paxiom.receipt.v0 resolves this by making valid a strict alias for trustState === "verified" at the bottom of a deterministic evaluation order:

PrecedenceTrust StateTriggering Condition
01malformed_headerX-Paxiom-Receipt is not valid UTF-8 JSON under base64url decoding.
02unsupported_formatreceiptVersion !== "paxiom.receipt.v0".
03schema_invalidDraft-07 JSON Schema violation (missing required field, unexpected property, invalid RFC 3339 timestamp, malformed 0x SHA-256 hex).
04invalid_signaturepayload.issuer.keyId !== signature.keyId, non-canonical base64, or Ed25519 verification failure over signingInput(receipt).
04bunauthorized_issuer(Added in v0.2.0) Signature passes, but signature.publicKey is not in expectedIssuerPublicKeys (discovered from the seller's HTTPS /.well-known/x402-keys.json) or payTo mismatches expectedPayTo.
05expiredOptional payload.expiresAt precedes verifier wall clock.
06errorSupplied output exceeds MAX_DEPTH or contains non-JSON-representable types.
07output_hash_mismatchjcs-sha256 or raw-sha256 digest of output ≠ payload.delivery.outputHash (payload tampering or proxy substitution).
08settlement_failedReceipt explicitly records payment.settlement.status === "failed".
09–10proof_invalid / proof_unavailableAttached upstream evidence entry reports invalid or unavailable.
11settlement_claimed_not_checkedReceipt claims claimed_not_checked, claims verified_settled without a trusted counter-signature, asserts checkedByPaxiom: true from an untrusted key, or smuggles a non-null transactionHash under not_required / verify_only.
12valid_signature_onlySignature passes, but caller omitted output (so delivery binding was not checked) or settlement is unknown.
13verifiedSchema, Ed25519 signature, outputHash binding, and settlement rules all pass (either not_required free tier or verified_settled counter-signed by a key in trustedPaxiomPublicKeys).

Step 11 closes two subtle privilege-escalation vectors uncovered during adversarial testing:

  1. Self-asserted counter-attestation: Any seller holds their own Ed25519 private key and can sign a payload with checkedByPaxiom: true and status: "verified_settled". Offline verification only promotes a settled receipt to verified when Boolean(trustedPaxiomSet && trustedPaxiomSet.has(receipt.signature.publicKey)) holds against keys pinned from /.well-known/paxiom-keys.json.
  2. Transaction-hash smuggling under free-tier statuses: If an issuer sets status: "not_required" while populating a non-null settlement.transactionHash, naive downstream indexers that inspect if (result.valid && receipt.payload.payment.settlement.transactionHash) would treat an unchecked hash as verified. Step 11 explicitly traps any non-null transactionHash paired with not_required, disabled, or verify_only and demotes the verdict to settlement_claimed_not_checked.

5. Middleware Stream-Capture Hazards in Node.js HTTP Servers

Signing receipts automatically inside HTTP server middleware introduces two operational traps that do not appear in pure unit functions:

  • Truncated request-body signing under memory caps: To prevent unauthenticated memory exhaustion, Express/Connect middleware must bound how many request body bytes it buffers (MAX_CAPTURE = 256 * 1024). If a 1 MiB request arrives and the middleware hashes only the first 256 KiB, the seller signs a bodyHash that will never match the buyer's full request hash. When capturedBytes + chunk.length > MAX_CAPTURE, createReceiptMiddleware sets reqCapped = true, discards buffered chunks, and skips receipt emission rather than signing a false prefix digest.
  • Accidental Promise object spreading in synchronous res.end hooks: Unlike Web Standard Fetch handlers (async (req) => Response), Node's http.ServerResponse.prototype.end flushes headers synchronously. If a caller mistakenly passes an async function resolvePayment() to createReceiptMiddleware, invoking it returns a pending Promise object. In JavaScript, object-spreading a Promise ({ ...paymentDefaults, ...dynamicPayment }) copies zero own enumerable properties and silently signs amountAtomic: "0"! The middleware therefore checks both resolvePayment.constructor.name === 'AsyncFunction' at registration time and typeof dynamicPayment.then === 'function' at runtime, refusing to emit a mis-bound receipt.