Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions internal/website/content/en/docs/guides/x402-payments.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ type Facilitator interface {
}
```

A facilitator may also implement `Challenger` to add per-challenge data (such as a fresh order id) to the `402` body; `Verify` and `Settle` still receive the operator's requirements.

### Self-hosted Nano facilitator

`wrapper/x402/nano` verifies `nano:mainnet` payments with scheme `exact` against a Nano node RPC you run or choose. It is off unless you configure it, uses only the standard library, and holds no key or seed:

```go
claims, err := nano.OpenFileClaimStore("/var/lib/myservice/nano-claims")
fac, err := nano.NewFacilitator("https://node.example/rpc", "nano_1...", claims)
price, err := nano.RawFromXNO("0.001") // 1 XNO = 10^30 raw

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documented 0.001 XNO price becomes 1000000000000000000000000000 raw units (10^27). The existing x402.Client.Do parses MaxAmountRequired with strconv.ParseInt(..., 64), so it rejects this challenge before invoking Payer, even with Budget == 0. I reproduced this against the middleware using the PR's gateway fixture. Please cover the real client-to-middleware path and resolve or explicitly scope this incompatibility; the current tests submit payment headers directly and miss it.


pay := x402.Middleware(x402.Config{
PayTo: "nano_1...",
Network: "nano",
Amount: price.String(),
Facilitator: fac,
})
```

Each `402` carries a fresh order id and a `representative` account in `extra` that commits to (order id, payTo, amount). The payer sends exactly that amount to `payTo` with that representative, then sends `{"scheme":"exact","network":"nano:mainnet","payload":{"orderId":"...","block":"<hash>"}}` (base64) as `X-PAYMENT`. The block must be confirmed, pay the exact amount and carry the commitment; it is then claimed in the claims file before the request is served, so a block pays for one order once, including after a restart. Run one process per claims file (the file is locked).

## At the MCP gateway

Because every endpoint is already an MCP tool, the gateway is where you charge. Payments are wired into both `micro mcp serve` and the `micro gateway` command, gated on `/mcp/call` (listing tools and health stay free), and **off unless you set a pay-to address**.
Expand Down
115 changes: 115 additions & 0 deletions wrapper/x402/nano/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package nano

import (
"errors"
"strings"
)

const accountAlphabet = "13456789abcdefghijkmnopqrstuwxyz"

// ErrInvalidAccount is returned for an account that is malformed or whose
// checksum does not match its public key.
var ErrInvalidAccount = errors.New("nano: invalid nano account")

// EncodeAccount encodes a 32-byte public key as a nano_ account with its
// BLAKE2b-40 checksum.
func EncodeAccount(pub []byte) (string, error) {
if len(pub) != 32 {
return "", ErrInvalidAccount
}
// 4 zero pad bits + 256 key bits = 260 bits = 52 characters.
var b strings.Builder
b.WriteString("nano_")
b.WriteString(encode5(append([]byte{0, 0, 0}, pub...), 52))
sum := blake2bSum(pub, 5)
rev := []byte{sum[4], sum[3], sum[2], sum[1], sum[0]}
b.WriteString(encode5(rev, 8))
return b.String(), nil
}

// DecodeAccount checks the prefix, alphabet and checksum of a nano_ (or
// legacy xrb_) account and returns its public key.
func DecodeAccount(account string) ([]byte, error) {
var body string
switch {
case strings.HasPrefix(account, "nano_"):
body = account[5:]
case strings.HasPrefix(account, "xrb_"):
body = account[4:]
default:
return nil, ErrInvalidAccount
}
if len(body) != 60 || (body[0] != '1' && body[0] != '3') {
return nil, ErrInvalidAccount
}
keyBits, ok := decode5(body[:52], 35)
if !ok {
return nil, ErrInvalidAccount
}
// The first 3 bytes hold the 4 pad bits plus nothing else.
if keyBits[0] != 0 || keyBits[1] != 0 || keyBits[2] != 0 {
return nil, ErrInvalidAccount
}
pub := keyBits[3:]
chk, ok := decode5(body[52:], 5)
if !ok {
return nil, ErrInvalidAccount
}
sum := blake2bSum(pub, 5)
for i := 0; i < 5; i++ {
if chk[i] != sum[4-i] {
return nil, ErrInvalidAccount
}
}
return append([]byte(nil), pub...), nil
}

// ValidateAccount reports whether account is a well-formed nano_ account
// with a correct checksum.
func ValidateAccount(account string) error {
_, err := DecodeAccount(account)
return err
}

// encode5 writes the low chars*5 bits of the big-endian number in b.
func encode5(b []byte, chars int) string {
out := make([]byte, chars)
for i := chars - 1; i >= 0; i-- {
bitPos := (chars - 1 - i) * 5
var v byte
for j := 0; j < 5; j++ {
p := bitPos + j
byteIdx := len(b) - 1 - p/8
if byteIdx >= 0 && b[byteIdx]&(1<<(uint(p)%8)) != 0 {
v |= 1 << uint(j)
}
}
out[i] = accountAlphabet[v]
}
return string(out)
}

// decode5 reads base32 characters into a big-endian number of size bytes.
// Bits that do not fit in size bytes must be zero.
func decode5(s string, size int) ([]byte, bool) {
out := make([]byte, size)
for i := 0; i < len(s); i++ {
v := strings.IndexByte(accountAlphabet, s[i])
if v < 0 {
return nil, false
}
bitPos := (len(s) - 1 - i) * 5
for j := 0; j < 5; j++ {
if v&(1<<uint(j)) == 0 {
continue
}
p := bitPos + j
byteIdx := size - 1 - p/8
if byteIdx < 0 {
return nil, false
}
out[byteIdx] |= 1 << (uint(p) % 8)
}
}
return out, true
}
63 changes: 63 additions & 0 deletions wrapper/x402/nano/amount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package nano

import (
"errors"
"math/big"
"strings"
)

// RawDecimals is the number of decimal places between one XNO and one raw:
// 1 XNO = 10^30 raw.
const RawDecimals = 30

// ErrInvalidAmount is returned for an amount that is not a positive decimal
// with at most RawDecimals fractional digits.
var ErrInvalidAmount = errors.New("nano: invalid XNO amount")

// RawFromXNO converts a decimal XNO string such as "0.001" to raw using
// integer arithmetic only. Floats, signs, exponents and more than 30
// fractional digits are refused.
func RawFromXNO(xno string) (*big.Int, error) {
s := strings.TrimSpace(xno)
if s == "" {
return nil, ErrInvalidAmount
}
whole, frac, hasDot := strings.Cut(s, ".")
if whole == "" {
whole = "0"
}
if hasDot && frac == "" {
return nil, ErrInvalidAmount
}
if len(frac) > RawDecimals || !allDigits(whole) || !allDigits(frac) {
return nil, ErrInvalidAmount
}
digits := whole + frac + strings.Repeat("0", RawDecimals-len(frac))
raw, ok := new(big.Int).SetString(digits, 10)
if !ok || raw.Sign() <= 0 {
return nil, ErrInvalidAmount
}
return raw, nil
}

// ParseRaw parses a raw amount as a node returns it (a base-10 integer
// string). It refuses anything that is not a non-negative integer.
func ParseRaw(raw string) (*big.Int, error) {
if raw == "" || !allDigits(raw) {
return nil, ErrInvalidAmount
}
v, ok := new(big.Int).SetString(raw, 10)
if !ok {
return nil, ErrInvalidAmount
}
return v, nil
}

func allDigits(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return false
}
}
return true
}
62 changes: 62 additions & 0 deletions wrapper/x402/nano/binding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package nano

import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"regexp"
)

// Network and Scheme are the identifiers this package offers in a 402.
const (
Network = "nano:mainnet"
Scheme = "exact"
Asset = "XNO"
)

var orderIDPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)

// ErrInvalidOrderID is returned for an order id that is not 32 lowercase hex
// characters (128 random bits).
var ErrInvalidOrderID = errors.New("nano: invalid order id")

// NewOrderID returns a random 128-bit order id as lowercase hex. The order id
// is the payer's claim secret: it is never published on the ledger, only its
// hash (inside the representative commitment) is.
func NewOrderID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return hex.EncodeToString(b[:]), nil
}

// ValidOrderID reports whether id has the shape NewOrderID produces.
func ValidOrderID(id string) bool { return orderIDPattern.MatchString(id) }

// Commitment binds one order to one destination and one price:
// SHA-256("xno-binding/v1/rep|" + orderID + "|" + payTo + "|" + priceRaw).
func Commitment(orderID, payTo, priceRaw string) [32]byte {
return sha256.Sum256([]byte("xno-binding/v1/rep|" + orderID + "|" + payTo + "|" + priceRaw))
}

// CommitmentAccount is the Commitment encoded as a nano_ account. The payer
// sets it as the representative of the send block, so the signed block
// itself names the order it pays for.
func CommitmentAccount(orderID, payTo, priceRaw string) string {
c := Commitment(orderID, payTo, priceRaw)
acct, _ := EncodeAccount(c[:]) // 32 bytes, cannot fail
return acct
}

// Offer is the nano:mainnet entry a 402 challenge carries.
type Offer struct {
Scheme string `json:"scheme"`
Network string `json:"network"`
Asset string `json:"asset"`
PayTo string `json:"payTo"`
Amount string `json:"amount"`
OrderID string `json:"orderId"`
Representative string `json:"representative"`
}
93 changes: 93 additions & 0 deletions wrapper/x402/nano/blake2b.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package nano

import (
"encoding/binary"
"math/bits"
)

// blake2bSum is an unkeyed BLAKE2b (RFC 7693) with a digest of size bytes
// (1..64). Nano uses BLAKE2b-40 for the account checksum. It lives here so
// this package needs nothing outside the Go standard library.
func blake2bSum(data []byte, size int) []byte {
if size < 1 || size > 64 {
panic("nano: blake2b digest size out of range")
}
var h [8]uint64

Check failure on line 15 in wrapper/x402/nano/blake2b.go

View workflow job for this annotation

GitHub Actions / golangci-lint

S1021: should merge variable declaration with assignment on next line (staticcheck)
h = blake2bIV
h[0] ^= 0x01010000 ^ uint64(size)

var t uint64
for len(data) > 128 {
t += 128
blake2bCompress(&h, data[:128], t, false)
data = data[128:]
}
var last [128]byte
copy(last[:], data)
t += uint64(len(data))
blake2bCompress(&h, last[:], t, true)

var out [64]byte
for i := 0; i < 8; i++ {
binary.LittleEndian.PutUint64(out[i*8:], h[i])
}
return append([]byte(nil), out[:size]...)
}

var blake2bIV = [8]uint64{
0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
}

var blake2bSigma = [12][16]byte{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
}

func blake2bCompress(h *[8]uint64, block []byte, t uint64, final bool) {
var m [16]uint64
for i := range m {
m[i] = binary.LittleEndian.Uint64(block[i*8:])
}
var v [16]uint64
copy(v[:8], h[:])
copy(v[8:], blake2bIV[:])
v[12] ^= t
if final {
v[14] = ^v[14]
}
g := func(a, b, c, d int, x, y uint64) {
v[a] = v[a] + v[b] + x
v[d] = bits.RotateLeft64(v[d]^v[a], -32)
v[c] = v[c] + v[d]
v[b] = bits.RotateLeft64(v[b]^v[c], -24)
v[a] = v[a] + v[b] + y
v[d] = bits.RotateLeft64(v[d]^v[a], -16)
v[c] = v[c] + v[d]
v[b] = bits.RotateLeft64(v[b]^v[c], -63)
}
for r := 0; r < 12; r++ {
s := &blake2bSigma[r]
g(0, 4, 8, 12, m[s[0]], m[s[1]])
g(1, 5, 9, 13, m[s[2]], m[s[3]])
g(2, 6, 10, 14, m[s[4]], m[s[5]])
g(3, 7, 11, 15, m[s[6]], m[s[7]])
g(0, 5, 10, 15, m[s[8]], m[s[9]])
g(1, 6, 11, 12, m[s[10]], m[s[11]])
g(2, 7, 8, 13, m[s[12]], m[s[13]])
g(3, 4, 9, 14, m[s[14]], m[s[15]])
}
for i := 0; i < 8; i++ {
h[i] ^= v[i] ^ v[i+8]
}
}
Loading
Loading