Repository navigation
Description
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 → receiveHTTP 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:
- Serves blobs over HTTP(S) — including HTTP/3 — addressed by BLAKE3 hash.
- Returns
402 Payment Requiredper the x402 spec, with payment requirements,
for requests not yet covered by a payment. - Verifies the x402 payment (via a facilitator), then fetches the blob over the
existingcdn/client/v1path 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.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
github-actions commentedon Jun 10, 2026
🎯 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
architecture,agentic-workflows,economics,missing-decision,medium🔗 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. A038-http-gateway.mdADR should be written before implementation. Key questions it needs to settle:Deployment model. Separate binary (e.g.,
decdn-gateway, analogous to thedecdn-node/decdnsplit in Splitdecdninto separate node and client binaries #421), or a built-in optional listener mode ondecdn-node? A separate binary keepsdecdn-node's QUIC-only surface clean and ships independently as proposed.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.
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.
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/v1path, not implement its own routing.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.Caching. Can the gateway reuse the
cachecrate for local blob caching after the first pull? This would reduce repeat x402 overhead for popular blobs.New crate. Likely lives at
crates/gateway/to follow the existing workspace layout. It would depend oncommon,protocol,incentive(for channel vouchers), andcache.Sub-tasks checklist (after ADR):
crates/gateway/crate to Cargo workspace402 Payment Requiredresponse + facilitator verificationdecdn-gatewaybinary wiring (similar tocrates/node/bring-up pattern)Add this agentic workflows to your repo
To install this agentic workflow, run
thiras commentedon Jun 19, 2026
Issue #866 —
decdn-gateway: optional x402 HTTP/3 payment edgeContext
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-channelvouchers (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:
HTTP 402 Payment Required) standard and expect a plainrequest → pay → receiveflow.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-gatewaybinary in a newcrates/gateway/crate (mirrors thedecdn-node/decdnsplit);HTTP/3 from day one via a
quinn+h3stack (with HTTP/1.1+2 fallback required for first contactAlt-Svcupgrade).This is a
missing-decisionissue: repo policy (CLAUDE.mdsingle-source-of-truth) requires an ADRfor 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-clibin crate, which the workspace marks"only ever a dev-dependency" — the gateway cannot depend on it.
cdn/client/v1paid fetch (stream_fetch_tracked,open_progressive_pull)crates/client-pull/src/lib.rsopen_channel,ensure_allowance)crates/client-pull/src/buyer_channel.rsBuyerChannelStore,RedbBuyerChannelStore,AdvanceOutcome)crates/incentive/src/buyer_channel*.rsactive_nodes,select_candidates,rank)crates/cli/src/commands/discovery.rsprobe_once)crates/cli/src/commands/probe_client.rscrates/cli/src/commands/client_endpoint.rsPhase 0 = a pure refactor (no behavior change): move
discovery.rs,probe_client.rs,client_endpoint.rs, andchain_ctx::build_providerfromcrates/cli/src/commands/into newpublic modules in
decdn-client-pull(discovery,probe,endpoint); repointcrates/cli/src/commands/fetch.rs+bundle_pull.rsimports; move the accompanying tests. Thisunblocks everything and keeps a single discovery implementation shared by CLI + gateway.
Note: discovery is registry+probe (
CapacityBond.getActiveNodes→cdn/probe/v1has_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
discoveryinterfacelater.
Request flow
GET /blob/{blake3hash}over HTTP/1.1, HTTP/2, or HTTP/3.402 Payment Requiredwith an x402PaymentRequirementsbody.X-PAYMENTheader. Gateway: verifies via a trusted facilitator (+ localEIP-712/EIP-3009 pre-check) → fetches the blob over
cdn/client/v1(paying the serving node froma long-lived buyer channel the gateway operator pre-funds) → streams bytes back →
/settles thex402 payment for the actual MB served → attaches
X-PAYMENT-RESPONSE.The gateway is HTTP-only at the edge and a plain
cdn/client/v1client downstream — no newdeCDN ALPN, no
crates/protocolchange, no node-side change. Two QUIC endpoints coexist in-processand stay separate: the iroh endpoint (downstream dials) and the quinn endpoint (upstream H3
edge listener).
x402 wire shapes (for the ADR +
x402/module){ x402Version, accepts: PaymentRequirements[], error? }.scheme("exact"),network(CAIP-2, e.g.eip155:8453),maxAmountRequired,resource,description,mimeType,outputSchema,payTo,maxTimeoutSeconds,asset(USDC addr),extra.PaymentPayload):x402Version,scheme,network,payload. For the exact-EVM schemepayload={ authorization: { from, to, value, validAfter, validBefore, nonce }, signature }(EIP-3009transferWithAuthorization)./verify→{ isValid, invalidReason?, payer }./settle→{ success, errorReason?, transaction|txHash, network, payer }.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.
price_micro_usdc_per_mb(edge retail ≥ expected upstreamrate_per_mb+margin).
maxAmountRequired = price_per_mb × max_blob_mb(authorize an upper bound), then/settles onlythe actual MB (EIP-3009 authorize-an-upper-bound, capture-≤-authorized) → change handled with no
on-chain refund. (No
HEADsize-probe path in v1 — avoids a free unpaid data-plane probe.)min_charge_mb(default 1 MB) covers the voucher interval + facilitator fee fordust blobs.
max_blob_mb(default 1024) feedsstream_fetch_tracked'smax_blob_size_bytesceiling; an over-ceiling upstream
total_bytes→ HTTP 502 and the x402 payment is neversettled (client keeps funds).
RedbBuyerChannelStore, fundedfrom 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 averified X-PAYMENT +
settle_amount(actual_bytes) -> micro_usdcclamped to[min, authorized].On fetch failure → skip
/settle(release authorization).nonce→ cached result, so a clientretrying 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.defense-in-depth pre-check (
x402/evm.rs): recover the EIP-712/EIP-3009 signer withalloyandconfirm
network/asset/payTo/value ≤ maxAmountRequiredbefore trusting/verify.FacilitatorClienttrait so tests inject a mock.Crate layout —
crates/gateway/Downstream fetch (
fetcher.rs) — concrete reuseBring-up:
RedbBuyerChannelStore::open(&data_dir),decdn_incentive::eth_identity::load_signer(...), providers (read-only + wallet viaProviderBuilder),voucher_domain/slash_judge_domain,client_pull::endpoint::client_endpoint,CacheEngine::open_full(...).Per fetch:
cache.get(hash)→ on missdiscovery::active_nodes+select_candidates→probe::probe_once+discovery::rank→store.get_by_providerelseensure_allowance+buyer_channel::open_channel+store.record→open_progressive_pull(...)loopUpstreamPull::next_chunk()(forward to HTTP body and tee intocache.open_tee_sink) +finish()whole-blob BLAKE3 check →store.advance_progress(...)perAdvanceOutcome.(Start with buffered
stream_fetch_trackedin 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"(rawserver 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-rsprovider — no new crypto provider). Enable
hyperhttp2feature 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 aTCP (hyper+tokio-rustls) and a UDP/QUIC (quinn+h3) listener on the same port;
http/request.rsisshared.
Config —
[gateway]section (5-site surfacing)Per the repo config-knob convention, every knob touches 5 sites:
crates/common/src/config/types.rs—pub gateway: Option<GatewayConfig>onFileConfig+GatewayConfigstruct (allOption<_>,#[serde(deny_unknown_fields)], modeled onReceiptsConfig).crates/common/src/config/resolved.rs—ResolvedGateway+ field onResolvedConfig.crates/common/src/config/mod.rs— resolver worker (CLI>TOML>defaults) +DEFAULT_*consts +validation invariants + round-trip tests.
crates/cli/src/commands/config.rs—[gateway]in theDEFAULT_CONFIGtemplate and theconfig validatesummary.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_addresschecksum-valid. Never echorpc_url/facilitator userinfo in errors (reuseredact_userinfo/sanitize_rpc_display, per #954).Workspace / CI
Cargo.toml: add"crates/gateway"tomembers; add new external deps to[workspace.dependencies]; adddecdn-gateway = { path = "crates/gateway" }.cargo deny:quinn/h3/h3-quinnare MIT/Apache-2.0 (compatible). Watchmultiple-versions—pin
quinn/rustls/ring(aws-lc-rs) to the iroh-aligned tree; document any new acceptedmultiple-versionsin the existing rootCargo.tomlcomment style.[lints] workspace = true: edition 2024, MSRV 1.95,max_width=100, anti-panicdenies (
unwrap/expect/panic/indexing_slicing) — H3/quinn glue must route errors througherror.rs, no panics.contracts/forgeunaffected (no new Solidity; reusesPaymentChannel/CapacityBondbindings).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
build_providercli→client-pull;repoint
fetch.rs/bundle_pull.rs; move tests. Verifycargo nextest run -p decdn-cli -p decdn-client-pullgreen.[gateway]config across the 5 sites;runtime.rsbinds H1/H2 with/healthzonly.fetcher.rsdownstream paid fetch (temporary always-allow gate) end-to-end.x402/*+bridge.rs) with unit tests.http/h3.rs+ Alt-Svc; sharedrequest.rs); progressive streaming.Verification
cargo build && cargo clippy --workspace --all-targets(anti-panic + pedantic denies are the usualCI 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).maxAmountRequiredmath + min/max clamp; X-PAYMENT base64round-trip + malformed rejection; EIP-3009 signer recovery (known fixture) + wrong-
payTo/asset/over-
valuerejection;settle_amountclamping + blob-too-large→no-settle; error→status mapping.tests/e2e_x402_to_blob.rs): in-processdecdn-node(seeded blob, loopback iroh,local anvil/
alloytest chain withPaymentChannel/CapacityBondfrom incentive test scaffolding)FacilitatorClient. Assert: (1)GET→ 402 + validPaymentRequirements;(2) retry with
X-PAYMENT→ 200, body BLAKE3-matches hash,X-PAYMENT-RESPONSEpresent, buyerstore advanced (a real voucher paid the node); (3) repeat
GET→ gateway cache hit, no new voucher;(4) H3 happy-path variant via a
quinn+h3test client.alpergundogdu commentedon Jun 30, 2026
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 privateinternalideas tracker rather than carried as an ADR here.The gateway needs no protocol change: no new ALPN, no
crates/protocolchange, no node-side change. It's HTTP-only at the edge and a plaincdn/client/v1client 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-pulllibrary and thedecdn-clibin crate (discovery / probe / client-endpoint / provider builder), which nothing can depend on. Promoting those into publicdecdn-client-pullmodules 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.chore(deps): update iroh-blobs to 0.104 and bao-tree to 0.17 (#2745)