# AI Agent Payment Integration Design for Fiber Network
**Date**: 2026-04-07 (u…pdated 2026-04-14)
**Status**: Draft
**Author**: Design Research
---
## Table of Contents
1. [Executive Summary](#1-executive-summary)
2. [Background & Motivation](#2-background--motivation)
3. [Protocol Survey](#3-protocol-survey)
- 3.1 [x402 (Coinbase)](#31-x402-coinbase)
- 3.2 [Stripe Agent Commerce Protocol (ACP)](#32-stripe-agent-commerce-protocol-acp)
- 3.3 [L402 (Lightning Labs)](#33-l402-lightning-labs)
- 3.4 [Fiber Native Agent Protocol](#34-fiber-native-agent-protocol)
4. [Fiber Technical Capabilities](#4-fiber-technical-capabilities)
5. [Application Scenarios](#5-application-scenarios)
6. [L402 vs Fiber Native Agent Protocol: Deep Comparison](#6-l402-vs-fiber-native-agent-protocol-deep-comparison)
- 6.0 [Relationship Positioning](#60-relationship-positioning)
7. [Token Delegation: Macaroon vs Biscuit](#7-token-delegation-macaroon-vs-biscuit)
8. [Fair Exchange Problem & Settlement Strategies](#8-fair-exchange-problem--settlement-strategies)
9. [Strategic Recommendation: Dual-Track Approach](#9-strategic-recommendation-dual-track-approach)
10. [Implementation Roadmap](#10-implementation-roadmap)
11. [Open Questions](#11-open-questions)
---
## 1. Executive Summary
This document evaluates integration strategies for AI Agent payments on the Fiber Network (CKB Lightning Network). We survey four candidate protocols (x402, Stripe ACP, L402, Fiber Native), analyze three application scenarios (M2M micropayments, Agent-to-Agent service trading, Agent proxy shopping), and recommend a **dual-track strategy**:
- **Track 1 (High Priority)**: x402 Facilitator -- integrate Fiber as a payment backend for the x402 ecosystem, gaining immediate access to the emerging HTTP-native payment standard.
- **Track 2 (Medium Priority)**: Fiber Native Agent Protocol -- adopt the L402 protocol skeleton (HTTP 402 + preimage payment proof + token credential) while introducing architectural innovations in token system (Biscuit replacing Macaroon), fair exchange (Hash-Locked Data Exchange), and multi-asset support (CKB + RGB++ stablecoins).
We recommend **against** Stripe ACP integration (centralized, no crypto-native path) and recommend **learning from L402** rather than directly implementing it (L402 is tightly coupled to Lightning/LND).
**Timeline**: 4 weeks, 1 engineer + AI coding agent.
---
## 2. Background & Motivation
### The Agent Economy
AI agents are becoming autonomous economic actors. They need to:
- **Discover** services programmatically (no human signup flows)
- **Pay** for API calls, compute, data (sub-cent micropayments)
- **Authenticate** with cryptographic credentials (not passwords/API keys)
- **Delegate** payment authority to sub-agents (hierarchical agent systems)
- **Settle** fairly (neither party can cheat the other)
### Why Fiber
Fiber Network is a CKB-based payment channel network with unique advantages for agent commerce:
- **Multi-asset**: Native support for CKB + RGB++ assets (UDTs) in payment channels
- **WASM nodes**: Agents can embed a full Fiber node in-browser or in-process
- **Sub-second finality**: Off-chain channel updates are instant
- **Programmable settlement**: CKB's RISC-V VM enables flexible on-chain contracts
- **Cross-chain**: HTLC-based interop with Bitcoin Lightning Network
---
## 3. Protocol Survey
### 3.1 x402 (Coinbase)
**Overview**: Open standard for HTTP-native payments. Uses HTTP 402 status code with a facilitator architecture.
**Flow**:
1. Client requests resource from server
2. Server returns `402 Payment Required` + `PAYMENT-REQUIRED` header (accepted networks, schemes, amounts)
3. Client creates `PaymentPayload` (signed transaction/authorization)
4. Client sends request with `PAYMENT-SIGNATURE` header
5. Server forwards to Facilitator for `/verify` and `/settle`
6. Facilitator submits payment on-chain, returns receipt
7. Server serves resource
**Key Properties**:
- Network/token agnostic (EVM, Solana, fiat -- extensible via `scheme` + `network` pairs)
- Trust-minimizing: Facilitator cannot move funds beyond client's signed authorization
- Multi-language SDKs (TypeScript, Python, Go, Java)
- Schemes: `exact` (fixed price), future `upto` (metered usage)
- Currently blockchain-based (on-chain transactions), no native payment channel support
**Fiber Integration Path**: Build a **Fiber Facilitator** that implements `/verify` and `/settle` endpoints using Fiber payment channels. This would make Fiber a payment backend for any x402-compatible server, with near-zero fees and instant settlement.
**Strengths**: Large ecosystem momentum (Coinbase backing), clean HTTP semantics, multi-network support.
**Weaknesses**: Currently on-chain only (slow, expensive for micropayments), no native credential/delegation system, facilitator is a trust point for settlement.
### 3.2 Stripe Agent Commerce Protocol (ACP)
**Overview**: Stripe's protocol for agent-to-merchant payments. Uses Stripe's existing payment infrastructure with a new "Secure Payment Token" (SPT) for agent delegation.
**Flow**:
1. Human pre-authorizes agent with spending limits via Stripe dashboard
2. Agent receives SPT (scoped Stripe token)
3. Agent browses merchant, selects items
4. Agent creates Stripe PaymentIntent using SPT
5. Stripe processes payment through traditional rails (cards, bank transfers)
6. Merchant fulfills order
**Key Properties**:
- Fully centralized (Stripe as sole payment processor)
- Requires Stripe merchant accounts (existing Stripe ecosystem only)
- SPT provides spending caps and merchant restrictions
- Designed for Agent-as-shopper scenarios (e-commerce)
- No crypto-native path, no micropayment support
**Assessment**: **Not recommended for Fiber integration.** ACP is a closed ecosystem with no path to decentralized payments. Stripe's existing infrastructure handles the use cases ACP targets. There is no meaningful technical overlap with Fiber's capabilities.
### 3.3 L402 (Lightning Labs)
**Overview**: HTTP 402 protocol combining Macaroon bearer tokens with Lightning Network invoice payments. Originally called LSAT (Lightning Service Authentication Token).
**Flow**:
1. Client requests resource from server
2. Server returns `402 Payment Required` + `WWW-Authenticate: L402 macaroon="M", invoice="P"`
3. Client pays Lightning invoice P, obtains preimage `r`
4. Client sends `Authorization: L402 M:r` (base64 macaroon + hex preimage)
5. Server verifies: macaroon integrity (HMAC chain) + payment proof (`H == sha256(r)`)
6. Server serves resource
**Key Properties**:
- **Stateless verification**: Macaroon commits to payment_hash; server verifies `H == sha256(preimage)` with no database lookup
- **Macaroon delegation**: Holders can append caveats to restrict (never widen) credentials, then pass to sub-agents
- **Standard caveats**: `services`, `capabilities`, `constraints` (volume limits, expiry)
- **Credential reuse**: Pay once, authenticate many times until revoked
- **gRPC support**: Same auth scheme adapted for gRPC (status in trailers)
- **Production deployment**: Aperture reverse proxy used in Lightning Loop, Pool
**Macaroon Identifier Structure** (66 bytes):
| Field | Size | Description |
|-------|------|-------------|
| version | 2 bytes | uint16, currently 0 |
| payment_hash | 32 bytes | SHA-256 hash from Lightning invoice |
| token_id | 32 bytes | Random, tracks user across rotations |
**Strengths**: Battle-tested, elegant stateless verification, rich delegation model, minimal trust assumptions.
**Weaknesses**: Tightly coupled to Lightning/LND ecosystem, Macaroons are less flexible than Biscuit tokens (no Datalog logic, no explicit revocation lists), no multi-asset support, no WASM node story.
### 3.4 Fiber Native Agent Protocol
**Overview**: A new protocol purpose-built for Fiber that adopts the L402 protocol skeleton — HTTP 402 challenge-response, preimage-based payment proof, and token:preimage credential format — but introduces substantial architectural innovations in three dimensions: Biscuit tokens (truly stateless verification via public-key cryptography and Datalog policies) replacing Macaroons, a Hash-Locked Data Exchange mechanism for cryptographic fair exchange (absent in L402), and native multi-asset support via CKB + RGB++ stablecoins. A detailed comparison is provided in Section 6.
**Proposed Flow** (see Section 6 for detailed comparison with L402):
1. Client requests resource from server
2. Server returns `402 Payment Required` with Fiber invoice + Biscuit token
3. Client pays via Fiber channel (Keysend or Invoice payment)
4. Client presents Biscuit token + payment proof
5. Server verifies Biscuit (Datalog policy engine) + payment proof
6. Server serves resource
**Differentiators vs L402**:
- **Multi-asset**: Pay in CKB, stablecoins, or any RGB++ asset
- **Biscuit tokens**: Datalog-based authorization (more expressive than Macaroon caveats)
- **WASM embedding**: Agents can run a full Fiber node in-process
- **Hold Invoice + Atomic Data Exchange**: Cryptographic fair exchange (see Section 8)
- **Custom Records**: 2KB arbitrary metadata in payment onion (keys 0-65535)
---
## 4. Fiber Technical Capabilities
### 4.1 Payment Primitives
| Capability | Details |
|-----------|---------|
| **Standard Invoice** | `new_invoice(payment_preimage=Some(preimage))` -- node generates hash from preimage |
| **Hold Invoice** | `new_invoice(payment_hash=Some(hash))` -- externally provided hash, settled later via `settle_invoice(hash, preimage)` |
| **Keysend** | Sender-initiated, no invoice required. Preimage in onion `PaymentHopData.payment_preimage` |
| **MPP** | Multi-path payment with `payment_secret` + `total_amount` in custom records (key 65536) |
| **Custom Records** | `HashMap<u32, Vec<u8>>` in onion payload. Keys 0-65535 for user data, 65536+ reserved. Max ~2KB |
| **Multi-asset** | Native UDT support via `udt_type_script` parameter in invoices and channels |
### 4.2 Authentication: Biscuit Auth
Fiber uses Biscuit tokens for RPC authentication:
- **Ed25519 signed** bearer tokens with Datalog authorization logic
- **Fine-grained permissions**: `read("payments")`, `write("channels")`, `right(channel_id, "watchtower")`
- **Time-based expiry**: `check if time($time), $time <= 2025-01-01T00:00:00Z`
- **Attenuation**: Token holders can create restricted sub-tokens (like Macaroons, but with Datalog)
- **Revocation**: Server-side via public key rotation
**Current RPC permission model** (resource-based):
```
channels: read/write invoices: read/write payments: read/write
peers: read/write graph: read node: read
cch: read/write chain: write watchtower: write + per-channel
```
### 4.3 WASM Node
Full Fiber node compiled to WASM with 22 exposed functions:
- Channel management (open, accept, abandon, list, shutdown, update)
- Graph queries (nodes, channels)
- Invoice lifecycle (new, parse, get, cancel, settle)
- Payment operations (send, get, build_router, send_with_router)
- Peer management (connect, disconnect, list)
**Missing from WASM**: `list_payments`, CCH (cross-chain hub), Biscuit auth middleware.
### 4.4 Hold Invoice Details
**Creation**: `InvoiceBuilder::payment_hash(hash)` -- only hash stored, no preimage on receiver side.
**Settlement**: `settle_invoice(payment_hash, payment_preimage)` -- caller provides preimage to release locked funds.
**Error states**: `InvoiceNotFound`, `HashMismatch`, `InvoiceStillOpen`, `InvoiceAlreadyCancelled`, `InvoiceAlreadyExpired`, `InvoiceAlreadyPaid`.
**Trust model (IMPORTANT)**:
- The entity that generates the preimage controls settlement
- In standard Hold Invoice usage: an external party (e.g., the Consumer) generates the preimage, gives only the hash to the Provider
- Provider creates invoice with that hash, Consumer pays, funds lock in HTLC
- Only the preimage holder can call `settle_invoice` to release funds
- **Hold Invoice alone protects the payer (Consumer)**, NOT the provider -- Consumer can refuse to reveal preimage after receiving service
---
## 5. Application Scenarios
### 5.1 M2M Micropayments (API Pay-per-call)
**Description**: Agent pays for individual API calls (LLM inference, data queries, compute).
| Protocol | Fit | Notes |
|----------|-----|-------|
| x402 Facilitator | **Excellent** | Native HTTP 402 flow, Fiber provides instant settlement |
| L402 | Excellent | Purpose-built for this. Credential reuse amortizes payment overhead |
| Fiber Native | **Excellent** | Same model as L402 but with multi-asset + Biscuit auth |
| Stripe ACP | Poor | Too expensive for micropayments, requires merchant Stripe accounts |
### 5.2 Agent-to-Agent Service Trading
**Description**: Agent A hires Agent B to perform a task (translation, analysis, code generation). Requires fair exchange -- payment conditional on delivery.
| Protocol | Fit | Notes |
|----------|-----|-------|
| x402 Facilitator | Good | Works for simple request/response. No native escrow |
| L402 | Moderate | Credential-based, but no built-in fair exchange mechanism |
| Fiber Native | **Excellent** | Hold Invoice + atomic data exchange (see Section 8) |
| Stripe ACP | Poor | No agent-to-agent path |
### 5.3 Agent Proxy Shopping
**Description**: Agent purchases goods/services on behalf of human (hotel booking, SaaS subscription).
| Protocol | Fit | Notes |
|----------|-----|-------|
| x402 Facilitator | Good | If merchant supports x402 |
| L402 | Moderate | Only Lightning-accepting merchants |
| Fiber Native | Good | If merchant accepts Fiber payments |
| Stripe ACP | Good | Only use case ACP handles well, but requires Stripe ecosystem |
### 5.4 Scenario-Protocol Matrix
```
x402 Facilitator L402 (ref) Fiber Native Stripe ACP
M2M Micropay ★★★★★ ★★★★★ ★★★★★ ★☆☆☆☆
Agent-to-Agent ★★★☆☆ ★★★☆☆ ★★★★★ ★☆☆☆☆
Proxy Shopping ★★★★☆ ★★★☆☆ ★★★★☆ ★★★★☆
Ecosystem Size ★★★★★ ★★★★☆ ★★☆☆☆ ★★★★★
Decentralization ★★★★☆ ★★★★★ ★★★★★ ★☆☆☆☆
```
---
## 6. L402 vs Fiber Native Agent Protocol: Deep Comparison
### 6.0 Relationship Positioning
Fiber Native Agent Protocol is best understood as **L402 re-implemented on Fiber with architectural upgrades**, not a clean-room design or a simple port.
**What is shared (the L402 skeleton)**:
- HTTP 402 challenge-response flow
- Preimage as proof-of-payment (`H == sha256(preimage)`)
- `token:preimage` credential format in the `Authorization` header
- Credential reuse (pay once, authenticate many times)
- Reverse proxy gateway pattern (Aperture → Fiber Gateway)
- Token attenuation for delegation (can only restrict, never widen)
**What is substantively different (Fiber's innovations)**:
| Dimension | L402 | Fiber Native | Why it matters |
|-----------|------|--------------|----------------|
| **Token system** | Macaroon (HMAC chain, requires server-side root key lookup) | Biscuit (Ed25519 + Datalog, verification needs only a public key) | Truly stateless verification; richer policy language |
| **Fair exchange** | None — no mechanism for atomic data-for-payment | Hash-Locked Data Exchange — encryption key = invoice preimage | Enables trustless Agent-to-Agent service trading |
| **Asset support** | Bitcoin only | CKB + any RGB++ asset (stablecoins, NFTs) | Agents can pay in stable value; richer commerce scenarios |
The relationship is analogous to how QUIC adopted TLS 1.3's cryptographic handshake but redesigned the transport layer around UDP — same security model, different architecture where it matters.
### 6.1 Architecture Comparison
| Dimension | L402 | Fiber Native Agent Protocol |
|-----------|------|-----------------------------|
| **Payment Layer** | Lightning Network (Bitcoin only) | Fiber Network (CKB + RGB++ multi-asset) |
| **Auth Token** | Macaroon (HMAC-chain bearer token) | Biscuit (Ed25519 + Datalog policy engine) |
| **HTTP Integration** | `WWW-Authenticate: L402 macaroon="M", invoice="P"` | `WWW-Authenticate: Fiber biscuit="B", invoice="P"` (proposed) |
| **Credential Format** | `Authorization: L402 <macaroon>:<preimage>` | `Authorization: Fiber <biscuit>:<preimage>` (proposed) |
| **Verification** | Stateless: `H == sha256(preimage)` + HMAC chain check | Stateless: `H == sha256(preimage)` + Ed25519 signature + Datalog policy |
| **Proxy/Gateway** | Aperture (reverse proxy) | To be built (Fiber Gateway) |
| **Invoice Format** | BOLT 11 (Bitcoin Lightning) | Fiber Invoice (CKB-native, supports UDT type scripts) |
| **gRPC Support** | Yes (status in trailers) | Not yet (can adopt same pattern) |
### 6.2 Token System: Macaroon vs Biscuit
| Feature | Macaroon (L402) | Biscuit (Fiber) |
|---------|-----------------|-----------------|
| **Crypto Foundation** | HMAC-SHA256 chain | Ed25519 signatures |
| **Authorization Logic** | Key-value caveats with custom satisfiers | Datalog rules and checks (Turing-incomplete but very expressive) |
| **Attenuation** | Append caveats (can only restrict). Requires current signature. | Append blocks (can only restrict). Requires... nothing -- anyone can attenuate. |
| **Verification** | Requires root key (server must store per-macaroon key) | Requires only public key (truly stateless) |
| **Revocation** | Delete root key (deletes all macaroons from that key) | Revocation IDs in token; server maintains revocation list |
| **Third-party Caveats** | Supported (cross-service delegation via encrypted caveats) | Supported via third-party blocks |
| **Standard Caveats** | `services`, `capabilities`, `constraints` | Datalog facts: `read("payments")`, `write("channels")`, `time()` checks |
| **Token Size** | ~100-200 bytes typical | ~200-500 bytes typical (larger due to signatures per block) |
| **Offline Attenuation** | Yes (only need current signature) | Yes (only need the token itself) |
**Key Insight**: Macaroons require the server to store a root key per macaroon and look it up by `sha256(identifier)` to verify. Biscuit verification requires only the server's public key -- it's more truly stateless for the verifier. However, L402 achieves practical statelessness by embedding the payment_hash in the macaroon identifier and using `sha256(preimage)` as the payment proof, so the payment verification itself is stateless even if macaroon verification needs a key lookup.
### 6.3 Payment Proof Mechanism
Both protocols use the same fundamental insight: **preimage as proof of payment**.
```
L402: payment_hash H embedded in macaroon identifier
Client pays invoice → gets preimage r
Verification: H == sha256(r)
Fiber: payment_hash H embedded in biscuit facts (or in invoice reference)
Client pays Fiber invoice → gets preimage r
Verification: H == sha256(r)
```
The mechanism is identical. The difference is the payment rail (Lightning vs Fiber) and the token format (Macaroon vs Biscuit).
### 6.4 Credential Delegation for Agent Hierarchies
**L402 Macaroon Delegation**:
```
Agent A has macaroon M with capabilities [read, write, admin]
Agent A attenuates: append caveat "capabilities=read"
Agent A gives M' to sub-agent B
B can only read (caveat chain enforced by HMAC)
B cannot recover M's signature (HMAC is one-way)
```
**Fiber Biscuit Delegation**:
```
Agent A has biscuit B with facts [read("payments"), write("channels"), time check]
Agent A attenuates: append block with check [read("payments")]
Agent A gives B' to sub-agent B
B can only read payments (Datalog evaluation restricts authority)
B cannot remove blocks (Ed25519 signature covers the chain)
```
**Fiber Advantage**: Biscuit's Datalog engine enables richer delegation policies:
- `check if amount($a), $a <= 10000` (spending limits in token itself)
- `check if resource($r), $r.starts_with("/api/v2/")` (path-scoped access)
- `check if time($t), $t <= 2026-04-15T00:00:00Z` (expiry)
- Combinations of the above in a single check
Macaroons can express similar constraints but require custom satisfier code on the server for each caveat type. Biscuit's Datalog is self-describing -- the verifier evaluates the logic generically.
### 6.5 What Fiber Can Learn from L402
1. **Stateless payment verification via preimage**: Already available in Fiber. The pattern of embedding payment_hash in the auth token and verifying `H == sha256(preimage)` should be adopted directly.
2. **Credential reuse**: L402 credentials are designed for reuse (pay once, authenticate many times). Fiber should adopt this -- a single payment buys a credential that grants N API calls or T seconds of access.
3. **Reverse proxy pattern (Aperture)**: A Fiber Gateway reverse proxy would separate payment/auth logic from business logic, just as Aperture does for Lightning services.
4. **Agent-spec format**: L402's agent-spec.md is a ~560-token document designed for LLM consumption. Fiber should produce a similar compact, token-efficient protocol description for agent integration.
5. **gRPC support**: Many agent frameworks use gRPC. L402's gRPC adaptation (status in trailers) should be adopted.
### 6.6 Where Fiber Goes Beyond L402
1. **Multi-asset payments**: L402 is Bitcoin-only. Fiber supports CKB + any RGB++ asset. An agent can pay in stablecoins, reducing volatility risk.
2. **Richer authorization (Biscuit)**: Datalog policies are more expressive than Macaroon caveats, and Biscuit verification doesn't require per-token server state.
3. **WASM-embedded nodes**: Agents can run a full Fiber node in-process (browser, Node.js, edge function). No need for a separate Lightning node or wallet -- the agent IS the node.
4. **Hold Invoice fair exchange**: Fiber's Hold Invoice + Custom Records enable atomic data-for-payment exchange (see Section 8). L402 has no built-in fair exchange mechanism.
5. **Custom Records metadata**: 2KB of arbitrary data in payment onion enables rich protocol extensions (service descriptors, result hashes, routing hints for sub-agents).
---
## 7. Token Delegation: Macaroon vs Biscuit
### 7.1 Agent Hierarchy Use Case
Consider a hierarchical agent system:
```
Human → Master Agent → Sub-Agent A (data analysis)
→ Sub-Agent B (code generation)
→ Sub-Agent C (web search)
```
The human authorizes the Master Agent with a budget. The Master Agent delegates scoped authority to each sub-agent.
### 7.2 Macaroon Approach (L402-style)
```
# Human creates master macaroon
master_mac = mint(root_key, payment_hash, token_id)
+ caveat "services=analysis:0,codegen:0,search:0"
+ caveat "monthly_volume_sats=1000000"
+ caveat "valid_until=1713225600"
# Master Agent attenuates for Sub-Agent A
sub_a_mac = attenuate(master_mac)
+ caveat "services=analysis:0"
+ caveat "monthly_volume_sats=200000"
# Sub-Agent A cannot:
# - Access codegen or search services
# - Exceed 200K sats/month
# - Use the credential after expiry
# - Remove any caveats (HMAC chain prevents it)
```
**Limitation**: Each attenuation requires the current macaroon's signature. If the Master Agent wants to update Sub-Agent A's budget, it must create a new macaroon (the old one can't be modified in-place).
### 7.3 Biscuit Approach (Fiber-style)
```
# Human creates master biscuit (authority block)
master_biscuit = sign(private_key) {
// Authority block (immutable)
right("analysis", "read");
right("analysis", "write");
right("codegen", "read");
right("codegen", "write");
right("search", "read");
check if time($t), $t <= 2026-04-15T00:00:00Z;
}
# Master Agent attenuates for Sub-Agent A
sub_a_biscuit = attenuate(master_biscuit) {
// Attenuation block (appended, can only restrict)
check if right($service, $action), $service == "analysis";
check if amount($a), $a <= 200000;
}
# Sub-Agent A cannot:
# - Access anything but analysis (Datalog check fails)
# - Exceed 200K budget (check enforced at verification)
# - Remove the attenuation block (signature chain)
```
**Advantage**: Biscuit attenuation doesn't require any secret -- anyone holding a biscuit can attenuate it. The Datalog checks compose naturally. Server verification only needs the public key.
### 7.4 Comparison Summary
| Aspect | Macaroon | Biscuit |
|--------|----------|---------|
| Attenuation secret | Requires current signature | No secret needed |
| Policy language | Ad-hoc key=value + custom code | Datalog (formal, composable) |
| Verification state | Root key per macaroon | Single public key |
| Spending limits | Custom caveat + server-side tracking | Expressible in Datalog checks |
| Multi-service scoping | `services=svc1:tier,svc2:tier` | `check if right($s, $a), ...` |
| Revocation | Delete root key | Revocation ID list |
| Agent ecosystem fit | Good (L402 proven) | Better (richer policies, less server state) |
**Recommendation**: Fiber should use Biscuit tokens for its native agent protocol, adopting L402's payment proof pattern (preimage binding) but replacing Macaroons with Biscuits for authorization.
---
## 8. Fair Exchange Problem & Settlement Strategies
### 8.1 The Problem
In Agent-to-Agent service trading, neither party should be able to cheat:
- **Consumer risk**: Pay but receive nothing (or garbage)
- **Provider risk**: Deliver service but receive no payment
Standard payment (pay-then-deliver or deliver-then-pay) always leaves one party at risk.
### 8.2 Hold Invoice Trust Model (Corrected)
**Critical clarification**: In a Hold Invoice, the **preimage is generated by an external entity** (typically the Consumer or an arbitrator), NOT by the invoice creator (Provider).
```
1. Consumer generates random preimage r, computes H = sha256(r)
2. Consumer gives H to Provider (keeps r secret)
3. Provider creates Hold Invoice with payment_hash = H
4. Consumer pays invoice → funds lock in HTLC across the path
5. Funds are locked but NOT settled -- Provider cannot claim them
6. Only the entity holding r can call settle_invoice(H, r) to release funds
```
**Implication**: Hold Invoice alone protects the **Consumer** (payer). The Consumer can refuse to reveal `r` even after the Provider delivers service. We need additional mechanisms for fair exchange.
### 8.3 Strategy 1: Hash-Locked Data Exchange (Recommended)
The most elegant solution, providing **cryptographic atomicity** between payment and data delivery.
```
Provider (service seller):
1. Perform computation, produce result R
2. Generate encryption key K (random 32 bytes)
3. Encrypt: E = encrypt(R, K)
4. Create Hold Invoice with payment_hash = sha256(K)
(K serves as the preimage!)
5. Send E (encrypted result) + invoice to Consumer
Consumer (service buyer):
1. Receive E + invoice
2. Optionally verify: check encrypted payload size, format, metadata
3. Pay the Hold Invoice → HTLC propagates through network
4. When HTLC settles, K is revealed as the preimage
5. Decrypt: R = decrypt(E, K)
```
**Why this works**:
- Payment settlement atomically reveals the decryption key
- Provider creates the invoice and holds the preimage (K), so Provider controls settlement
- Consumer gets the key only by paying -- no payment, no key
- Provider gets paid only when HTLC settles -- settlement reveals K to Consumer
- **Neither party can cheat**: Provider can't get paid without revealing K; Consumer can't get K without paying
**Fiber implementation**:
- Provider uses `new_invoice(payment_preimage=Some(K))` (standard invoice, not hold)
- Or Provider uses `new_invoice(payment_hash=Some(sha256(K)))` (hold) and calls `settle_invoice` when ready
- Encrypted result E sent via Custom Records (if < 2KB) or out-of-band
**Limitations**: Consumer can't verify result quality before paying. Mitigation: include a hash of R in the metadata so Consumer can verify after decryption and dispute if needed.
### 8.4 Strategy 2: Incremental Payments (Keysend Streaming)
For large services, break delivery into N small chunks:
```
For i = 1 to N:
1. Consumer sends Keysend payment (1/N of total)
2. Provider delivers chunk i
3. If either party defects, max loss is 1/N of total
```
**Fiber implementation**:
- Use Keysend (`send_payment` with no invoice, preimage in onion)
- Custom Records carry chunk metadata (sequence number, total chunks, content hash)
- Suitable for streaming data, incremental computation results
**Trade-off**: More round-trips, higher total overhead, but bounded risk per chunk.
### 8.5 Strategy 3: Third-Party Arbitration (Hold Invoice + Arbitrator)
For high-value transactions where neither party trusts the other:
```
1. Arbitrator generates preimage r, computes H = sha256(r)
2. Provider creates Hold Invoice with payment_hash = H
3. Consumer pays → funds lock
4. Provider delivers service to Consumer
5. Consumer confirms receipt to Arbitrator (or Arbitrator verifies independently)
6. Arbitrator releases r → Provider calls settle_invoice(H, r)
OR: Arbitrator calls settle on Provider's behalf
```
**Trade-off**: Introduces a trusted third party, but the Arbitrator only holds the preimage -- it never holds the funds.
### 8.6 Strategy Comparison
| Strategy | Atomicity | Trust Assumption | Round-trips | Best For |
|----------|-----------|-----------------|-------------|----------|
| Hash-Locked Data Exchange | Cryptographic | None (trustless) | 2 (offer + payment) | Digital goods, API results |
| Incremental Payments | Probabilistic | Bounded risk (1/N) | 2N | Streaming, large jobs |
| Third-Party Arbitration | Conditional | Arbitrator honest | 3+ | High-value, physical goods |
---
## 9. Strategic Recommendation: Dual-Track Approach
### Track 1: x402 Fiber Facilitator (High Priority)
**Goal**: Enable any x402-compatible client/server to use Fiber for instant, cheap payments.
**What to build**:
1. **Fiber Facilitator Server**: HTTP service implementing x402 `/verify` and `/settle` endpoints
2. **Payment scheme**: `exact` on `fiber` network (new scheme-network pair for x402 ecosystem)
3. **Client SDK**: Thin wrapper creating Fiber-compatible `PaymentPayload` from x402 `PaymentRequirements`
**Why high priority**:
- x402 ecosystem is growing rapidly (Coinbase backing, multi-language SDKs)
- Fiber becomes a payment backend without needing to build a whole new agent protocol
- Developers already using x402 get Fiber's speed/cost benefits for free
- Fastest path to production: x402 spec is stable, we only need to implement the Fiber adapter
**Estimated effort**: 1.5 weeks
### Track 2: Fiber Native Agent Protocol (Medium Priority)
**Goal**: Build a differentiated, L402-inspired protocol that leverages Fiber's unique capabilities.
**What to build**:
1. **Protocol spec**: HTTP 402 flow with Biscuit tokens + Fiber invoices (inspired by L402)
2. **Fiber Gateway**: Reverse proxy (like Aperture) that handles auth + payment, forwards to backends
3. **Agent SDK**: Compact library for agents to discover, pay, and authenticate with Fiber services
4. **Agent-spec document**: ~500-token LLM-friendly protocol description
5. **Fair exchange module**: Hash-Locked Data Exchange using Hold Invoice
**Why medium priority**:
- Higher differentiation (multi-asset, Biscuit auth, fair exchange) but needs ecosystem bootstrapping
- More complex to build than the x402 adapter
- Long-term strategic value: Fiber-native protocol can evolve independently
**Estimated effort**: 2.5 weeks
### Not Recommended
- **Stripe ACP**: Centralized, no crypto path, closed ecosystem. Skip entirely.
- **Direct L402 implementation**: L402 is tightly coupled to LND/Lightning. Adapting it to Fiber would require forking Aperture and rewriting the payment layer. Better to learn from L402's design and build natively.
---
## 10. Implementation Roadmap
### Phase 1: x402 Fiber Facilitator (Weeks 1-2)
| Week | Task | Deliverable |
|------|------|-------------|
| 1.1 | Define `fiber` network type + `exact` scheme for x402 | Spec document |
| 1.2 | Implement Facilitator `/verify` endpoint | Validates Fiber payment signatures |
| 1.3 | Implement Facilitator `/settle` endpoint | Executes Fiber payment (Keysend or Invoice) |
| 1.4 | Build x402 client adapter (TypeScript) | NPM package: `@x402/fiber` |
| 2.1 | Integration tests with x402 reference server | End-to-end test suite |
| 2.2 | Documentation + example server | README, example express app |
### Phase 2: Fiber Native Agent Protocol (Weeks 2-4)
| Week | Task | Deliverable |
|------|------|-------------|
| 2.3 | Protocol spec: HTTP 402 + Biscuit + Fiber Invoice | Markdown spec in `docs/specs/` |
| 2.4 | Agent-spec document (~500 tokens, LLM-friendly) | `agent-spec.md` |
| 3.1 | Fiber Gateway (reverse proxy): basic auth + payment flow | Rust binary |
| 3.2 | Fiber Gateway: Biscuit minting, verification, attenuation | Auth middleware |
| 3.3 | Fair exchange module: Hash-Locked Data Exchange | Library + example |
| 3.4 | Agent SDK (Rust + TypeScript): discover, pay, authenticate | Crate + NPM package |
| 4.1 | WASM node integration: agent runs embedded Fiber node | WASM example |
| 4.2 | End-to-end demo: Agent-to-Agent service trading | Demo application |
| 4.3 | Performance benchmarks + documentation | Benchmark results, docs |
### Resource Estimate
- **Engineer**: 1 senior Rust developer
- **AI Coding Agent**: Assists with boilerplate, tests, documentation, SDK generation
- **Total calendar time**: 4 weeks
- **Risk**: WASM node integration (week 4.1) may surface missing APIs (`list_payments` needed for payment tracking)
---
## 11. Open Questions
1. **x402 scheme registration**: How does a new `(exact, fiber)` scheme-network pair get accepted into x402? Need to engage with x402-foundation/x402 community.
2. **Biscuit payment binding**: Should we embed payment_hash directly in Biscuit facts (like L402 embeds it in Macaroon identifier), or reference it indirectly via an invoice ID?
3. **Credential pricing models**: L402 supports pay-once-use-many. Should Fiber also support per-request payments (cheaper per call but no credential reuse)?
4. **Cross-chain agent payments**: If an agent holds BTC Lightning credentials (L402) but wants to pay a Fiber service, can CCH (Cross-Chain Hub) bridge this automatically?
5. **WASM Biscuit**: The current WASM node doesn't expose Biscuit auth. Should the WASM node include Biscuit token creation/verification for embedded agent use?
6. **Multi-asset credential pricing**: How should an x402 `PaymentRequirements` express "pay 0.5 USDT on Fiber OR 100 CKB on Fiber"? Need to define asset-specific fields.
7. **Rate limiting without state**: L402 achieves rate limiting via `monthly_volume_sats` caveats checked server-side. Biscuit can express this in Datalog but still needs server-side counters. Is there a fully stateless rate limiting approach?
---
## Appendix A: Protocol Header Formats
### x402
```
# Server → Client (402 response)
PAYMENT-REQUIRED: <base64(PaymentRequired)>
# Client → Server (payment)
PAYMENT-SIGNATURE: <base64(PaymentPayload)>
# Server → Client (receipt)
PAYMENT-RESPONSE: <base64(SettlementResponse)>
```
### L402
```
# Server → Client (402 response)
WWW-Authenticate: L402 macaroon="<base64>", invoice="<bolt11>"
# Client → Server (auth)
Authorization: L402 <base64(macaroon)>:<hex(preimage)>
```
### Fiber Native (Proposed)
```
# Server → Client (402 response)
WWW-Authenticate: Fiber biscuit="<base64>", invoice="<fiber-invoice>"
# Client → Server (auth)
Authorization: Fiber <base64(biscuit)>:<hex(preimage)>
```
## Appendix B: References
- [x402 Protocol](https://github.com/x402-foundation/x402) -- Coinbase/x402 Foundation
- [L402 Protocol](https://github.com/lightninglabs/L402) -- Lightning Labs
- [L402 Protocol Specification](https://github.com/lightninglabs/L402/blob/master/protocol-specification.md)
- [L402 Macaroon Spec](https://github.com/lightninglabs/L402/blob/master/macaroon-spec.md)
- [L402 Agent Spec](https://github.com/lightninglabs/L402/blob/master/agent-spec.md)
- [Aperture (L402 Reverse Proxy)](https://github.com/lightninglabs/aperture)
- [Biscuit Authorization](https://www.biscuitsec.org/)
- [Fiber Light Paper](../light-paper.md)
- [Fiber Biscuit Auth](../biscuit-auth.md)
- [Macaroons: Cookies with Contextual Caveats (Google Research)](https://research.google/pubs/pub41892/)