Skip to content

gateway: optional x402 HTTP payment edge for non-QUIC (browser/agent) clients #866

Closed

Description

@thiras

Context

deCDN's data plane delivers BLAKE3-addressed blobs over iroh QUIC using custom
binary ALPNs (cdn/probe/v1, cdn/client/v1), and clients pay per-MB via
off-chain USDC payment-channel vouchers (ADR 003). This is the right design for
the core data plane: sub-cent, streaming, bidirectional (client→node and
node→node) micropayments that settle on-chain only ~3 times per channel
lifecycle.

That design hard-couples paying for content to being able to speak deCDN's
QUIC ALPN and operate an L2 payment channel
. Two large client classes cannot
do that today:

  • Browsers — cannot open arbitrary QUIC connections with custom ALPNs, and
    cannot manage a wallet + payment channel without a heavy extension.
  • AI agents / generic HTTP tooling — increasingly transact via the emerging
    x402 (HTTP 402 Payment Required) standard and expect a plain
    request → pay → receive HTTP flow.

Problem

There is no HTTP front door to deCDN, so the network is unreachable to the
largest population of potential consumers and to the growing x402 agent
ecosystem.

Proposal

Add an optional, edge-only HTTP gateway (new component; ships independently
of decdn-node) that:

  1. Serves blobs over HTTP(S) — including HTTP/3 — addressed by BLAKE3 hash.
  2. Returns 402 Payment Required per the x402 spec, with payment requirements,
    for requests not yet covered by a payment.
  3. Verifies the x402 payment (via a facilitator), then fetches the blob over the
    existing cdn/client/v1 path and settles into a normal ADR 003 payment
    channel behind the scenes
    .

Key framing

x402 is additive at the edge, NOT a replacement for payment channels.
Per-MB streaming economics still require channels underneath: an on-chain settle
per payment (~$0.05–0.10) is economically impossible at the ~$0.00001/MB market
rate (ADR 003 "Context"). The gateway's job is to translate coarse-grained HTTP
payments into the fine-grained voucher flow the data plane already speaks.

