Documentation
¶
Overview ¶
Package termsroute is a host's terms route: one small HTTP handler beside an overlay host, whose base URL is what the host publishes for its lookup service (BRC-180 metanet.overlays). It is the Go twin of the TypeScript package's host entry point (ts/src/host: LookupFront, its budgets, its sessions, the payee ledger and payment acceptance), for an overlay host written in Go. It serves
GET <base>/<service>/terms the host terms document (404 when the host prices nothing) POST <base>/.well-known/auth the BRC-104 handshake POST <base>/lookup BRC-24 questions to the service, free and priced
A free question is answered with or without BRC-104 authentication. A question of a class the host prices must be asked over BRC-104; without a payment it is answered 402 with BRC-105's headers (the version, the price, the derivation prefix; the payee is the server's identity key in the authentication headers), and with one that pays the price to the key BRC-29 derives for that prefix, suffix and asker, and that verifies against the host's headers, it is held to acceptance (Gate): the host broadcasts it, and answers at once when it is small and the network took it, or 202 ERR_PAYMENT_HELD until it mines (the same payment, sent again once mined, buys the answer). One payment buys one question.
Every authenticated request is answered with a signed response, so a session is given a budget of them (KeyedBudget), and a request sent twice is refused (SeenRequests); handshakes are held to a budget (HandshakeBudget) before any signature work, and the sessions they buy are bounded (Sessions). Status codes, bodies, metric names (under the application's prefix) and ledger lines are the TypeScript route's, so a client sees one route whichever language the host is written in.
Index ¶
- Constants
- Variables
- func AddressKey(address string) string
- func Caller(ctx context.Context) (string, bool)
- func LedgerLine(p *Received, at int64, layout Layout) ([]byte, error)
- func ParseDuration(name, raw string) (time.Duration, error)
- func ParsePrices(raw string, classes []PricedClass, variable string) (map[string]uint64, error)
- func SpentOutpoints(tx *transaction.Transaction) []string
- func TermsPath(service string) string
- func WithCaller(ctx context.Context, identity string) context.Context
- type AcceptConfig
- type Answerer
- type BudgetConfig
- type Claim
- type FastLine
- type Front
- func (f *Front) Identity() string
- func (f *Front) Listen(ctx context.Context, addr string) error
- func (f *Front) RestoreFast(lines []FastLine)
- func (f *Front) Serve(ctx context.Context, l net.Listener) error
- func (f *Front) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (f *Front) Tick(ctx context.Context)
- type Gate
- func (g *Gate) Accept(ctx context.Context, tx *transaction.Transaction, payer string, script []byte, ...) GateVerdict
- func (g *Gate) Count(decision, reason string)
- func (g *Gate) Forget(txid string)
- func (g *Gate) Networked() bool
- func (g *Gate) Restore(tx *transaction.Transaction, payer string, sats uint64, at time.Time)
- func (g *Gate) Sweep(ctx context.Context)
- func (g *Gate) Watching() []string
- type GateOptions
- type GateVerdict
- type HandshakeBudget
- type KeyedBudget
- type Layout
- type Ledger
- type MemoryReceiver
- type NodeView
- type Options
- type PricedClass
- type Question
- type ReadLine
- type Received
- type Receiver
- type ResponseBudgetConfig
- type SeenRequests
- type SessionBound
- type Sessions
- func (s *Sessions) AddSession(session *auth.PeerSession) error
- func (s *Sessions) GetSession(identifier string) (*auth.PeerSession, error)
- func (s *Sessions) HasSession(identifier string) bool
- func (s *Sessions) RemoveSession(session *auth.PeerSession)
- func (s *Sessions) Size() int
- func (s *Sessions) UpdateSession(session *auth.PeerSession)
- type Terms
- type TermsClass
- type Verdict
Constants ¶
const ( MaxBody = 64 << 10 MaxHeaders = 256 << 10 // AuthTimeout bounds a Peer's work on one message. AuthTimeout = 30 * time.Second )
MaxBody bounds a request body: a question and its authentication are small, and a payment rides in a header. MaxHeaders bounds the headers.
The claims.
const ( DefaultMaxSessions = 10_000 DefaultSessionTTL = 600 )
DefaultMaxSessions is the default bound on BRC-104 sessions the terms route keeps, and DefaultSessionTTL their idle life in seconds.
const LedgerFile = payee.LedgerFile
LedgerFile is the ledger's name in a host's state directory.
const MaxAddresses = 10_000
MaxAddresses is the most addresses with a bucket; past it the least recently seen is forgotten.
const MaxSafe = 1<<53 - 1
MaxSafe is 2^53 - 1: the largest price, as the TypeScript route bounds it.
const MaxSeenRequests = 65536
MaxSeenRequests is the most request identifiers remembered, to refuse one sent twice.
const PaymentVersion = "1.0"
PaymentVersion is BRC-105's payment version.
const UnsettleableFile = "unsettleable.jsonl"
UnsettleableFile records each fast payment the watch found lost.
Variables ¶
var DefaultBudget = BudgetConfig{PerSec: 4, Burst: 8, PerAddressPerSec: 1, AddressBurst: 4}
DefaultBudget is a fraction of the roughly 10 handshakes a second a test host's process signs, so its own work keeps most of the process. An honest client shakes hands once per session.
var DefaultResponseBudget = ResponseBudgetConfig{PerSec: 5, Burst: 20}
DefaultResponseBudget is far above what a reader walking pages needs and far below what a process signs.
var EventKinds = []string{"confirmed", "double-spent", "refused", "unmined"}
EventKinds are what became of a fast payment, as the route counts them.
var HandshakeResults = []string{"accepted", "failed", "limited_address", "limited_global"}
HandshakeResults are <app>_handshakes_total's results.
var PaymentLabels = [][2]string{
{"requested", "no-payment"},
{"fast", "at-or-below-threshold"},
{"fast", "mined"},
{"hold", "above-threshold"},
{"hold", "payer-limit"},
{"hold", "total-limit"},
{"hold", "payer-flagged"},
{"hold", "no-broadcast-leg"},
{"hold", "broadcast-unconfirmed"},
{"hold", "no-network-verdict"},
{"hold", "double-spend-attempted"},
{"hold", "spend-view-unknown"},
{"hold", "already-charged"},
{"hold", "payer-asked-hold"},
{"hold", "price-unknown"},
{"hold", "price-stale"},
{"hold", "no-txid"},
{"hold", "watch-limit"},
{"refuse", "pays-nothing"},
{"refuse", "malformed"},
{"refuse", "wrong-script"},
{"refuse", "spv-failed"},
{"refuse", "not-final"},
{"refuse", "outputs-exceed-inputs"},
{"refuse", "network-refused"},
{"refuse", "double-spent"},
{"refuse", "replayed"},
{"refuse", "conflict"},
}
PaymentLabels are the decision and reason pairs the route counts payments under, preset so a dashboard sees zeros.
var RequestResults = []string{"replayed", "limited"}
RequestResults are <app>_requests_total's results: authenticated requests refused before any signature.
Functions ¶
func AddressKey ¶
AddressKey is the key an address is budgeted under: IPv4 as is, an IPv4-mapped address as its IPv4 address, IPv6 by its /64.
func Caller ¶
Caller is the identity key the request being answered was verified under, when the route verified one.
func LedgerLine ¶
LedgerLine is p as a ledger line, newline included; at is Unix seconds.
func ParseDuration ¶
ParseDuration parses <n>ms, <n>s, <n>m or <n>h; name is the setting, for the error.
func ParsePrices ¶
ParsePrices parses a host's prices, `history=5,history-after=5`: a comma list of <class>=<satoshis>, each a priceable class of classes once, priced 0 to 2^53 - 1. A free class is refused: it never has a price. A class and its -after form, where classes defines one, are priced together or not at all. variable names the setting in errors, for example APP_PRICES. An empty raw is no price.
func SpentOutpoints ¶
func SpentOutpoints(tx *transaction.Transaction) []string
SpentOutpoints is every outpoint a transaction spends, "<txid>.<index>".
Types ¶
type AcceptConfig ¶
type AcceptConfig struct {
ArcadeURL string
AssetURL string
// Chain is WhatsOnChain's network ("main" or "test") as the node view,
// for a host with no node (<P>_CHAIN=woc:main or woc:test); WocKey its
// API key (<P>_WOC_KEY), if any.
Chain string
WocKey string
Policy acceptance.Policy
}
AcceptConfig is the acceptance settings a host reads from its environment.
func ParseAcceptConfig ¶
func ParseAcceptConfig(prefix string, getenv func(string) string) (AcceptConfig, error)
ParseAcceptConfig reads <P>_ARCADE_URL, <P>_ASSET_URL (or <P>_CHAIN, woc:main or woc:test, with <P>_WOC_KEY, for a host with no node) and <P>_ACCEPT_THRESHOLD_SATS, _ACCEPT_PAYER_LIMIT, _ACCEPT_TOTAL_LIMIT, _ACCEPT_WINDOW and _ACCEPT_WATCH through getenv, as the TypeScript package's parseAcceptConfig reads them. Defaults are bcommon's DefaultPolicy and no watch.
type Answerer ¶
type Answerer interface {
Restored() bool
Classify(ctx context.Context, q Question) (string, error)
Answer(ctx context.Context, q Question) (any, error)
}
Answerer is the lookup service behind the route. Classify names a question's class or errs (answered 400 with the error's text, before any price: a question about a crypt the asker is not served costs nothing); Answer is the JSON a 200 carries (an error is answered 400 with its text). Both get the asker's identity in ctx (Caller) when the request was authenticated. Restored is false until the service can answer (503).
type BudgetConfig ¶
type BudgetConfig struct {
// PerSec is the handshakes a second the route answers, Burst the most
// it answers at once.
PerSec float64
Burst int
// The same for each remote address.
PerAddressPerSec float64
AddressBurst int
}
BudgetConfig is the handshake budget: token buckets, one for the route and one for each remote address, checked before any signature work.
type FastLine ¶
FastLine is a fast payment read from the ledger at start: watched again until it mines.
type Front ¶
type Front struct {
// Sessions are the BRC-104 sessions the route keeps.
Sessions *Sessions
// Budget is what handshakes the route answers; Responses what signed
// responses each session is given; Seen the authenticated requests
// answered lately.
Budget *HandshakeBudget
Responses *KeyedBudget
Seen *SeenRequests
// Gate is payment acceptance, when the host prices anything.
Gate *Gate
// contains filtered or unexported fields
}
Front is the terms route. It is an http.Handler.
func (*Front) Identity ¶
Identity is the route's BRC-104 identity key, compressed hex; empty without a payee.
func (*Front) RestoreFast ¶
RestoreFast watches again the fast payments a ledger read at start, charged as they were.
type Gate ¶
type Gate struct {
// contains filtered or unexported fields
}
Gate is the fast path, the hold, and the watch over what the fast path took: bcommon's acceptance rule, counted and recorded as the TypeScript route counts and records it.
func GateFor ¶
func GateFor(app string, host bmodule.Host, headers chaintracker.ChainTracker, c AcceptConfig, stateDir string) *Gate
GateFor is the gate for a host's configuration.
func NewGate ¶
func NewGate(o GateOptions) *Gate
NewGate makes a gate. Every payment is held when Arcade is nil, or both Asset and Node are.
func (*Gate) Accept ¶
func (g *Gate) Accept(ctx context.Context, tx *transaction.Transaction, payer string, script []byte, sats uint64) GateVerdict
Accept decides tx, which pays sats to output 0 locked by script and passed the route's own checks, for payer.
func (*Gate) Forget ¶
Forget releases and stops watching a payment the route did not take after all.
func (*Gate) Restore ¶
func (g *Gate) Restore(tx *transaction.Transaction, payer string, sats uint64, at time.Time)
Restore watches a fast payment taken before a restart, charged as it was.
type GateOptions ¶
type GateOptions struct {
// App is the metric prefix.
App string
Host bmodule.Host
// Headers are the host's block headers, which a payment verifies against.
Headers chaintracker.ChainTracker
Policy acceptance.Policy
// Arcade is the broadcaster the host collects through; Asset the node's
// asset service (spend view, proofs). Without both no payment is fast.
Arcade *publish.Arcade
Asset *nodeapi.Asset
// Node, when Asset is nil, is another spend view and proof source in
// its place, such as WhatsOnChain (nodeapi.WoC) for a host with no
// node.
Node NodeView
// MaxAge is how long a fast payment may stay unmined before it is
// reported; a day when zero. MaxWatched is the most fast payments
// watched at once, 100000 when zero; past it a payment is held.
MaxAge time.Duration
MaxWatched int
// StateDir is where unsettleable.jsonl is written; none when empty.
StateDir string
Now func() time.Time
}
GateOptions builds a Gate.
type GateVerdict ¶
GateVerdict is a decision on one payment: "fast", "hold" or "refuse", the reason, and the reason in words.
type HandshakeBudget ¶
type HandshakeBudget struct {
// contains filtered or unexported fields
}
HandshakeBudget answers handshakes from the route's bucket and each address's, the address's checked first, so one address that floods spends its own budget and not the route's.
func NewHandshakeBudget ¶
func NewHandshakeBudget(c BudgetConfig, now func() time.Time) (*HandshakeBudget, error)
NewHandshakeBudget makes a budget; every rate and burst must be positive.
func (*HandshakeBudget) Addresses ¶
func (h *HandshakeBudget) Addresses() int
Addresses is how many addresses have a bucket.
func (*HandshakeBudget) Take ¶
func (h *HandshakeBudget) Take(address string) Verdict
Take takes one handshake for address from both buckets, or says which refused and how long to wait.
type KeyedBudget ¶
type KeyedBudget struct {
// contains filtered or unexported fields
}
KeyedBudget is token buckets by key, at most max of them; past it the least recently used is forgotten.
func NewKeyedBudget ¶
func NewKeyedBudget(c ResponseBudgetConfig, max int, now func() time.Time) (*KeyedBudget, error)
NewKeyedBudget makes a budget of at most max keys.
func (*KeyedBudget) Take ¶
func (k *KeyedBudget) Take(key string) Verdict
Take takes one from key's bucket, or says how long until one is there.
type Layout ¶
type Layout string
Layout is where a ledger line puts the host's decision: LayoutPayee after at (the Go payee package's order), LayoutSpread before it (the order the applications' own routes wrote). A line with no decision is the same in both, and is byte for byte what payee.Payment.Line writes.
type Ledger ¶
type Ledger struct {
Path string
// Fast are the fast lines read at start, newest last.
Fast []FastLine
// contains filtered or unexported fields
}
Ledger is payments as a file, payments.jsonl in a directory, one line each, flushed to disk before the question is answered: what the operator's wallet internalizes. The txids already in the file are claimed, and so are the coins they spend; a line written before lines carried their inputs is read from its transaction.
func OpenLedger ¶
OpenLedger opens or creates dir/payments.jsonl and reads what it holds. A last line cut short is ended with a newline.
type MemoryReceiver ¶
type MemoryReceiver struct {
Payments []*Received
// contains filtered or unexported fields
}
MemoryReceiver keeps payments in memory, for tests.
func (*MemoryReceiver) Claim ¶
func (m *MemoryReceiver) Claim(p *Received) Claim
Claim implements Receiver.
type NodeView ¶ added in v0.30.0
type NodeView interface {
acceptance.SpendView
acceptance.ProofSource
}
NodeView is a node's view a gate reads: who spent an output, and a mined transaction's proof. *nodeapi.Asset and *nodeapi.WoC are both one.
type Options ¶
type Options struct {
// App is the application's name: the prefix of the route's metrics and
// log lines. Service is the lookup service's name.
App string
Service string
// Classes are the classes a question can be, in the terms document's
// order.
Classes []PricedClass
// PaymentProtocol is BRC-29's derivation protocol, under which a priced
// question's payment pays the host.
PaymentProtocol wallet.Protocol
LS Answerer
Host bmodule.Host
// Prices by priceable class; empty when the host prices nothing.
Prices map[string]uint64
// Payee is the payee's key, whose identity key is the server's: needed
// for BRC-104 and priced classes.
Payee *ec.PrivateKey
// Receiver is where accepted payments go.
Receiver Receiver
// Headers are the host's block headers, which a payment verifies against.
Headers chaintracker.ChainTracker
// Sessions bounds BRC-104 sessions; the defaults when zero.
Sessions SessionBound
// Gate is payment acceptance; without one, and with a price and
// headers, every payment is held for confirmation.
Gate *Gate
// Budget is the handshake budget, DefaultBudget when zero; Responses
// the budget of signed responses for each session,
// DefaultResponseBudget when zero.
Budget BudgetConfig
Responses ResponseBudgetConfig
// ResponseBudgetBeforeVerify takes a session's budget by every request
// that names the session, before verification, so forged requests on
// one session cost its budget and not the host's CPU; false (the
// default) takes it only by a request whose signature verified.
ResponseBudgetBeforeVerify bool
Now func() time.Time
}
Options builds a Front.
type PricedClass ¶
PricedClass is a class of question, as a price list names it.
type Question ¶
type Question struct {
Service string `json:"service"`
Query json.RawMessage `json:"query"`
}
Question is a question as the route reads it: a JSON object, its members unchecked.
type ReadLine ¶
type ReadLine struct {
Txid string
Inputs []string
Decision string
Beef string
SenderIdentityKey string
Satoshis uint64
At int64
}
ReadLine is a ledger line as a host reads it at start: the keys the host itself reads, unchecked beyond their types. Inputs are the line's own, or else those read from its transaction; empty when neither can be read.
func ParseLedgerLine ¶
ParseLedgerLine reads one line, or (nil, false) for one that is no payment (cut short by a crash, whose question was never answered).
type Received ¶
type Received struct {
Txid string
// Beef is the payment as Atomic BEEF.
Beef []byte
OutputIndex uint32
Satoshis uint64
// DerivationPrefix and DerivationSuffix are the BRC-29 remittance,
// base64, and SenderIdentityKey the payer, compressed hex.
DerivationPrefix string
DerivationSuffix string
SenderIdentityKey string
Class string
// Inputs are every outpoint the payment spends, "<txid>.<index>", the
// txid in display order.
Inputs []string
// Decision is what the host did: "fast" and "mined" are answered,
// "hold" is not; empty is the payee's own line. Reason is why.
Decision string
Reason string
}
Received is a payment the route accepted: what a wallet's internalizeAction needs to take it, and what the host decided.
type Receiver ¶
type Receiver interface {
// Refusal is why p cannot be taken, before it is broadcast; Accepted
// when it can.
Refusal(txid string, inputs []string) Claim
Claim(p *Received) Claim
}
Receiver is where accepted payments go. Claim records p and answers Accepted, atomically, unless its txid was claimed before (Replayed) or it spends a coin an accepted payment spent (Conflict): one payment buys one question, and one coin pays once.
type ResponseBudgetConfig ¶
ResponseBudgetConfig is the budget of signed responses for each authenticated session: PerSec a second, Burst at once.
type SeenRequests ¶
type SeenRequests struct {
// contains filtered or unexported fields
}
SeenRequests is the requests a route answered lately, by a key of the asker and the request's own identifier: a request sent again byte for byte is refused without a signature. Bounded, oldest forgotten first; the response budget bounds what a replay older than this memory can cost.
func NewSeenRequests ¶
func NewSeenRequests(max int) *SeenRequests
NewSeenRequests remembers at most max requests.
func (*SeenRequests) Has ¶
func (s *SeenRequests) Has(key string) bool
Has reports whether key was answered lately.
type SessionBound ¶
SessionBound is the bound on BRC-104 sessions: the most kept, and how long one idle is kept.
type Sessions ¶
type Sessions struct {
// contains filtered or unexported fields
}
Sessions is the BRC-104 sessions the terms route keeps, bounded. The SDK's own store keeps every session for the life of the process, and a handshake is unauthenticated, so anyone could grow it without end. This one holds at most max sessions and forgets one idle for ttl (idle: not added, updated or looked up); past the cap it forgets the least recently used. A client whose session was forgotten is refused (401) and shakes hands again. It is the SessionManager contract the SDK's Peer uses.
func NewSessions ¶
func NewSessions(max int, ttl time.Duration, now func() time.Time, evicted func(why string)) (*Sessions, error)
NewSessions makes a bounded store. evicted, when set, is told why each forgotten session went: "cap" or "idle".
func (*Sessions) AddSession ¶
func (s *Sessions) AddSession(session *auth.PeerSession) error
AddSession implements auth.SessionManager.
func (*Sessions) GetSession ¶
func (s *Sessions) GetSession(identifier string) (*auth.PeerSession, error)
GetSession implements auth.SessionManager: by session nonce, or else the most recently updated session of an identity key.
func (*Sessions) HasSession ¶
HasSession implements auth.SessionManager.
func (*Sessions) RemoveSession ¶
func (s *Sessions) RemoveSession(session *auth.PeerSession)
RemoveSession implements auth.SessionManager.
func (*Sessions) UpdateSession ¶
func (s *Sessions) UpdateSession(session *auth.PeerSession)
UpdateSession implements auth.SessionManager.
type Terms ¶
type Terms struct {
Service string `json:"service"`
Terms int `json:"terms"`
Classes []TermsClass `json:"classes"`
}
Terms is the host terms document.
func TermsDocument ¶
func TermsDocument(service string, classes []PricedClass, prices map[string]uint64) Terms
TermsDocument is the host terms document: the priced classes in the order of classes.
type TermsClass ¶
TermsClass is one line of the terms document.