Documentation
¶
Index ¶
- Constants
- func DisableLog()
- func UseLogger(logger btclog.Logger)
- type Authenticator
- type ChallengePrices
- type ChargeStore
- type CreditOutcome
- type InvoiceChecker
- type L402Authenticator
- type Level
- type MPPAuthenticator
- func (a *MPPAuthenticator) Accept(header *http.Header, serviceName string) bool
- func (a *MPPAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
- func (a *MPPAuthenticator) ReceiptHeader(header *http.Header, serviceName string) http.Header
- func (a *MPPAuthenticator) Scheme() string
- func (a *MPPAuthenticator) SetReusableChargePolicy(policy func(serviceName string) bool)
- func (a *MPPAuthenticator) Start()
- func (a *MPPAuthenticator) Stop()
- type MPPSessionAuthenticator
- func (a *MPPSessionAuthenticator) Accept(header *http.Header, serviceName string) bool
- func (a *MPPSessionAuthenticator) BearerSessionID(ctx context.Context, header *http.Header) (string, int64, bool)
- func (a *MPPSessionAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
- func (a *MPPSessionAuthenticator) FreshChallengeHeaderWithPrices(serviceName string, prices ChallengePrices) (http.Header, error)
- func (a *MPPSessionAuthenticator) ReceiptHeader(header *http.Header, serviceName string) http.Header
- func (a *MPPSessionAuthenticator) Scheme() string
- func (a *MPPSessionAuthenticator) SettleSessionRequest(ctx context.Context, sessionID string, chargedSats, actualSats int64) error
- type MPPSessionConfig
- type Minter
- type MockAuthenticator
- type MultiAuthenticator
- func (m *MultiAuthenticator) Accept(header *http.Header, serviceName string) bool
- func (m *MultiAuthenticator) AcceptForScheme(header *http.Header, serviceName string, scheme string) bool
- func (m *MultiAuthenticator) BearerSessionID(ctx context.Context, header *http.Header) (string, int64, bool)
- func (m *MultiAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
- func (m *MultiAuthenticator) FreshChallengeHeaderWithPrices(serviceName string, prices ChallengePrices) (http.Header, error)
- func (m *MultiAuthenticator) ReceiptHeader(header *http.Header, serviceName string) http.Header
- func (m *MultiAuthenticator) SettleSessionRequest(ctx context.Context, sessionID string, chargedSats, actualSats int64) error
- type PaymentSender
- type PricedChallenger
- type ReceiptProvider
- type SchemeTagged
- type Session
- type SessionSettler
- type SessionStore
- type TransactionRecorder
Constants ¶
const ( // AuthSchemeL402 is the L402 (macaroon + preimage) authentication // scheme identifier. AuthSchemeL402 = "l402" // AuthSchemeMPP is the Payment HTTP Authentication Scheme identifier. AuthSchemeMPP = "mpp" // AuthSchemeL402MPP enables both L402 and MPP simultaneously. AuthSchemeL402MPP = "l402+mpp" )
const ( // DefaultInvoiceLookupTimeout is the default maximum time we wait for // an invoice update to arrive. DefaultInvoiceLookupTimeout = 3 * time.Second )
const Subsystem = "AUTH"
Variables ¶
This section is empty.
Functions ¶
func DisableLog ¶
func DisableLog()
DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.
Types ¶
type Authenticator ¶
type Authenticator interface {
// Accept returns whether or not the header successfully authenticates
// the user to a given backend service.
Accept(*http.Header, string) bool
// FreshChallengeHeader returns a header containing a challenge for the
// user to complete.
FreshChallengeHeader(string, int64) (http.Header, error)
}
Authenticator is the generic interface for validating client headers and returning new challenge headers.
type ChallengePrices ¶ added in v0.6.0
type ChallengePrices struct {
// Charge is the price in satoshis of a single one-shot purchase. It is
// what the L402 and MPP charge challenges quote, and it is the value
// the plain FreshChallengeHeader receives.
Charge int64
// SessionUnit is the estimated price in satoshis of one request served
// against a prepaid session. Zero means no session-aware price was
// available, and the session challenge falls back to Charge.
SessionUnit int64
// SessionDeposit is the deposit in satoshis to ask for when opening a
// session. Zero leaves the deposit to the authenticator's configured
// deposit multiplier.
SessionDeposit int64
}
ChallengePrices carries the prices a fresh 402 challenge should quote. A single number no longer suffices, because the intents a challenge can carry ask genuinely different questions of the pricer: L402 and the MPP charge intent quote a whole one-shot purchase, which for a metered service is a token bundle, while the MPP session intent quotes the cost of one request drawn against a prepaid balance. Quoting a bundle price as a session's per-unit amount would make every bearer request cost as much as a bundle.
type ChargeStore ¶ added in v0.6.0
type ChargeStore interface {
// ConsumeCharge claims the given payment hash for the request being
// authorized, and reports whether this call is the one that claimed it.
// A hash that some earlier request already claimed returns false, and
// the credential naming it must be refused.
//
// The claim must be atomic. Concurrent presentations of one credential
// must see exactly one true between them, which rules out asking
// whether a hash is spent and then marking it spent: both callers would
// read it as unspent and both would be served.
//
// The expiry is the one the challenge carried. It is recorded rather
// than consulted, because a challenge past its expiry is refused before
// the store is reached; what it is for is telling a later prune which
// records can no longer matter.
ConsumeCharge(ctx context.Context, paymentHash lntypes.Hash,
challengeID string, expiresAt time.Time) (bool, error)
// PruneConsumedCharges removes every record whose challenge expired
// before the given instant, and returns how many it removed. Without it
// the table grows for as long as the proxy serves traffic, which on a
// public proxy is a slow denial of service rather than a tidiness
// problem.
PruneConsumedCharges(ctx context.Context,
expiredBefore time.Time) (int64, error)
}
ChargeStore remembers which Lightning payments have already bought a request under the MPP charge intent. The charge credential is otherwise entirely a statement about the past: the preimage hashes to the payment hash forever, the challenge HMAC is stateless by design and says nothing about whether its challenge has been redeemed, and a settled invoice stays settled. Nothing in the credential distinguishes its first presentation from its thousandth, so this store is the only thing that can.
type CreditOutcome ¶ added in v0.6.0
type CreditOutcome uint8
CreditOutcome says what a credit attempt did to a session's deposit. A settled Lightning invoice stays settled forever, so a preimage proves only that the payment happened at some point, never that it has not already been spent. The store is the only thing that knows the difference, and this is how it reports it.
const ( // CreditApplied means the payment hash had never funded anything, so // the deposit grew by the full amount. CreditApplied CreditOutcome = iota // CreditReplayed means the payment hash had already funded this very // session, so nothing was added. This is what an honest client looks // like when its top-up response was lost and it resent the request: // the balance it is asking for is already there, and the right answer // is to let it proceed rather than charge it a second time. CreditReplayed // CreditForeign means the payment hash had already funded a different // session. Nothing was added, and no honest client does this: it is a // credential paid for one session being pointed at another. CreditForeign )
func (CreditOutcome) String ¶ added in v0.6.0
func (c CreditOutcome) String() string
String returns a human readable name for the outcome.
type InvoiceChecker ¶
type InvoiceChecker interface {
// VerifyInvoiceStatus checks that an invoice identified by a payment
// hash has the desired status. To make sure we don't fail while the
// invoice update is still on its way, we try several times until either
// the desired status is set or the given timeout is reached.
VerifyInvoiceStatus(lntypes.Hash, lnrpc.Invoice_InvoiceState,
time.Duration) error
}
InvoiceChecker is an entity that is able to check the status of an invoice, particularly whether it's been paid or not.
type L402Authenticator ¶
type L402Authenticator struct {
// contains filtered or unexported fields
}
L402Authenticator is an authenticator that uses the L402 protocol to authenticate requests.
func NewL402Authenticator ¶
func NewL402Authenticator(minter Minter, checker InvoiceChecker) *L402Authenticator
NewL402Authenticator creates a new authenticator that authenticates requests based on L402 tokens.
func (*L402Authenticator) Accept ¶
func (l *L402Authenticator) Accept(header *http.Header, serviceName string) bool
Accept returns whether or not the header successfully authenticates the user to a given backend service.
NOTE: This is part of the Authenticator interface.
func (*L402Authenticator) FreshChallengeHeader ¶
func (l *L402Authenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
FreshChallengeHeader returns a header containing a challenge for the user to complete.
NOTE: This is part of the Authenticator interface.
func (*L402Authenticator) Scheme ¶ added in v0.5.0
func (l *L402Authenticator) Scheme() string
Scheme returns the authentication scheme identifier for the L402 authenticator.
NOTE: This implements the SchemeTagged interface.
type Level ¶
type Level string
const ( // LevelOff is the default level where no authentication is required. LevelOff Level = "off" )
func ParseLevel ¶ added in v0.6.0
ParseLevel validates and normalizes an authentication level.
func (Level) FreebieCount ¶
type MPPAuthenticator ¶ added in v0.5.0
type MPPAuthenticator struct {
// contains filtered or unexported fields
}
MPPAuthenticator is an authenticator that implements the Payment HTTP Authentication Scheme for the Lightning "charge" intent. It issues BOLT11 invoices as challenges and verifies payment preimages as credentials.
func NewMPPAuthenticator ¶ added in v0.5.0
func NewMPPAuthenticator(challenger mint.Challenger, checker InvoiceChecker, realm string, hmacSecret []byte, network string, txnRecorder TransactionRecorder, chargeStore ChargeStore) (*MPPAuthenticator, error)
NewMPPAuthenticator creates a new authenticator for the Payment HTTP Authentication Scheme with the "charge" intent.
The charge store is required. Everything else the authenticator checks is a property of the payment rather than of the request carrying it, so without somewhere to record that a payment has been spent there is no way to tell a first presentation from a replay, and one payment would buy unlimited service. Refusing to build is the only honest answer for a deployment that cannot offer one.
func (*MPPAuthenticator) Accept ¶ added in v0.5.0
func (a *MPPAuthenticator) Accept(header *http.Header, serviceName string) bool
Accept returns whether the header contains a valid Payment credential for the Lightning charge intent.
NOTE: This is part of the Authenticator interface.
func (*MPPAuthenticator) FreshChallengeHeader ¶ added in v0.5.0
func (a *MPPAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
FreshChallengeHeader returns a WWW-Authenticate: Payment header containing a charge challenge with a fresh BOLT11 invoice.
NOTE: This is part of the Authenticator interface.
func (*MPPAuthenticator) ReceiptHeader ¶ added in v0.5.0
ReceiptHeader returns a Payment-Receipt header for a successfully authenticated charge request.
NOTE: This is part of the ReceiptProvider interface.
func (*MPPAuthenticator) Scheme ¶ added in v0.5.0
func (a *MPPAuthenticator) Scheme() string
Scheme returns the authentication scheme identifier for the MPP charge authenticator.
NOTE: This implements the SchemeTagged interface.
func (*MPPAuthenticator) SetReusableChargePolicy ¶ added in v0.6.0
func (a *MPPAuthenticator) SetReusableChargePolicy( policy func(serviceName string) bool)
Start launches the background sweep that keeps the consumption record table from growing without bound. It is safe to call more than once. SetReusableChargePolicy installs the predicate that decides which services treat charge credentials as re-presentable rather than single use. It is meant to be called once, between construction and Start, with a predicate naming the metered services: on those, the payment buys a bundle whose draw-down is the spend, so the credential must stay presentable until the pricer refuses it. Passing nil restores the strict single-use rule everywhere.
func (*MPPAuthenticator) Start ¶ added in v0.6.0
func (a *MPPAuthenticator) Start()
func (*MPPAuthenticator) Stop ¶ added in v0.6.0
func (a *MPPAuthenticator) Stop()
Stop halts the background sweep and waits for it to finish. It is safe to call more than once, and safe to call on an authenticator that was never started.
type MPPSessionAuthenticator ¶ added in v0.5.0
type MPPSessionAuthenticator struct {
// contains filtered or unexported fields
}
MPPSessionAuthenticator is an authenticator that implements the Payment HTTP Authentication Scheme for the Lightning "session" intent. It manages prepaid sessions with deposit, bearer, top-up, and close operations.
func NewMPPSessionAuthenticator ¶ added in v0.5.0
func NewMPPSessionAuthenticator( cfg *MPPSessionConfig) *MPPSessionAuthenticator
NewMPPSessionAuthenticator creates a new session intent authenticator.
func (*MPPSessionAuthenticator) Accept ¶ added in v0.5.0
func (a *MPPSessionAuthenticator) Accept(header *http.Header, serviceName string) bool
Accept returns whether the header contains a valid Payment credential for the Lightning session intent.
NOTE: This is part of the Authenticator interface.
func (*MPPSessionAuthenticator) BearerSessionID ¶ added in v0.6.0
func (a *MPPSessionAuthenticator) BearerSessionID(ctx context.Context, header *http.Header) (string, int64, bool)
BearerSessionID returns the session a bearer credential in the header draws against, along with the per-unit amount its challenge quoted, which is what handleBearer has already deducted from the balance.
The credential is verified here rather than assumed good, even though Accept has already run. A request can carry credentials for several schemes at once and only one of them needs to have been the one that authenticated it, so a caller holding a valid L402 token could otherwise attach an unverified session credential naming somebody else's session and have this request's cost settled against that stranger's balance. Re-running the checks costs one HMAC and one session read, which is cheap next to being able to spend another buyer's deposit.
NOTE: This is part of the SessionSettler interface.
func (*MPPSessionAuthenticator) FreshChallengeHeader ¶ added in v0.5.0
func (a *MPPSessionAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
FreshChallengeHeader returns a WWW-Authenticate: Payment header containing a session challenge with a fresh deposit invoice.
NOTE: This is part of the Authenticator interface.
func (*MPPSessionAuthenticator) FreshChallengeHeaderWithPrices ¶ added in v0.6.0
func (a *MPPSessionAuthenticator) FreshChallengeHeaderWithPrices( serviceName string, prices ChallengePrices) (http.Header, error)
FreshChallengeHeaderWithPrices returns a WWW-Authenticate: Payment header containing a session challenge priced with the session-aware quote when one is available.
The unit price a session advertises is the estimated cost of one request, not the price of a one-shot purchase. On a metered service those differ by orders of magnitude, since a one-shot purchase buys a whole token bundle, so quoting the charge price here would make every bearer request cost a bundle and empty the deposit on its first call.
NOTE: This is part of the PricedChallenger interface.
func (*MPPSessionAuthenticator) ReceiptHeader ¶ added in v0.5.0
func (a *MPPSessionAuthenticator) ReceiptHeader(header *http.Header, serviceName string) http.Header
ReceiptHeader returns a Payment-Receipt header for a successfully authenticated session request.
NOTE: This is part of the ReceiptProvider interface.
func (*MPPSessionAuthenticator) Scheme ¶ added in v0.5.0
func (a *MPPSessionAuthenticator) Scheme() string
Scheme returns the authentication scheme identifier for the MPP session authenticator.
NOTE: This implements the SchemeTagged interface.
func (*MPPSessionAuthenticator) SettleSessionRequest ¶ added in v0.6.0
func (a *MPPSessionAuthenticator) SettleSessionRequest(ctx context.Context, sessionID string, chargedSats, actualSats int64) error
SettleSessionRequest reconciles a request that was charged chargedSats at bearer time against the actualSats its completed response turned out to cost.
This is the second half of post-hoc reconciliation, which is the accounting model sessions use deliberately. The alternative, reserving a worst case at request time and releasing the remainder, never overspends but makes the buyer's displayed balance lurch downward for the length of every request. Reconciling instead leaves the balance transiently optimistic between the start of a request and the end of its response, and the most that optimism can cost the seller is the difference on a single in-flight request.
NOTE: This is part of the SessionSettler interface.
type MPPSessionConfig ¶ added in v0.5.0
type MPPSessionConfig struct {
Challenger mint.Challenger
Checker InvoiceChecker
SessionStore SessionStore
PaymentSender PaymentSender
Realm string
HMACSecret []byte
Network string
DepositMultiplier int
IdleTimeout time.Duration
}
MPPSessionConfig holds the configuration for the session authenticator.
type Minter ¶
type Minter interface {
// MintL402 mints a new L402 for the target services.
MintL402(context.Context, ...l402.Service) (*macaroon.Macaroon, string, error)
// VerifyL402 attempts to verify an L402 with the given parameters.
VerifyL402(context.Context, *mint.VerificationParams) error
}
Minter is an entity that is able to mint and verify L402s for a set of services.
type MockAuthenticator ¶
type MockAuthenticator struct{}
MockAuthenticator is a mock implementation of the authenticator.
func NewMockAuthenticator ¶
func NewMockAuthenticator() *MockAuthenticator
NewMockAuthenticator returns a new MockAuthenticator instance.
func (MockAuthenticator) Accept ¶
func (a MockAuthenticator) Accept(header *http.Header, _ string) bool
Accept returns whether or not the header successfully authenticates the user to a given backend service.
func (MockAuthenticator) FreshChallengeHeader ¶
FreshChallengeHeader returns a header containing a challenge for the user to complete.
type MultiAuthenticator ¶ added in v0.5.0
type MultiAuthenticator struct {
// contains filtered or unexported fields
}
MultiAuthenticator wraps multiple Authenticator implementations and tries each in order. It supports both the Authenticator and ReceiptProvider interfaces, delegating receipt generation to whichever sub-authenticator handles the credential type.
func NewMultiAuthenticator ¶ added in v0.5.0
func NewMultiAuthenticator(auths ...Authenticator) *MultiAuthenticator
NewMultiAuthenticator creates a new MultiAuthenticator that tries each authenticator in order.
func (*MultiAuthenticator) Accept ¶ added in v0.5.0
func (m *MultiAuthenticator) Accept(header *http.Header, serviceName string) bool
Accept returns whether any of the wrapped authenticators accept the request. The first authenticator that returns true wins. This delegates to AcceptForScheme with an empty scheme, which tries all authenticators.
NOTE: This is part of the Authenticator interface.
func (*MultiAuthenticator) AcceptForScheme ¶ added in v0.5.0
func (m *MultiAuthenticator) AcceptForScheme(header *http.Header, serviceName string, scheme string) bool
AcceptForScheme returns whether any of the wrapped authenticators that match the given auth scheme accept the request. An empty scheme tries all authenticators (backwards compatible). The scheme string can be "l402", "mpp", or "l402+mpp".
func (*MultiAuthenticator) BearerSessionID ¶ added in v0.6.0
func (m *MultiAuthenticator) BearerSessionID(ctx context.Context, header *http.Header) (string, int64, bool)
BearerSessionID asks each wrapped authenticator that holds session balances whether the header is a bearer credential it recognizes, and returns the first answer.
NOTE: This is part of the SessionSettler interface.
func (*MultiAuthenticator) FreshChallengeHeader ¶ added in v0.5.0
func (m *MultiAuthenticator) FreshChallengeHeader(serviceName string, servicePrice int64) (http.Header, error)
FreshChallengeHeader returns merged challenge headers from all wrapped authenticators. This allows a 402 response to include challenges for multiple authentication schemes (e.g., both L402 and Payment), letting the client choose which scheme to use.
NOTE: This is part of the Authenticator interface.
func (*MultiAuthenticator) FreshChallengeHeaderWithPrices ¶ added in v0.6.0
func (m *MultiAuthenticator) FreshChallengeHeaderWithPrices(serviceName string, prices ChallengePrices) (http.Header, error)
FreshChallengeHeaderWithPrices returns merged challenge headers from all wrapped authenticators, giving each the price for the question it actually asks. An authenticator that only knows the one-shot charge price receives it through the plain FreshChallengeHeader, exactly as before.
NOTE: This is part of the PricedChallenger interface.
func (*MultiAuthenticator) ReceiptHeader ¶ added in v0.5.0
ReceiptHeader tries each sub-authenticator that implements ReceiptProvider and returns the first non-nil receipt. This avoids the race condition of storing a per-request index on the shared struct; instead, each provider inspects the credential and only produces a receipt if it handles that credential type.
NOTE: This is part of the ReceiptProvider interface.
func (*MultiAuthenticator) SettleSessionRequest ¶ added in v0.6.0
func (m *MultiAuthenticator) SettleSessionRequest(ctx context.Context, sessionID string, chargedSats, actualSats int64) error
SettleSessionRequest hands the reconciliation to every wrapped authenticator that holds session balances. A settler that does not know the session reports an error, which is why the first success wins rather than the first attempt.
NOTE: This is part of the SessionSettler interface.
type PaymentSender ¶ added in v0.5.0
type PaymentSender interface {
// SendPayment sends a payment to the given invoice with the specified
// amount in satoshis. Returns the payment preimage hex on success.
SendPayment(ctx context.Context, invoice string,
amtSats int64) (string, error)
}
PaymentSender is an interface for sending Lightning payments. This is used by the session authenticator to refund unspent balance when a session is closed.
type PricedChallenger ¶ added in v0.6.0
type PricedChallenger interface {
// FreshChallengeHeaderWithPrices returns a challenge header quoting the
// given set of prices.
FreshChallengeHeaderWithPrices(serviceName string,
prices ChallengePrices) (http.Header, error)
}
PricedChallenger is an optional interface an Authenticator implements when the challenge it mints depends on more than one price. Authenticators that do not implement it are driven through FreshChallengeHeader with the charge price, which is what they have always received.
type ReceiptProvider ¶ added in v0.5.0
type ReceiptProvider interface {
// ReceiptHeader returns any response headers that should be added to
// the proxied response for a successfully authenticated request. The
// request headers and service name are provided for context. Returns
// nil if no receipt headers are needed.
ReceiptHeader(*http.Header, string) http.Header
}
ReceiptProvider is an optional interface that authenticators can implement to provide response headers (e.g., Payment-Receipt) for successfully authenticated requests. This is used by the MPP authenticator to add Payment-Receipt headers to proxied responses.
type SchemeTagged ¶ added in v0.5.0
type SchemeTagged interface {
// Scheme returns the authentication scheme identifier (e.g., "l402"
// or "mpp") that this authenticator handles.
Scheme() string
}
SchemeTagged is an optional interface that authenticators can implement to declare which authentication scheme they handle. This is used by MultiAuthenticator to filter sub-authenticators based on the per-service auth scheme setting.
type Session ¶ added in v0.5.0
type Session struct {
// SessionID is the payment hash of the deposit invoice, encoded as a
// lowercase hex string. Serves as the unique session identifier.
SessionID string
// PaymentHash is the raw 32-byte payment hash of the deposit invoice.
PaymentHash lntypes.Hash
// DepositSats is the total satoshis deposited into the session.
// Increases with each successful top-up.
DepositSats int64
// SpentSats is the running total of satoshis charged against the
// session.
SpentSats int64
// ReturnInvoice is the BOLT11 return invoice for refunds on close.
ReturnInvoice string
// Status is either "open" or "closed".
Status string
// CreatedAt is the time the session was created.
CreatedAt time.Time
// UpdatedAt is the time the session was last updated.
UpdatedAt time.Time
}
Session represents an MPP prepaid session. The session is identified by the payment hash of the deposit invoice.
type SessionSettler ¶ added in v0.6.0
type SessionSettler interface {
// BearerSessionID returns the session a bearer credential in the header
// draws against, along with the amount that credential's challenge
// quoted and that the authenticator has already deducted. It reports
// false for a header that is not a bearer credential the implementation
// itself would accept.
//
// The implementation must re-verify the credential rather than trust
// that authentication already passed. A request can carry credentials
// for several schemes at once, and only one of them needs to have been
// the one that authenticated it.
BearerSessionID(ctx context.Context, header *http.Header) (
sessionID string, chargedSats int64, ok bool)
// SettleSessionRequest reconciles a request that was charged
// chargedSats against the actualSats it turned out to cost.
SettleSessionRequest(ctx context.Context, sessionID string,
chargedSats, actualSats int64) error
}
SessionSettler is an optional interface an Authenticator implements when it holds prepaid session balances that are drawn down per request.
It exists because the two halves of metered session pricing sit on opposite sides of the authenticator's boundary. An Authenticator only ever sees request headers, so it cannot ask a pricer what the request in hand should cost, and it never sees a response at all, so it cannot learn what the request did cost. The proxy sees both, but the balance lives behind the authenticator's session store. This interface is the narrow seam between them: the proxy costs a completed request and hands the reconciliation back to whoever owns the balance.
type SessionStore ¶ added in v0.5.0
type SessionStore interface {
// CreateSession creates a new session with the given initial state,
// claiming the deposit payment hash for it in the same atomic step.
// The session is refused if that hash has already funded a session,
// which is what stops one deposit payment from opening a session and
// then being presented again as a top-up somewhere else.
CreateSession(ctx context.Context, session *Session) error
// GetSession returns the session with the given session ID.
GetSession(ctx context.Context, sessionID string) (*Session, error)
// CreditSession adds the given amount to the session's deposit if and
// only if the given payment hash has never been credited before, and
// reports which of those two happened. The claim on the payment hash
// and the balance increment are one atomic step, so concurrent replays
// of the same credential credit exactly once between them.
//
// This is deliberately the only way to grow a balance. A separate "has
// this hash been seen" query would leave the once-only property resting
// on every caller remembering to ask.
CreditSession(ctx context.Context, sessionID string,
paymentHash lntypes.Hash, addSats int64) (CreditOutcome, error)
// DeductSessionBalance atomically adds the given amount to the
// session's spent counter. Returns an error if the deduction would
// exceed the deposit balance.
DeductSessionBalance(ctx context.Context, sessionID string,
amount int64) error
// CloseSession marks the session as closed. No further operations are
// accepted on a closed session.
CloseSession(ctx context.Context, sessionID string) error
// SettleSessionBalance atomically adjusts the session's spent counter
// by a signed amount, clamped so the spend can neither go below zero
// nor above the deposit, and returns the resulting spend. It is how a
// request charged an estimate before its response existed is
// reconciled against what it turned out to cost.
SettleSessionBalance(ctx context.Context, sessionID string,
deltaSats int64) (int64, error)
// CloseSessionAndGetBalance atomically closes the session and returns
// the remaining balance (deposit_sats - spent_sats). This prevents
// the TOCTOU race where a concurrent bearer request could deduct
// balance between a separate read and close.
CloseSessionAndGetBalance(ctx context.Context,
sessionID string) (int64, error)
}
SessionStore persists MPP session state for the session intent. Sessions track prepaid balances that are decremented as services are consumed.
type TransactionRecorder ¶ added in v0.5.0
type TransactionRecorder interface {
// RecordMPPTransaction records a pending MPP charge or session
// payment. The authType distinguishes between "mpp_charge" and
// "mpp_session".
RecordMPPTransaction(ctx context.Context, paymentHash []byte,
serviceName string, priceSats int64,
authType string) error
}
TransactionRecorder records payment transactions for admin dashboard tracking. Both L402 and MPP payments use this to populate the transactions table.