Activity

  1. added
    kind:feature
    on Jun 10, 2026
  2. added
    design:economics
    prio:medium
    design:missing-decision
    on Jun 10, 2026
  3. github-actions commented on Jun 10, 2026

    @github-actions

    🎯 Triage report

    This is a well-framed proposal for a new optional edge gateway component that bridges browser and AI-agent HTTP clients (via x402 / HTTP 402) into deCDN's existing iroh QUIC + ADR 003 payment-channel data plane. The author correctly identifies x402 as additive—not a replacement—and the payment translation model (coarse x402 → fine-grained vouchers) is architecturally sound given ADR 003's on-chain economics. No ADR exists yet for this component, which is the main blocker before implementation can begin.

    📊 Assessment

    Dimension Value Reasoning
    Type Feature New standalone component with new payment protocol integration
    Labels architecture, agentic-workflows, economics, missing-decision, medium New top-level component (arch); AI/agent x402 use-case explicit (agentic-workflows); payment bridging (economics); no ADR exists yet (missing-decision); strategically important but not PoC-blocking (medium)
    Coding agent Not suitable Requires a new ADR and architectural design decisions before any implementation can start; scope, deployment model, and x402 facilitator trust model are all undefined

    🔗 Similar issues

    No duplicate issues found. Issue #402 (client priority staking edge cases) is loosely related through ADR 003 payment channels but covers a completely different problem.

    💡 Notes and suggestions

    ADR required first. Per CLAUDE.md, the next ADR number is 038. A 038-http-gateway.md ADR should be written before implementation. Key questions it needs to settle:

    1. Deployment model. Separate binary (e.g., decdn-gateway, analogous to the decdn-node / decdn split in Split decdn into separate node and client binaries #421), or a built-in optional listener mode on decdn-node? A separate binary keeps decdn-node's QUIC-only surface clean and ships independently as proposed.

    2. x402 facilitator trust model. Which x402 facilitators does the gateway accept? Should facilitators be a node-operator config list, a registry, or a well-known default? Trust here directly impacts payment security.

    3. Payment granularity impedance mismatch. x402 is typically per-request; ADR 003 channels are per-MB streaming. The gateway needs a defined reconciliation strategy—e.g., pre-fund a channel chunk from the x402 receipt, then stream against it. The ADR should specify the minimum/maximum blob size for a single x402 payment and how change is handled.

    4. Blob resolution. The gateway still needs to find which nodes hold a given BLAKE3 hash (DHT / ADR 022). It should integrate with the existing cdn/dht/v1 path, not implement its own routing.

    5. HTTP/3 specifics. The proposal mentions HTTP/3; iroh already uses QUIC underneath. Whether the gateway can share the iroh QUIC endpoint or needs a separate HTTP/3 stack (e.g., quinn + h3) should be decided early—it affects the crate dependency graph.

    6. Caching. Can the gateway reuse the cache crate for local blob caching after the first pull? This would reduce repeat x402 overhead for popular blobs.

    7. New crate. Likely lives at crates/gateway/ to follow the existing workspace layout. It would depend on common, protocol, incentive (for channel vouchers), and cache.

    Sub-tasks checklist (after ADR):

    • Write ADR 038 covering the above decisions
    • Add crates/gateway/ crate to Cargo workspace
    • Implement HTTP server (axum or hyper) with x402 402 Payment Required response + facilitator verification
    • Implement x402 → ADR 003 voucher bridge (payment channel open/fund/voucher generation)
    • Integrate DHT lookup for blob resolution
    • Add decdn-gateway binary wiring (similar to crates/node/ bring-up pattern)
    • Integration test: full x402 → blob delivery flow

    Generated by Agentic Triage for issue #866 · sonnet46 641.2K · ◷

    Add this agentic workflows to your repo

    To install this agentic workflow, run

    gh aw add githubnext/agentics/workflows/issue-triage.md@94ec5db57374c5b04a4b8eef8b4413f9af44d63f
    
  4. self-assigned this
    on Jun 19, 2026
  5. thiras commented on Jun 19, 2026

    @thiras
    ContributorAuthor

    Issue #866 — decdn-gateway: optional x402 HTTP/3 payment edge

    Context

    deCDN's data plane delivers BLAKE3-addressed blobs over iroh QUIC with custom binary ALPNs
    (cdn/probe/v1, cdn/client/v1) and clients pay per-MB via off-chain USDC payment-channel
    vouchers (ADR 003). That design hard-couples paying for content to speaking deCDN's QUIC ALPN
    and running an L2 payment channel
    . Two large client classes are locked out today:

    • Browsers — cannot open custom-ALPN QUIC nor manage a wallet+channel without a heavy extension.
    • AI agents / generic HTTP tooling — transact via the emerging x402 (HTTP 402 Payment Required) standard and expect a plain request → pay → receive flow.

    There is no HTTP front door to deCDN, so the network is unreachable to the largest consumer
    population and the x402 agent ecosystem. This issue adds an optional, edge-only HTTP gateway
    that translates one coarse x402 HTTP payment per request into the fine-grained per-MB voucher flow
    the data plane already speaks. x402 is additive at the edge, NOT a replacement for payment
    channels
    — an on-chain settle per request (~$0.05–0.10) is impossible at the ~$0.00001/MB market
    rate; channels remain underneath.

    Decisions confirmed with the user: full implementation (not just an ADR/scaffold); a separate
    decdn-gateway binary
    in a new crates/gateway/ crate (mirrors the decdn-node/decdn split);
    HTTP/3 from day one via a quinn+h3 stack (with HTTP/1.1+2 fallback required for first contact

    • Alt-Svc upgrade).

    This is a missing-decision issue: repo policy (CLAUDE.md single-source-of-truth) requires an ADR
    for a new top-level component before merge. The next ADR number is 040 (verified by listing
    adr/; the triage comment's "038" is stale — 038/039 are taken).


    The load-bearing finding (Phase 0 prerequisite)

    The downstream "discover a node → probe → open/reuse a channel → paid-fetch" logic already exists,
    but the discovery half lives in the decdn-cli bin crate, which the workspace marks
    "only ever a dev-dependency" — the gateway cannot depend on it.

    Capability Location now Reusable?
    cdn/client/v1 paid fetch (stream_fetch_tracked, open_progressive_pull) crates/client-pull/src/lib.rs ✅ library
    Buyer-channel open (open_channel, ensure_allowance) crates/client-pull/src/buyer_channel.rs ✅
    Buyer-channel store/state (BuyerChannelStore, RedbBuyerChannelStore, AdvanceOutcome) crates/incentive/src/buyer_channel*.rs ✅
    Active-node discovery + rank (active_nodes, select_candidates, rank) crates/cli/src/commands/discovery.rs ❌ in bin crate
    Probe (probe_once) crates/cli/src/commands/probe_client.rs ❌ in bin crate
    Client iroh endpoint builder crates/cli/src/commands/client_endpoint.rs ❌ in bin crate

    Phase 0 = a pure refactor (no behavior change): move discovery.rs, probe_client.rs,
    client_endpoint.rs, and chain_ctx::build_provider from crates/cli/src/commands/ into new
    public modules in decdn-client-pull (discovery, probe, endpoint); repoint
    crates/cli/src/commands/fetch.rs + bundle_pull.rs imports; move the accompanying tests. This
    unblocks everything and keeps a single discovery implementation shared by CLI + gateway.

    Note: discovery is registry+probe (CapacityBond.getActiveNodes → cdn/probe/v1 has_blob →
    rank), not cdn/dht/v1 FIND_VALUE. That is the shipped, tested path (ADR 019/030) and is adequate;
    the triage's "integrate cdn/dht/v1" is aspirational and slots behind the same discovery interface
    later.


    Request flow

    1. GET /blob/{blake3hash} over HTTP/1.1, HTTP/2, or HTTP/3.
    2. Not yet paid → 402 Payment Required with an x402 PaymentRequirements body.
    3. Client retries with X-PAYMENT header. Gateway: verifies via a trusted facilitator (+ local
      EIP-712/EIP-3009 pre-check) → fetches the blob over cdn/client/v1 (paying the serving node from
      a long-lived buyer channel the gateway operator pre-funds) → streams bytes back → /settles the
      x402 payment for the actual MB served → attaches X-PAYMENT-RESPONSE.

    The gateway is HTTP-only at the edge and a plain cdn/client/v1 client downstream — no new
    deCDN ALPN
    , no crates/protocol change, no node-side change. Two QUIC endpoints coexist in-process
    and stay separate: the iroh endpoint (downstream dials) and the quinn endpoint (upstream H3
    edge listener).


    x402 wire shapes (for the ADR + x402/ module)

    • 402 body: { x402Version, accepts: PaymentRequirements[], error? }.
    • PaymentRequirements: scheme ("exact"), network (CAIP-2, e.g. eip155:8453),
      maxAmountRequired, resource, description, mimeType, outputSchema, payTo,
      maxTimeoutSeconds, asset (USDC addr), extra.
    • X-PAYMENT header (base64 JSON PaymentPayload): x402Version, scheme, network,
      payload. For the exact-EVM scheme payload = { authorization: { from, to, value, validAfter, validBefore, nonce }, signature } (EIP-3009 transferWithAuthorization).
    • Facilitator /verify → { isValid, invalidReason?, payer }.
    • Facilitator /settle → { success, errorReason?, transaction|txHash, network, payer }.
    • X-PAYMENT-RESPONSE (success): base64 JSON of the settle result.

    x402 ↔ ADR 003 reconciliation (the bridge)

    The gateway is a market-maker: it fronts per-MB voucher spend and recoups it via one x402
    payment per request. x402-in (operator revenue) ⟂ vouchers-out (operator cost) — they do not
    share a channel.

    • Pricing: config price_micro_usdc_per_mb (edge retail ≥ expected upstream rate_per_mb +
      margin).
    • Unknown size up front (hash doesn't encode size): the 402 advertises
      maxAmountRequired = price_per_mb × max_blob_mb (authorize an upper bound), then /settles only
      the actual MB
      (EIP-3009 authorize-an-upper-bound, capture-≤-authorized) → change handled with no
      on-chain refund. (No HEAD size-probe path in v1 — avoids a free unpaid data-plane probe.)
    • Min charge min_charge_mb (default 1 MB) covers the voucher interval + facilitator fee for
      dust blobs.
    • Max blob max_blob_mb (default 1024) feeds stream_fetch_tracked's max_blob_size_bytes
      ceiling; an over-ceiling upstream total_bytes → HTTP 502 and the x402 payment is never
      settled
      (client keeps funds).
    • Channels: one long-lived buyer channel per provider in RedbBuyerChannelStore, funded
      from the operator's own USDC — exactly the node's buyer side.
    • bridge.rs: PaymentBudget { authorized_micro_usdc, price_per_mb, min_mb, max_mb } from a
      verified X-PAYMENT + settle_amount(actual_bytes) -> micro_usdc clamped to [min, authorized].
      On fetch failure → skip /settle (release authorization).
    • Idempotency: bounded in-memory map keyed by EIP-3009 nonce → cached result, so a client
      retrying after a mid-stream drop is not double-settled.

    Facilitator trust model

    • gateway.facilitators = operator-curated allowlist of facilitator base URLs (HTTPS only);
      gateway.facilitator_default = well-known default so a turnkey deploy works.
    • Gateway never custodies client funds; it trusts the facilitator verdict plus a local
      defense-in-depth pre-check (x402/evm.rs): recover the EIP-712/EIP-3009 signer with alloy and
      confirm network/asset/payTo/value ≤ maxAmountRequired before trusting /verify.
    • FacilitatorClient trait so tests inject a mock.

    Crate layout — crates/gateway/

    Cargo.toml            # [[bin]] name = "decdn-gateway"; [lints] workspace = true
    src/
      main.rs             # thin clap shell -> runtime::run  (mirrors crates/node/src/main.rs)
      lib.rs              # re-exports, crate docs
      runtime.rs          # bring-up: load config+signer+store+endpoint+cache; bind H3 + H1/H2;
                          #   spawn metrics; JoinSet + oneshot shutdown (mirrors node runtime/mod.rs)
      http/
        mod.rs            # route GET /blob/{hash}, /healthz; Alt-Svc
        h3.rs             # quinn+h3 accept loop
        h1h2.rs           # hyper 1.x H1+H2 over tokio-rustls (carries Alt-Svc)
        request.rs        # protocol-agnostic handler: parse hash -> x402 gate -> serve
        response.rs       # Bytes -> h3/hyper body streaming; headers
      x402/
        mod.rs            # X-PAYMENT / X-PAYMENT-RESPONSE (de)serialization
        requirements.rs   # 402 body builder (maxAmountRequired math, min/max clamp)
        verify.rs         # FacilitatorClient trait + HttpFacilitator (/verify, /settle via reqwest)
        evm.rs            # local EIP-3009/EIP-712 signer recovery + field checks (alloy)
      bridge.rs           # PaymentBudget + settle_amount; nonce idempotency cache
      fetcher.rs          # downstream engine: client-pull discovery+probe+open_or_reuse+
                          #   stream_fetch_tracked (progressive) + CacheEngine tee/coalesce
      metrics.rs          # decdn_gateway_* registry + /metrics (hyper 1.x, mirrors node metrics.rs)
      error.rs            # GatewayError -> HTTP status (404/402/502/504); redaction
    tests/
      e2e_x402_to_blob.rs # in-process node + gateway full flow
    

    Downstream fetch (fetcher.rs) — concrete reuse

    Bring-up: RedbBuyerChannelStore::open(&data_dir),
    decdn_incentive::eth_identity::load_signer(...), providers (read-only + wallet via
    ProviderBuilder), voucher_domain/slash_judge_domain, client_pull::endpoint::client_endpoint,
    CacheEngine::open_full(...).
    Per fetch: cache.get(hash) → on miss discovery::active_nodes + select_candidates →
    probe::probe_once + discovery::rank → store.get_by_provider else ensure_allowance +
    buyer_channel::open_channel + store.record → open_progressive_pull(...) loop
    UpstreamPull::next_chunk() (forward to HTTP body and tee into cache.open_tee_sink) +
    finish() whole-blob BLAKE3 check → store.advance_progress(...) per AdvanceOutcome.
    (Start with buffered stream_fetch_tracked in Phase 3; switch to progressive in Phase 5/6.)


    Dependencies

    Internal (workspace = true): decdn-common, decdn-protocol, decdn-incentive, decdn-cache,
    decdn-client-pull.
    Reuse existing pins: tokio, anyhow, thiserror, tracing(+-subscriber), serde,
    serde_json, bytes, clap, alloy, reqwest, iroh, blake3, hyper/hyper-util/
    http-body-util, futures-util, url.
    New to [workspace.dependencies] (only cargo-deny-relevant adds): quinn = "0.11" (raw
    server QUIC for H3 — iroh doesn't expose one), h3 + h3-quinn (HTTP/3), rustls = "0.23" +
    rustls-pemfile = "2" + tokio-rustls = "0.26" (reuse the workspace rustls 0.23 + aws-lc-rs
    provider — no new crypto provider). Enable hyper http2 feature for the gateway.

    HTTP/1.1+2 fallback is required: H3 can't be first contact — client arrives over H1/H2, gateway
    responds with Alt-Svc: h3=":<port>"; ma=86400, client upgrades to H3 next request. Bind both a
    TCP (hyper+tokio-rustls) and a UDP/QUIC (quinn+h3) listener on the same port; http/request.rs is
    shared.


    Config — [gateway] section (5-site surfacing)

    Per the repo config-knob convention, every knob touches 5 sites:

    1. crates/common/src/config/types.rs — pub gateway: Option<GatewayConfig> on FileConfig +
      GatewayConfig struct (all Option<_>, #[serde(deny_unknown_fields)], modeled on
      ReceiptsConfig).
    2. crates/common/src/config/resolved.rs — ResolvedGateway + field on ResolvedConfig.
    3. crates/common/src/config/mod.rs — resolver worker (CLI>TOML>defaults) + DEFAULT_* consts +
      validation invariants + round-trip tests.
    4. crates/cli/src/commands/config.rs — [gateway] in the DEFAULT_CONFIG template and the
      config validate summary.

    Fields (defaults): enabled(false), http_bind(0.0.0.0), http_port(8443),
    tls_cert_path/tls_key_path (required when enabled), data_dir, cache_dir, cache_max_bytes,
    price_micro_usdc_per_mb, min_charge_mb(1), max_blob_mb(1024), pay_to_address
    (defaults to keystore address), x402_network, x402_asset, x402_scheme("exact"),
    facilitators(list), facilitator_default, fetch_timeout_ms, select_k, probe_timeout_ms.
    Reuse existing [blockchain] (rpc_url, contract addrs, chain_id), [identity], [network],
    [observability] (metrics) — do not duplicate.
    Invariants (when enabled): TLS cert+key present; non-empty facilitator set (or default);
    min_charge_mb ≤ max_blob_mb; price_micro_usdc_per_mb > 0; facilitator URLs parse + HTTPS;
    pay_to_address checksum-valid. Never echo rpc_url/facilitator userinfo in errors (reuse
    redact_userinfo/sanitize_rpc_display, per #954).


    Workspace / CI

    • Root Cargo.toml: add "crates/gateway" to members; add new external deps to
      [workspace.dependencies]; add decdn-gateway = { path = "crates/gateway" }.
    • cargo deny: quinn/h3/h3-quinn are MIT/Apache-2.0 (compatible). Watch multiple-versions —
      pin quinn/rustls/ring(aws-lc-rs) to the iroh-aligned tree; document any new accepted
      multiple-versions in the existing root Cargo.toml comment style.
    • Lints apply via [lints] workspace = true: edition 2024, MSRV 1.95, max_width=100, anti-panic
      denies (unwrap/expect/panic/indexing_slicing) — H3/quinn glue must route errors through
      error.rs, no panics.
    • contracts/forge unaffected (no new Solidity; reuses PaymentChannel/CapacityBond bindings).
    • CI builds/tests via existing workspace jobs; H3 e2e needs a UDP-capable runner (already true for
      iroh QUIC node tests).

    ADR 040

    Write adr/040-http-gateway.md (status Draft, no frontmatter; sections Context / Decision /
    Consequences / Cross-ADR Impact / References; inline [ADR NNN § …](NNN-file.md#anchor) citations).
    Decision must settle: separate-binary deployment, HTTP/3+fallback stack, the x402↔ADR003
    reconciliation (pricing, authorize-upper-bound/capture-actual, min/max, idempotency), the
    facilitator allowlist trust model, registry+probe blob resolution (cite ADR 022/019/030), and the
    Phase-0 client-pull extraction. Cite ADR 003 (payments), 016 (contracts), 022 (discovery),
    appendix-binaries. Bump CLAUDE.md's "Next ADR number" to 041 and add 040 to the canonical list.


    Phased sequence

    • Phase 0 — Extraction (prereq): move discovery/probe/endpoint/build_provider cli→client-pull;
      repoint fetch.rs/bundle_pull.rs; move tests. Verify cargo nextest run -p decdn-cli -p decdn-client-pull green.
    • Phase 1 — ADR 040 (the design decisions above; required before merge).
    • Phase 2 — Crate skeleton + [gateway] config across the 5 sites; runtime.rs binds H1/H2 with
      /healthz only.
    • Phase 3 — fetcher.rs downstream paid fetch (temporary always-allow gate) end-to-end.
    • Phase 4 — x402 layer (x402/* + bridge.rs) with unit tests.
    • Phase 5 — HTTP/3 (http/h3.rs + Alt-Svc; shared request.rs); progressive streaming.
    • Phase 6 — metrics, error mapping, idempotency, redaction, e2e test, cargo-deny review.

    Verification

    • cargo build && cargo clippy --workspace --all-targets (anti-panic + pedantic denies are the usual
      CI fail).
    • cargo fmt -- --check; cargo deny check (new quinn/h3 license + multiple-versions).
    • cargo nextest run -p decdn-gateway -p decdn-client-pull -p decdn-cli (Phase 0 move + new crate).
    • Unit: 402 body shape vs x402 spec; maxAmountRequired math + min/max clamp; X-PAYMENT base64
      round-trip + malformed rejection; EIP-3009 signer recovery (known fixture) + wrong-payTo/asset/
      over-value rejection; settle_amount clamping + blob-too-large→no-settle; error→status mapping.
    • Integration (tests/e2e_x402_to_blob.rs): in-process decdn-node (seeded blob, loopback iroh,
      local anvil/alloy test chain with PaymentChannel/CapacityBond from incentive test scaffolding)
      • gateway with a mock FacilitatorClient. Assert: (1) GET → 402 + valid PaymentRequirements;
        (2) retry with X-PAYMENT → 200, body BLAKE3-matches hash, X-PAYMENT-RESPONSE present, buyer
        store advanced (a real voucher paid the node); (3) repeat GET → gateway cache hit, no new voucher;
        (4) H3 happy-path variant via a quinn+h3 test client.
  6. alpergundogdu commented on Jun 30, 2026

    @alpergundogdu
    Contributor

    Closing — out of scope for this repo. The decdn-gateway (x402 HTTP/3 payment edge) is an optional, operator-run edge product built on top of deCDN, not a protocol change, so the full design + phased implementation plan is parked in the private internal ideas tracker rather than carried as an ADR here.

    The gateway needs no protocol change: no new ALPN, no crates/protocol change, no node-side change. It's HTTP-only at the edge and a plain cdn/client/v1 client downstream.

    One follow-up does belong in this repo and is worth doing on its own merits, independent of whether the gateway ships: the client fetch path is split between the reusable decdn-client-pull library and the decdn-cli bin crate (discovery / probe / client-endpoint / provider builder), which nothing can depend on. Promoting those into public decdn-client-pull modules is a pure refactor (no behavior change) that removes a duplicated discovery path and gives the repo one documented client-fetch surface. Suggest tracking that as a small standalone refactor issue if/when desired — no ADR required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

design:economicsdesign:missing-decisionkind:featureprio:medium

Type

No type

Fields

Priority

None yet

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions