From 2e13569e9ca7d7841a5ee6074706bfd4e2086f4e Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Wed, 2 Dec 2026 22:27:41 -0800 Subject: [PATCH 1/8] Size payment tickets per job by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split fixed-price quotes across the fewest tickets that fit the signer’s limits. For metered jobs, target three seconds of quoted usage per ticket and keep billing based on elapsed time and carried credit. Size the winning payout from recent redemption fees and payer funding, then derive the odds from ticket EV. Ensure the payer’s reserve can cover every ticket winning in the fixed-price or metered opening batch. --- .../testdata/cli/orchestrator-help.golden | 6 +- configs/orchestrator/config.example.toml | 14 +- docs/http-api.md | 6 + docs/metrics.md | 1 + docs/orchestrator.md | 24 ++- docs/payment-recovery.md | 7 + eth/payment.go | 24 ++- orchestrator/app.go | 69 +++++-- orchestrator/app_test.go | 3 + orchestrator/metrics.go | 2 +- orchestrator/metrics_test.go | 3 +- orchestrator/payment.go | 20 +- orchestrator/payment_engine.go | 41 +++- orchestrator/redemption.go | 5 +- orchestrator/ticket_sizing.go | 138 +++++++++++++ orchestrator/ticket_sizing_test.go | 79 +++++++ pm/payerpolicy.go | 2 +- pm/remotepayment.go | 7 +- redeemer/app.go | 1 + redemption/fees.go | 192 ++++++++++++++++++ redemption/fees_test.go | 146 +++++++++++++ redemption/http.go | 16 +- redemption/migrations/006_fee_samples.sql | 8 + redemption/redeemer.go | 26 ++- redemption/redeemer_db.go | 25 +++ redemption/redeemer_db_test.go | 38 ++-- redemption/redemption_store.go | 15 ++ redemption/state.go | 18 +- redemption/worker.go | 11 + signer/payment.go | 4 +- signer/payment_test.go | 132 ++++++++++++ 31 files changed, 1014 insertions(+), 69 deletions(-) create mode 100644 orchestrator/ticket_sizing.go create mode 100644 orchestrator/ticket_sizing_test.go create mode 100644 redemption/fees.go create mode 100644 redemption/fees_test.go create mode 100644 redemption/migrations/006_fee_samples.sql diff --git a/cmd/livepeer/testdata/cli/orchestrator-help.golden b/cmd/livepeer/testdata/cli/orchestrator-help.golden index f9b72bf..59bcff0 100644 --- a/cmd/livepeer/testdata/cli/orchestrator-help.golden +++ b/cmd/livepeer/testdata/cli/orchestrator-help.golden @@ -44,7 +44,11 @@ Flags: --controller-address string (env: LIVEPEER_ORCHESTRATOR_CONTROLLER_ADDRESS) -w, --wei-per-usd string (env: LIVEPEER_ORCHESTRATOR_WEI_PER_USD) -t, --ticket-face-value string (env: LIVEPEER_ORCHESTRATOR_TICKET_FACE_VALUE) - --ticket-win-prob string (env: LIVEPEER_ORCHESTRATOR_TICKET_WIN_PROB) + --ticket-win-prob string Legacy setting accepted for compatibility (env: LIVEPEER_ORCHESTRATOR_TICKET_WIN_PROB) + --max-ticket-ev string Maximum quoted EV per ticket in wei; defaults to the stock signer limit (env: LIVEPEER_ORCHESTRATOR_MAX_TICKET_EV) + --max-batch-ev string Maximum quoted EV per payment batch in wei; defaults to the stock signer limit (env: LIVEPEER_ORCHESTRATOR_MAX_BATCH_EV) + --metered-ticket-seconds int Seconds of quoted usage per metered ticket; defaults to 3 (env: LIVEPEER_ORCHESTRATOR_METERED_TICKET_SECONDS) + --payer-deposit-multiplier int Signer deposit multiplier; defaults to 1 (env: LIVEPEER_ORCHESTRATOR_PAYER_DEPOSIT_MULTIPLIER) --runner-grants strings Private runner IP[:port] or CIDR grants (env: LIVEPEER_ORCHESTRATOR_RUNNER_GRANTS) --session-proxy-grants strings Private session proxy IP[:port] or CIDR grants (env: LIVEPEER_ORCHESTRATOR_SESSION_PROXY_GRANTS) --health-grants strings Private static runner health IP[:port] or CIDR grants (env: LIVEPEER_ORCHESTRATOR_HEALTH_GRANTS) diff --git a/configs/orchestrator/config.example.toml b/configs/orchestrator/config.example.toml index d9e1fea..4ef932f 100644 --- a/configs/orchestrator/config.example.toml +++ b/configs/orchestrator/config.example.toml @@ -21,8 +21,8 @@ HealthGrants = [] # To retain other cookies, omit "Cookie" from ExcludedHeaders. # ExcludedCookies = ["CF_Authorization"] # Remove only the named cookies from app requests. -# Paid operation requires an on-chain network, account password, RPC, face -# value, winning probability, and one conversion source. +# Paid operation requires an on-chain network, account password, RPC, baseline +# ticket face value, and one conversion source. # Runner prices are USD per hour or per fixed request. Choose WeiPerUSD # for a fixed conversion OR ETHUSDFeed for an ETH/USD feed on the payment # chain. The fee ceiling and PriceMaxAge are optional. See docs/orchestrator.md. @@ -43,10 +43,12 @@ HealthGrants = [] # WeiPerUSD = "1000000000000000" # ETHUSDFeed = "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612" # Arbitrum default. # PriceMaxAge = "2h" -# Ticket EV is approximately 2e11 wei; a 100-ticket batch fits the signer -# default 2e13 wei cap. Fund sufficient deposit and recipient-claimable reserve. -# TicketFaceValue = "400000000000" -# TicketWinProb = "57896044618658097711785492504343953926634992332820282019728792003956564819967" +# Baseline payout for a winning ticket, in wei. +# TicketFaceValue = "1000000000000000" +# MaxTicketEV = "3000000000000" +# MaxBatchEV = "20000000000000" +# MeteredTicketSeconds = 3 +# PayerDepositMultiplier = 1 # Remote redemption: set a public recipient address and omit local wallet/tx settings. # OrchestratorAddress = "0xYOUR_REGISTERED_ORCHESTRATOR" diff --git a/docs/http-api.md b/docs/http-api.md index 1e7657f..15bdb3e 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -246,6 +246,12 @@ example `"X-List: a,b",Authorization: Bearer credential`. ## Redeemer HTTP +`GET /fee-estimate` requires no ticket submission credential. It returns +`fee_wei` (a decimal string) and `expires_at` (RFC 3339) for the 95th percentile +of successful, finalized redemption fees. It returns `204` when fewer than 20 +samples are available in the last 24 hours. Do not use an estimate after its +expiry. + `POST /tickets` submits one winning ticket to a standalone redeemer. Send a JSON object with `chain_id` (a decimal string), `controller` (an Ethereum address), and `ticket`. The chain and Controller must match the redeemer's configuration. diff --git a/docs/metrics.md b/docs/metrics.md index 945f9af..1277ab7 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -83,6 +83,7 @@ gauges; timestamps use Unix seconds. Most event families appear on first use. | Lifecycle | `runner_events_total{event}`, `runner_health_checks_total{outcome}`, `session_reservations_total{outcome}`, `session_ends_total{reason}`, `session_duration_seconds`, with app identity. Reservations include allocations pending payment; only activated sessions contribute lifetime observations. | | Streams | `trickle_channels{kind="control\|session"}`, `trickle_buffered_bytes` for retained published segment bytes; `stream_transfer_bytes_total{app,app_id,runner_id,mode,protocol,direction}`, `stream_errors_total{app,app_id,runner_id,mode,protocol,outcome}`. Trickle requests are transport activity, not extra app invocations. | | Payments | `payment_operations_total{operation,outcome}` for challenge/receive/refresh/charge; `payment_operation_duration_seconds{operation}` for challenge/receive/refresh; `payment_tickets_total{kind="accepted\|winning"}`, `payment_credit_eth_total`, `payment_charge_eth_total`, `payment_billed_seconds_total`, `payment_fixed_charges_total`, with app identity. Credit is accepted expected ticket value; charges are successfully debited service usage. | +| Ticket sizing | `payment_gas_target_unmet_total` counts quotes whose funded face value is below the gas target. `payment_fee_estimate_errors_total` counts failed estimate polls. Both are aggregate counters. | | Signer | `signer_payments_total{type,outcome}`, `signer_payment_duration_seconds{type}`, `signer_tickets_total{type}`, `signer_sign_operations_total{kind,outcome}`. Signing kinds are ticket, segment, state, and orchestrator_info. Partial signing before a failed request remains visible. Successful payment/ticket totals follow required outbox persistence, even if response delivery is interrupted. | | Authorization | `signer_auth_webhook_requests_total{status,outcome}`, `signer_auth_webhook_duration_seconds`, `signer_auth_cache_hits_total`. Status zero means no webhook response; outcomes distinguish success, denied, and error. | | Redeemer authorization | `redeemer_auth_webhook_requests_total{status,outcome}`, `redeemer_auth_webhook_duration_seconds`. Status is the upstream HTTP status, or zero without a response; outcomes are `success`, `denied`, and `error`. | diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 5d554a6..67be04c 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -127,8 +127,7 @@ For paid operation, select an on-chain `Network` and supply: [Ethereum keystores](configuration.md#ethereum-keystores). - `RPCURLFile` or `LIVEPEER_ORCHESTRATOR_RPC_URL`: RPC credential. - `ChainID` and `Controller` for custom networks. -- `TicketFaceValue` and `TicketWinProb`: positive uint256 ticket parameters. - The winning probability must be less than `2^256 - 1`. +- `TicketFaceValue`: baseline payout for a winning ticket in wei. - Exactly one conversion source: `WeiPerUSD` or `ETHUSDFeed` (Arbitrum supplies a feed). The payment database has a [default path](configuration.md); `RedeemerDB` / @@ -142,6 +141,27 @@ Incomplete paid configuration fails startup. The orchestrator address must be ac on the configured chain. Runner prices use USD per hour for live work or USD per fixed request. Hourly discovery prices are normalized to USD and wei per second. +Node sizes tickets when it issues or refreshes paid session parameters. Face +value is limited by the payer's deposit divided by `PayerDepositMultiplier` +(default 1) and by recipient-claimable reserve after locally known unsettled wins. +Available reserve must cover every ticket winning in a fixed-price quote or a +metered session's ten-second opening batch. Node checks funding again when it +receives tickets. Later metered top-ups may have more tickets than the opening +batch. + +Node aims to keep redemption gas costs at 0.5% of face value, using the 95th +percentile of recent finalized redemption fees. Node continues to quote if +funding limits prevent it from meeting that target. When the estimate is +missing or stale, Node uses the funded baseline. Arbitrum fees include the L1 +posting charge. + +Fixed-price quotes use the fewest tickets that cover the price, up to 100. +Metered tickets target `MeteredTicketSeconds` seconds of quoted usage (default +3). The signer bills elapsed time and carries forward credit. Set `MaxTicketEV` +and `MaxBatchEV` to match the signer's limits, in wei. Their defaults are +`3000000000000` and `20000000000000`. Node accepts legacy `TicketWinProb` +configuration. Ticket odds are calculated from expected value and face value. + `WeiPerUSD` sets a fixed conversion. Alternatively, set `ETHUSDFeed` to a Chainlink-compatible ETH/USD feed on the payment chain. The feed is checked every hour; `PriceMaxAge` must be positive and defaults to two hours. Startup diff --git a/docs/payment-recovery.md b/docs/payment-recovery.md index 86bfe3b..ea09e31 100644 --- a/docs/payment-recovery.md +++ b/docs/payment-recovery.md @@ -71,6 +71,13 @@ data, including payment/accounting tables in the initial migrations. If downgrad is incompatible, retain the latest state for a compatible fix; restoring an old snapshot can lose events, winners, and transaction identities. +To roll back `006_fee_samples.sql`, stop each orchestrator and standalone +redeemer writer and back up its database. Use the newer binary's `migrate status` +to confirm migration 006 is the latest applied migration, then run `migrate down` +once with that binary and database path. This removes only fee sample history. +Restore the previous image and its matching configuration, and check migration +status with the previous binary before starting it. + ## Signer accounting recovery Keep `Kafka.OutboxDB` on persistent local storage, one file per replica. It uses diff --git a/eth/payment.go b/eth/payment.go index befa55d..b672ff6 100644 --- a/eth/payment.go +++ b/eth/payment.go @@ -68,31 +68,39 @@ func (c PaymentChain) activeAt(ctx context.Context, address, recipient ethcommon // FinalizedReceipt retains canonical inclusion evidence for durable collateral admission. func (c PaymentChain) FinalizedReceipt(ctx context.Context, hash ethcommon.Hash) (*types.Receipt, error) { + receipt, _, err := c.FinalizedReceiptWithTime(ctx, hash) + return receipt, err +} + +func (c PaymentChain) FinalizedReceiptWithTime(ctx context.Context, hash ethcommon.Hash) (*types.Receipt, time.Time, error) { receipt, err := c.Contracts.RPC.TransactionReceipt(ctx, hash) if errors.Is(err, ethereum.NotFound) { - return nil, nil + return nil, time.Time{}, nil } if err != nil { - return nil, err + return nil, time.Time{}, err } finalized, err := c.Contracts.RPC.header(ctx, "finalized") if err != nil { - return nil, err + return nil, time.Time{}, err } if finalized.Number == nil { - return nil, errors.New("invalid finalized header") + return nil, time.Time{}, errors.New("invalid finalized header") } if (*big.Int)(finalized.Number).Cmp(receipt.BlockNumber) < 0 { - return nil, nil + return nil, time.Time{}, nil } canonical, err := c.Contracts.RPC.header(ctx, hexutil.EncodeBig(receipt.BlockNumber)) if err != nil { - return nil, err + return nil, time.Time{}, err } if canonical.Hash != receipt.BlockHash { - return nil, nil + return nil, time.Time{}, nil } - return receipt, nil + if canonical.Timestamp == nil { + return receipt, time.Time{}, nil + } + return receipt, time.Unix(int64(*canonical.Timestamp), 0), nil } // Address retention adapts livepeer/go-livepeer eth/client.go setContracts at diff --git a/orchestrator/app.go b/orchestrator/app.go index 119c179..7803dc3 100644 --- a/orchestrator/app.go +++ b/orchestrator/app.go @@ -27,6 +27,7 @@ import ( "github.com/livepeer/node/internal/observability" "github.com/livepeer/node/nodeconfig" "github.com/livepeer/node/nodeconfig/migrations" + "github.com/livepeer/node/pm" "github.com/livepeer/node/redemption" "github.com/spf13/cobra" ) @@ -68,7 +69,11 @@ type Params struct { Controller *ethcommon.Address `name:"controller-address"` WeiPerUSD *big.Rat TicketFaceValue *uint256.Int - TicketWinProb *uint256.Int + TicketWinProb *uint256.Int `optional:"true" descr:"Legacy setting accepted for compatibility"` + MaxTicketEV *big.Rat `name:"max-ticket-ev" descr:"Maximum quoted EV per ticket in wei; defaults to the stock signer limit"` + MaxBatchEV *big.Rat `name:"max-batch-ev" descr:"Maximum quoted EV per payment batch in wei; defaults to the stock signer limit"` + MeteredTicketSeconds *int64 `min:"1" descr:"Seconds of quoted usage per metered ticket; defaults to 3"` + PayerDepositMultiplier *int64 `min:"1" descr:"Signer deposit multiplier; defaults to 1"` RunnerGrants []string `optional:"true" descr:"Private runner IP[:port] or CIDR grants"` SessionProxyGrants []string `optional:"true" descr:"Private session proxy IP[:port] or CIDR grants"` HealthGrants []string `optional:"true" descr:"Private static runner health IP[:port] or CIDR grants"` @@ -80,7 +85,25 @@ type Params struct { } func (p Params) paymentsRequested() bool { - return p.RedeemerURL != nil || p.Account != nil || p.OrchestratorAddress != nil || p.KeystoreFile != "" || p.KeystorePassword != nil || p.KeystorePasswordFile != "" || p.RedeemerDB != "" || p.RPCURL != nil || p.RPCURLFile != "" || p.ChainID != nil || p.Controller != nil || p.WeiPerUSD != nil || p.ETHUSDFeed != nil || p.TicketFaceValue != nil || p.TicketWinProb != nil || p.RedeemerMaxFeePerGas != nil + return p.RedeemerURL != nil || p.Account != nil || p.OrchestratorAddress != nil || p.KeystoreFile != "" || p.KeystorePassword != nil || p.KeystorePasswordFile != "" || p.RedeemerDB != "" || p.RPCURL != nil || p.RPCURLFile != "" || p.ChainID != nil || p.Controller != nil || p.WeiPerUSD != nil || p.ETHUSDFeed != nil || p.TicketFaceValue != nil || p.TicketWinProb != nil || p.RedeemerMaxFeePerGas != nil || + p.MaxTicketEV != nil || p.MaxBatchEV != nil || p.MeteredTicketSeconds != nil || p.PayerDepositMultiplier != nil +} + +func (p Params) ticketSizing() TicketSizing { + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + if p.MaxTicketEV != nil { + sizing.MaxTicketEV = p.MaxTicketEV + } + if p.MaxBatchEV != nil { + sizing.MaxBatchEV = p.MaxBatchEV + } + if p.MeteredTicketSeconds != nil { + sizing.MeteredTicketSeconds = *p.MeteredTicketSeconds + } + if p.PayerDepositMultiplier != nil { + sizing.DepositMultiplier = *p.PayerDepositMultiplier + } + return sizing } func (p Params) Validate() error { @@ -107,8 +130,8 @@ func (p Params) Validate() error { if p.OrchestratorAddress != nil && *p.OrchestratorAddress == (ethcommon.Address{}) { return errors.New("--orchestrator-address must be a nonempty Ethereum address") } - if (p.RedeemerURL == nil && p.KeystorePassword == nil && p.KeystorePasswordFile == "") || p.RedeemerDB == "" || p.RPCURL == nil || p.ChainID == nil || p.Controller == nil || (p.WeiPerUSD == nil && p.ETHUSDFeed == nil) || p.TicketFaceValue == nil || p.TicketWinProb == nil { - return errors.New("on-chain payment requires --redeemer-db, LIVEPEER_ORCHESTRATOR_KEYSTORE_PASSWORD or --keystore-password-file, LIVEPEER_ORCHESTRATOR_RPC_URL or --rpc-url-file, --chain-id, --controller-address, --wei-per-usd or --eth-usd-feed, --ticket-face-value and --ticket-win-prob") + if (p.RedeemerURL == nil && p.KeystorePassword == nil && p.KeystorePasswordFile == "") || p.RedeemerDB == "" || p.RPCURL == nil || p.ChainID == nil || p.Controller == nil || (p.WeiPerUSD == nil && p.ETHUSDFeed == nil) || p.TicketFaceValue == nil { + return errors.New("on-chain payment requires --redeemer-db, LIVEPEER_ORCHESTRATOR_KEYSTORE_PASSWORD or --keystore-password-file, LIVEPEER_ORCHESTRATOR_RPC_URL or --rpc-url-file, --chain-id, --controller-address, --wei-per-usd or --eth-usd-feed, and --ticket-face-value") } if p.RedeemerURL != nil { if _, err := redemption.RedeemerURL(p.RedeemerURL); err != nil { @@ -127,11 +150,14 @@ func (p Params) Validate() error { if *p.Controller == (ethcommon.Address{}) { return errors.New("--controller-address must be a nonempty Ethereum address") } - if *p.ChainID == 0 || p.TicketFaceValue.IsZero() || p.TicketWinProb.IsZero() { - return errors.New("--chain-id, --ticket-face-value and --ticket-win-prob must be positive") + if *p.ChainID == 0 || p.TicketFaceValue.IsZero() { + return errors.New("--chain-id and --ticket-face-value must be positive") } - if p.TicketWinProb.Eq(new(uint256.Int).SetAllOne()) { - return errors.New("--ticket-win-prob must be less than 2^256 - 1") + if p.TicketWinProb != nil && (p.TicketWinProb.IsZero() || p.TicketWinProb.Eq(new(uint256.Int).SetAllOne())) { + return errors.New("--ticket-win-prob must be less than 2^256 - 1 and positive") + } + if err := p.ticketSizing().validate(); err != nil { + return err } if p.RedeemerTxTimeout <= 0 || p.RedeemerMaxTxReplacements < 0 { return errors.New("--redeemer-tx-timeout must be positive and --redeemer-max-tx-replacements must be nonnegative") @@ -298,6 +324,8 @@ func printConfig(ctx *boa.HookContext, p *Params, out io.Writer) error { "RedeemerURL": &p.RedeemerURL, "RedeemerGrants": &p.RedeemerGrants, "MaxPendingTickets": &p.MaxPendingTickets, "MaxTicketsPerRecipient": &p.MaxTicketsPerRecipient, "RedeemerDB": &p.RedeemerDB, "ChainID": &p.ChainID, "RedeemerMaxFeePerGas": &p.RedeemerMaxFeePerGas, "Controller": &p.Controller, "WeiPerUSD": &p.WeiPerUSD, "ETHUSDFeed": &p.ETHUSDFeed, "PriceMaxAge": &p.PriceMaxAge, "TicketFaceValue": &p.TicketFaceValue, "TicketWinProb": &p.TicketWinProb, + "MaxTicketEV": &p.MaxTicketEV, "MaxBatchEV": &p.MaxBatchEV, + "MeteredTicketSeconds": &p.MeteredTicketSeconds, "PayerDepositMultiplier": &p.PayerDepositMultiplier, } for name, ptr := range values { if !ctx.HasValue(ptr) { @@ -423,9 +451,9 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { return err } observedChain.Observer = eth.NewPaymentObserver(paymentChain, p.Network == nodeconfig.Mainnet, recipient) - engine, err = NewPaymentEngine(redeemerDB, observedChain, recipient, p.TicketFaceValue.ToBig(), p.TicketWinProb.ToBig()) + engine, err = NewAdaptivePaymentEngine(redeemerDB, observedChain, recipient, p.TicketFaceValue.ToBig(), p.ticketSizing()) if err != nil { - return fmt.Errorf("initialize payment engine (check --account, --ticket-face-value and --ticket-win-prob): %w", err) + return fmt.Errorf("initialize payment engine (check --account and ticket sizing settings): %w", err) } } registry.proxyTemplate = p.ProxyURLTemplate @@ -482,6 +510,7 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { metricsMux.Handle("GET /metrics", registry.metrics.Handler()) ctx, cancel := signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM) defer cancel() + var readFeeEstimate func(context.Context) (*redemption.FeeEstimate, error) if engine != nil { var target redemption.Destination if p.RedeemerURL != nil { @@ -499,12 +528,14 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { } defer remote.Close() target = remote + readFeeEstimate = remote.FeeEstimate } else { local, e := redemption.NewChainDestination(eth.WithRPCWork(ctx, "background"), redeemerDB.RedeemerDB, paymentChain, redeemerKey, paymentChainID, redemption.RedemptionOptions{Timeout: p.RedeemerTxTimeout, MaxReplacements: p.RedeemerMaxTxReplacements}) if e != nil { return e } target = local + readFeeEstimate = redeemerDB.FeeEstimate } redemptionWorker, err = redemption.NewWorker(redeemerDB.RedeemerDB, paymentChain, target) if err != nil { @@ -541,6 +572,19 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { workers.Go(func() { app.runO2RKeepalives(ctx, 10*time.Second) }) if engine != nil { workers.Go(func() { observedChain.Observer.Run(ctx) }) + startWorker(time.Minute, 5*time.Second, func(ctx context.Context) { + fee, err := readFeeEstimate(ctx) + if err != nil { + registry.metrics.Add("payment_fee_estimate_errors_total", 1, nil) + return + } + if fee != nil { + if limit := time.Now().Add(5 * time.Minute); fee.ExpiresAt.After(limit) { + fee.ExpiresAt = limit + } + } + engine.redemptionFee.Store(fee) + }) startWorker(p.HeartbeatInterval, 30*time.Second, func(ctx context.Context) { readiness.check(ctx, redeemerDB, observedChain, engine, registry.metrics, logger) }) @@ -562,8 +606,9 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { logger.Error("payment retention", "event", "payment_retention", "operation", "prune", "outcome", "error", "error_kind", observability.ErrorKind(err)) } }) - startWorker(p.HeartbeatInterval, 30*time.Second, func(ctx context.Context) { - failures := redemptionWorker.Process(ctx) + startWorker(p.HeartbeatInterval, 30*time.Second, func(passCtx context.Context) { + failures := redemptionWorker.Process(passCtx) + redemptionWorker.CollectFees(ctx) for _, err := range failures { registry.metrics.Add("redemption_errors_total", 1, observability.Labels{"error_kind": observability.ErrorKind(err)}) logger.Error("redemption failed", "event", "redemption_pass", "operation", "redeem", "outcome", "error", "error_kind", observability.ErrorKind(err)) diff --git a/orchestrator/app_test.go b/orchestrator/app_test.go index 48114fb..2d71e0c 100644 --- a/orchestrator/app_test.go +++ b/orchestrator/app_test.go @@ -105,6 +105,7 @@ func TestPaidHTTPStartup(t *testing.T) { address := fmt.Sprintf("http://127.0.0.1:%d", mainPort) p := paymentKeystoreParams(t, "http://127.0.0.1:1") p.HeartbeatInterval = time.Second + p.TicketFaceValue, p.TicketWinProb = uint256.NewInt(100), nil p.KeystoreFile, p.KeystorePasswordFile = test.WriteFixedKeystore(t) key, err := eth.OpenKeystoreFile(p.KeystoreFile, p.KeystorePasswordFile) require.NoError(t, err) @@ -215,6 +216,8 @@ func TestPaidHTTPStartup(t *testing.T) { require.NoError(t, err) require.Equal(t, recipient.Bytes(), info.Address) require.Equal(t, recipient.Bytes(), info.TicketParams.Recipient) + require.Equal(t, uint64(100), new(big.Int).SetBytes(info.TicketParams.FaceValue).Uint64()) + require.Equal(t, uint64(3), new(big.Int).Quo(new(big.Int).Mul(new(big.Int).SetBytes(info.TicketParams.WinProb), big.NewInt(100)), maxWinProb).Uint64()) require.Eventually(t, func() bool { ready, err := client.Get(metricsURL + "/readyz") if err != nil { diff --git a/orchestrator/metrics.go b/orchestrator/metrics.go index 64906eb..0cee2f0 100644 --- a/orchestrator/metrics.go +++ b/orchestrator/metrics.go @@ -246,7 +246,7 @@ func paymentOutcome(err error) string { return "already_charged" case errors.Is(err, ErrInsufficientBalance): return "insufficient_balance" - case errors.Is(err, ErrInvalidPayment), errors.Is(err, pm.ErrPayerUnavailable): + case errors.Is(err, ErrInvalidPayment), errors.Is(err, pm.ErrPayerUnavailable), errors.Is(err, errQuoteUnpayable): return "rejected" case errors.Is(err, ErrMissingChallenge): return "missing_challenge" diff --git a/orchestrator/metrics_test.go b/orchestrator/metrics_test.go index 49fd5fd..b601db9 100644 --- a/orchestrator/metrics_test.go +++ b/orchestrator/metrics_test.go @@ -87,7 +87,8 @@ func TestPaidReadinessUsesCurrentPublication(t *testing.T) { }) require.EqualValues(t, 1, unknown, "a healthy current observer cannot authorize a saved orphaned queue clock") ticket.Sig = []byte{99, 2, 3} - require.ErrorIs(t, store.storeWinningTickets(t.Context(), ticket.PayerAddress, ticket.RecipientRandHash, big.NewInt(10000), []*pm.SignedTicket{ticket}, snapshot), eth.ErrObservationUnavailable) + funds := pm.PayerFunds{Snapshot: snapshot, Deposit: big.NewInt(10000), Reserve: new(big.Int)} + require.ErrorIs(t, store.storeWinningTickets(t.Context(), ticket.PayerAddress, ticket.RecipientRandHash, funds, []*pm.SignedTicket{ticket}, nil), eth.ErrObservationUnavailable) count, err := store.WinningTicketCount(ticket.PayerAddress) require.NoError(t, err) require.Equal(t, 1, count, "invalidated admission must roll back its ticket insert") diff --git a/orchestrator/payment.go b/orchestrator/payment.go index 1a0f8a8..517fa8d 100644 --- a/orchestrator/payment.go +++ b/orchestrator/payment.go @@ -10,6 +10,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/livepeer/node/eth" "github.com/livepeer/node/internal/observability" + "github.com/livepeer/node/pm" ) func paymentPrice(price priceInfo) (int64, bool) { @@ -40,12 +41,23 @@ func (s *Server) challenge(w http.ResponseWriter, r *http.Request, appID string, if err != nil { observability.Outcome(r, paymentAppOutcome(err)) s.logger.Warn("payment challenge failed", "event", "payment_challenge", "operation", "challenge", "runner_id", s.registry.identity(appID, manifest).Runner, "app_id", appID, "outcome", paymentOutcome(err), "error_kind", observability.ErrorKind(err)) - fail(w, 502, "payment challenge unavailable") + failPaymentChallenge(w, err, http.StatusBadGateway, "payment challenge unavailable") return } writeJSON(w, http.StatusPaymentRequired, challenge) } +func failPaymentChallenge(w http.ResponseWriter, err error, status int, message string) { + switch { + case errors.Is(err, pm.ErrPayerUnavailable): + fail(w, http.StatusBadRequest, pm.ErrPayerUnavailable.Error()) + case errors.Is(err, errQuoteUnpayable): + fail(w, http.StatusBadRequest, errQuoteUnpayable.Error()) + default: + fail(w, status, message) + } +} + func (s *Server) paidReceipt(w http.ResponseWriter, r *http.Request, appID string, price priceInfo) (string, bool) { manifest, err := ManifestFromSegment(r.Header.Get("Livepeer-Segment")) if err != nil { @@ -224,7 +236,11 @@ func (s *Server) refreshPayment(w http.ResponseWriter, r *http.Request) { } challenge, err := s.payment.RefreshChallenge(r.Context(), request.ManifestID, ethcommon.HexToAddress(request.PayerAddress), s.registry.service) if err != nil { - fail(w, 404, "payment challenge not found") + if errors.Is(err, ErrMissingChallenge) || errors.Is(err, ErrInvalidPayment) { + fail(w, http.StatusNotFound, "payment challenge not found") + } else { + failPaymentChallenge(w, err, http.StatusBadGateway, "payment challenge unavailable") + } return } writeJSON(w, http.StatusOK, challenge) diff --git a/orchestrator/payment_engine.go b/orchestrator/payment_engine.go index 3d3142d..2aede1e 100644 --- a/orchestrator/payment_engine.go +++ b/orchestrator/payment_engine.go @@ -11,6 +11,7 @@ import ( "math/big" "strconv" "sync" + "sync/atomic" "time" ethcommon "github.com/ethereum/go-ethereum/common" @@ -18,6 +19,7 @@ import ( "github.com/livepeer/node/internal/observability" "github.com/livepeer/node/pm" "github.com/livepeer/node/pm/wire" + "github.com/livepeer/node/redemption" ) var maxWinProb = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) @@ -34,6 +36,9 @@ type PaymentEngine struct { recipient ethcommon.Address faceValue *big.Int winProb *big.Int + sizing *TicketSizing + redemptionFee atomic.Pointer[redemption.FeeEstimate] + gasWarningAt atomic.Int64 secret [32]byte authSecret [32]byte sessions map[string]*paymentSession @@ -58,10 +63,22 @@ type paymentSession struct { } func NewPaymentEngine(store *RedeemerDB, chain pm.PaymentChain, recipient ethcommon.Address, faceValue, winProb *big.Int) (*PaymentEngine, error) { - if store == nil || chain == nil || recipient == (ethcommon.Address{}) || faceValue == nil || faceValue.Sign() <= 0 || winProb == nil || winProb.Sign() <= 0 || winProb.Cmp(maxWinProb) >= 0 { + if winProb == nil || winProb.Sign() <= 0 || winProb.Cmp(maxWinProb) >= 0 { return nil, errors.New("invalid payment engine configuration") } - e := &PaymentEngine{store: store, chain: chain, recipient: recipient, faceValue: new(big.Int).Set(faceValue), winProb: new(big.Int).Set(winProb), sessions: make(map[string]*paymentSession), ticketNonces: make(map[string]*recipientNonces), lastSeenBlock: new(big.Int)} + e, err := newPaymentEngine(store, chain, recipient, faceValue) + if err != nil { + return nil, err + } + e.winProb = new(big.Int).Set(winProb) + return e, nil +} + +func newPaymentEngine(store *RedeemerDB, chain pm.PaymentChain, recipient ethcommon.Address, faceValue *big.Int) (*PaymentEngine, error) { + if store == nil || chain == nil || recipient == (ethcommon.Address{}) || faceValue == nil || faceValue.Sign() <= 0 || faceValue.BitLen() > 256 { + return nil, errors.New("invalid payment engine configuration") + } + e := &PaymentEngine{store: store, chain: chain, recipient: recipient, faceValue: new(big.Int).Set(faceValue), sessions: make(map[string]*paymentSession), ticketNonces: make(map[string]*recipientNonces), lastSeenBlock: new(big.Int)} // Port of Yondon Fu's go-livepeer/pm.NewRecipient: a fresh 256-bit HMAC // key per recipient lifetime. AuthToken has its own independent key. rand.Read(e.secret[:]) @@ -97,7 +114,7 @@ func (e *PaymentEngine) makeChallenge(ctx context.Context, appID, manifest strin if appID == "" || manifest == "" || payer == (ethcommon.Address{}) || price <= 0 || (unit != "seconds" && unit != "fixed") { return Challenge{}, errors.New("invalid payment challenge scope") } - snapshot, err := e.chain.Snapshot(ctx) + snapshot, faceValue, winProb, err := e.quoteTicket(ctx, payer, price, unit) if err != nil { return Challenge{}, err } @@ -119,10 +136,10 @@ func (e *PaymentEngine) makeChallenge(ctx context.Context, appID, manifest strin priceInfo := wire.PriceInfo{PricePerUnit: price, UnitsPerPrice: 1} expiration := &pm.TicketExpirationParams{CreationRound: snapshot.Round.Int64(), CreationRoundBlockHash: snapshot.RoundHash} expiresAtBlock := new(big.Int).Add(snapshot.Block, big.NewInt(40)) - recipientRand := e.recipientRand(new(big.Int).SetBytes(seed), payer, e.faceValue, e.winProb, expiresAtBlock, big.NewRat(price, 1), expiration) + recipientRand := e.recipientRand(new(big.Int).SetBytes(seed), payer, faceValue, winProb, expiresAtBlock, big.NewRat(price, 1), expiration) randHash := crypto.Keccak256Hash(ethcommon.LeftPadBytes(recipientRand.Bytes(), 32)) info := wire.OrchestratorInfo{Transcoder: service, Address: e.recipient.Bytes(), Price: priceInfo, - TicketParams: wire.TicketParams{Recipient: e.recipient.Bytes(), FaceValue: e.faceValue.Bytes(), WinProb: e.winProb.Bytes(), RecipientRandHash: randHash.Bytes(), Seed: seed, ExpirationBlock: expiresAtBlock.Bytes(), Expiration: wire.ExpirationParams{CreationRound: expiration.CreationRound, CreationRoundBlockHash: expiration.CreationRoundBlockHash.Bytes()}}, + TicketParams: wire.TicketParams{Recipient: e.recipient.Bytes(), FaceValue: faceValue.Bytes(), WinProb: winProb.Bytes(), RecipientRandHash: randHash.Bytes(), Seed: seed, ExpirationBlock: expiresAtBlock.Bytes(), Expiration: wire.ExpirationParams{CreationRound: expiration.CreationRound, CreationRoundBlockHash: expiration.CreationRoundBlockHash.Bytes()}}, Auth: e.authToken(manifest, time.Now().Add(time.Hour).Unix())} encoded := wire.EncodeOrchestratorInfo(info) challenge := paymentChallenge(appID, manifest, service, encoded) @@ -248,7 +265,7 @@ func (e *PaymentEngine) Receive(ctx context.Context, appID, manifest, paymentHea appMatches, payerMatches, price := session.appID == appID, session.payer == payer, session.price e.mu.Unlock() params, recipientRand, err := e.authenticatePayment(payment, segment.Auth) - if err != nil || !appMatches || !payerMatches || payment.ExpectedPrice != price || len(payment.PayerParams) == 0 || len(payment.PayerParams) > 100 { + if err != nil || !appMatches || !payerMatches || payment.ExpectedPrice != price || len(payment.PayerParams) == 0 || len(payment.PayerParams) > pm.MaxTicketBatchSize { return ethcommon.Address{}, nil, ErrInvalidPayment } flatten := append([]byte(manifest), make([]byte, 32)...) @@ -275,7 +292,11 @@ func (e *PaymentEngine) Receive(ctx context.Context, appID, manifest, paymentHea if err := pm.ValidatePayerFunds(funds); err != nil { return ethcommon.Address{}, nil, paymentObservation{err, "rejected"} } - if funds.Reserve.Cmp(params.FaceValue) < 0 || funds.Deposit.Cmp(params.FaceValue) < 0 { + deposit := funds.Deposit + if e.sizing != nil { + deposit = new(big.Int).Quo(deposit, big.NewInt(e.sizing.DepositMultiplier)) + } + if funds.Reserve.Cmp(params.FaceValue) < 0 || deposit.Cmp(params.FaceValue) < 0 { if e.store != nil && e.store.logger != nil { e.store.logger.WarnContext(ctx, "orchestrator payer deposit or claimable reserve below ticket face value", "event", "payment", "operation", "receive", "outcome", "rejected", "payer", payer, "deposit", funds.Deposit, "claimable_reserve", funds.Reserve, "face_value", params.FaceValue) } @@ -334,7 +355,11 @@ func (e *PaymentEngine) Receive(ctx context.Context, appID, manifest, paymentHea } } balance := new(big.Rat).Add(session.balance, batchCredit) - if err := e.store.storeWinningTickets(ctx, payer, params.RecipientRandHash, new(big.Int).Add(funds.Deposit, funds.Reserve), winners, snapshot); err != nil { + var funding *redemption.ReceiptFunding + if e.sizing != nil { + funding = &redemption.ReceiptFunding{Recipient: e.recipient, Reserve: funds.Reserve, FaceValue: params.FaceValue} + } + if err := e.store.storeWinningTickets(ctx, payer, params.RecipientRandHash, funds, winners, funding); err != nil { return ethcommon.Address{}, nil, err } if previous == nil { diff --git a/orchestrator/redemption.go b/orchestrator/redemption.go index 9496f64..2438988 100644 --- a/orchestrator/redemption.go +++ b/orchestrator/redemption.go @@ -50,8 +50,9 @@ func (s *RedeemerDB) configure() { }) } -func (s *RedeemerDB) storeWinningTickets(ctx context.Context, payer common.Address, randHash common.Hash, collateral *big.Int, tickets []*pm.SignedTicket, snapshot pm.ChainSnapshot) error { - err := s.StoreWinningTickets(ctx, payer, randHash, collateral, tickets, snapshot) +func (s *RedeemerDB) storeWinningTickets(ctx context.Context, payer common.Address, randHash common.Hash, funds pm.PayerFunds, tickets []*pm.SignedTicket, funding *redemption.ReceiptFunding) error { + collateral := new(big.Int).Add(funds.Deposit, funds.Reserve) + err := s.StoreFundedWinningTickets(ctx, payer, randHash, collateral, tickets, funds.Snapshot, funding) if errors.Is(err, redemption.ErrExposedRandomness) { return ErrInvalidPayment } diff --git a/orchestrator/ticket_sizing.go b/orchestrator/ticket_sizing.go new file mode 100644 index 0000000..733035c --- /dev/null +++ b/orchestrator/ticket_sizing.go @@ -0,0 +1,138 @@ +package orchestrator + +import ( + "context" + "errors" + "fmt" + "math/big" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/livepeer/node/pm" +) + +// TicketSizing limits the exposure of ticket parameters quoted by the orchestrator. +type TicketSizing struct { + pm.PayerPolicy + MeteredTicketSeconds int64 +} + +func (s TicketSizing) validate() error { + if s.MeteredTicketSeconds < 1 { + return errors.New("metered ticket duration must be positive") + } + return s.PayerPolicy.Validate() +} + +func NewAdaptivePaymentEngine(store *RedeemerDB, chain pm.PaymentChain, recipient common.Address, baseline *big.Int, sizing TicketSizing) (*PaymentEngine, error) { + if err := sizing.validate(); err != nil { + return nil, err + } + engine, err := newPaymentEngine(store, chain, recipient, baseline) + if err != nil { + return nil, err + } + sizing.MaxTicketEV = new(big.Rat).Set(sizing.MaxTicketEV) + sizing.MaxBatchEV = new(big.Rat).Set(sizing.MaxBatchEV) + engine.sizing = &sizing + return engine, nil +} + +var errQuoteUnpayable = errors.New("quote cannot be paid within ticket EV and funding limits") + +func (e *PaymentEngine) quoteTicket(ctx context.Context, payer common.Address, price int64, unit string) (pm.ChainSnapshot, *big.Int, *big.Int, error) { + if e.sizing == nil { + snapshot, err := e.chain.Snapshot(ctx) + return snapshot, e.faceValue, e.winProb, err + } + funds, err := e.chain.PayerFunds(ctx, payer, e.recipient) + if err != nil { + return pm.ChainSnapshot{}, nil, nil, err + } + if err := pm.ValidatePayerFunds(funds); err != nil { + return pm.ChainSnapshot{}, nil, nil, fmt.Errorf("%w: %v", pm.ErrPayerUnavailable, err) + } + pending, err := e.store.RecipientLiability(ctx, payer, e.recipient) + if err != nil { + return pm.ChainSnapshot{}, nil, nil, err + } + reserve := new(big.Int).Sub(funds.Reserve, pending) + if reserve.Sign() <= 0 { + return pm.ChainSnapshot{}, nil, nil, pm.ErrPayerUnavailable + } + deposit := new(big.Int).Quo(funds.Deposit, big.NewInt(e.sizing.DepositMultiplier)) + if deposit.Sign() <= 0 { + return pm.ChainSnapshot{}, nil, nil, pm.ErrPayerUnavailable + } + now := time.Now() + desiredFace := e.faceValue + var gasTarget *big.Int + if estimate := e.redemptionFee.Load(); estimate != nil && now.Before(estimate.ExpiresAt) { + gasTarget = new(big.Int).Mul(estimate.Wei, big.NewInt(200)) + if gasTarget.Cmp(desiredFace) > 0 { + desiredFace = minBigInt(gasTarget, maxWinProb) + } + } + face, odds, err := e.sizing.ticketTerms(minBigInt(desiredFace, deposit), reserve, price, unit) + if err == nil && gasTarget != nil && face.Cmp(gasTarget) < 0 { + e.metrics.Add("payment_gas_target_unmet_total", 1, nil) + if last := e.gasWarningAt.Load(); e.store.logger != nil && now.Unix()-last >= 60 && e.gasWarningAt.CompareAndSwap(last, now.Unix()) { + e.store.logger.Warn("payment face value below redemption gas target", "event", "payment_challenge", "face_value", face, "target_face_value", gasTarget) + } + } + return funds.Snapshot, face, odds, err +} + +func minBigInt(a, b *big.Int) *big.Int { + if a.Cmp(b) <= 0 { + return a + } + return b +} + +func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit string) (*big.Int, *big.Int, error) { + metered := unit == "seconds" + fee := big.NewRat(price, 1) + var meteredEV *big.Rat + if metered { + meteredEV = new(big.Rat).Mul(fee, big.NewRat(s.MeteredTicketSeconds, 1)) + fee.Mul(fee, big.NewRat(pm.InitialLivePaymentSeconds, 1)) + } + if fee.Cmp(s.MaxBatchEV) > 0 { + return nil, nil, errQuoteUnpayable + } + maxValidOdds := new(big.Int).Sub(maxWinProb, big.NewInt(1)) + for count := int64(1); count <= pm.MaxTicketBatchSize; count++ { + // Every ticket in the quoted batch may win. + face := minBigInt(faceLimit, new(big.Int).Quo(reserve, big.NewInt(count))) + if face.Sign() == 0 { + break + } + maxOdds := minBigInt(ticketProbability(s.MaxTicketEV, face, big.Floor), maxValidOdds) + if metered { + maxOdds = minBigInt(maxOdds, ticketProbability(meteredEV, face, big.Ceil)) + } + tickets := big.NewRat(count, 1) + minOdds := ticketProbability(new(big.Rat).Quo(fee, tickets), face, big.Ceil) + if minOdds.Cmp(maxOdds) > 0 { + continue + } + batchOdds := ticketProbability(new(big.Rat).Quo(s.MaxBatchEV, tickets), face, big.Floor) + if minOdds.Cmp(batchOdds) <= 0 { + if metered { + // Aim for the cadence EV, with enough room for the signer to open + // the session without exceeding its batch limit. + return face, minBigInt(maxOdds, batchOdds), nil + } + return face, minOdds, nil + } + } + return nil, nil, errQuoteUnpayable +} + +func ticketProbability(ev *big.Rat, face *big.Int, rounding big.RoundingMode) *big.Int { + scaled := new(big.Int).Mul(ev.Num(), maxWinProb) + denominator := new(big.Int).Mul(ev.Denom(), face) + odds, _ := new(big.Int).Divide(scaled, denominator, nil, rounding) + return odds +} diff --git a/orchestrator/ticket_sizing_test.go b/orchestrator/ticket_sizing_test.go new file mode 100644 index 0000000..d778352 --- /dev/null +++ b/orchestrator/ticket_sizing_test.go @@ -0,0 +1,79 @@ +package orchestrator + +import ( + "context" + "math/big" + "path/filepath" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/livepeer/node/pm" + "github.com/livepeer/node/redemption" + "github.com/stretchr/testify/require" +) + +func TestAdaptiveFaceValue(t *testing.T) { + store, err := OpenRedeemerDB(filepath.Join(t.TempDir(), "tickets.sqlite")) + require.NoError(t, err) + defer store.Close() + chain := &recipientTestChain{active: true, block: 50} + engine, err := NewAdaptivePaymentEngine(store, chain, common.HexToAddress("0x1234"), big.NewInt(1000), TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3}) + require.NoError(t, err) + now := time.Now() + chain.funds = func(_ context.Context, funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.Deposit, funds.Reserve = big.NewInt(6000), big.NewInt(5000) + return funds, nil + } + face := func() int64 { + _, face, _, err := engine.quoteTicket(t.Context(), common.HexToAddress("0x5678"), 10, "fixed") + require.NoError(t, err) + return face.Int64() + } + require.EqualValues(t, 1000, face()) + engine.redemptionFee.Store(&redemption.FeeEstimate{Wei: big.NewInt(30), ExpiresAt: now.Add(time.Minute)}) + require.EqualValues(t, 5000, face()) + engine.redemptionFee.Store(&redemption.FeeEstimate{Wei: big.NewInt(30), ExpiresAt: now}) + require.EqualValues(t, 1000, face()) +} + +func TestQuotedBatchFitsAvailableReserve(t *testing.T) { + sizing := TicketSizing{PayerPolicy: pm.PayerPolicy{ + MaxTicketEV: big.NewRat(30_000_000_000_000, 1), MaxBatchEV: big.NewRat(3_000_000_000_000_000, 1), DepositMultiplier: 1, + }, MeteredTicketSeconds: 3} + reserve := big.NewInt(526_552_682_532_519) + for _, tt := range []struct { + unit string + price, openingFee int64 + tickets int + }{ + {"fixed", 201_300_000_000_000, 201_300_000_000_000, 7}, + {"seconds", 10_000_000_000, 10_000_000_000 * pm.InitialLivePaymentSeconds, 4}, + } { + t.Run(tt.unit, func(t *testing.T) { + face, odds, err := sizing.ticketTerms(big.NewInt(1_053_105_365_065_039), reserve, tt.price, tt.unit) + require.NoError(t, err) + count, err := pm.RemoteBatchSize(pm.TicketParams{FaceValue: face, WinProb: odds}, big.NewRat(tt.openingFee, 1), new(big.Rat)) + require.NoError(t, err) + require.Equal(t, tt.tickets, count) + require.Equal(t, new(big.Int).Quo(reserve, big.NewInt(int64(count))), face) + }) + } +} + +func TestMeteredOpeningFitsBatchLimit(t *testing.T) { + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + const rate = 1_800_000_000_000 + limit := big.NewInt(1_053_105_365_065_039) + reserve := new(big.Int).Mul(limit, big.NewInt(pm.MaxTicketBatchSize)) + face, odds, err := sizing.ticketTerms(limit, reserve, rate, "seconds") + require.NoError(t, err) + params := pm.TicketParams{FaceValue: face, WinProb: odds} + count, err := pm.RemoteBatchSize(params, big.NewRat(rate*pm.InitialLivePaymentSeconds, 1), new(big.Rat)) + require.NoError(t, err) + require.Equal(t, 7, count) + ev := new(big.Rat).SetFrac(new(big.Int).Mul(face, odds), maxWinProb) + require.LessOrEqual(t, new(big.Rat).Mul(ev, big.NewRat(int64(count), 1)).Cmp(sizing.MaxBatchEV), 0) + _, _, err = sizing.ticketTerms(limit, reserve, 2_000_000_000_001, "seconds") + require.ErrorIs(t, err, errQuoteUnpayable) +} diff --git a/pm/payerpolicy.go b/pm/payerpolicy.go index baf7e44..a026e8c 100644 --- a/pm/payerpolicy.go +++ b/pm/payerpolicy.go @@ -42,7 +42,7 @@ func (p PayerPolicy) Check(params TicketParams, count int, funds PayerFunds) err if err := ValidatePayerFunds(funds); err != nil { return fmt.Errorf("%w: %v", ErrPayerUnavailable, err) } - if params.FaceValue == nil || params.WinProb == nil || params.FaceValue.Sign() <= 0 || params.WinProb.Sign() <= 0 || params.WinProb.Cmp(maxWinProb) >= 0 || count < 1 || count > 100 { + if params.FaceValue == nil || params.WinProb == nil || params.FaceValue.Sign() <= 0 || params.WinProb.Sign() <= 0 || params.WinProb.Cmp(maxWinProb) >= 0 || count < 1 || count > MaxTicketBatchSize { return errors.New("invalid ticket exposure") } ev := ticketEV(params.FaceValue, params.WinProb) diff --git a/pm/remotepayment.go b/pm/remotepayment.go index 1ab3bc6..8b0bbf5 100644 --- a/pm/remotepayment.go +++ b/pm/remotepayment.go @@ -12,6 +12,11 @@ type TicketSigner interface { SignMessage([]byte) ([]byte, error) } +const ( + MaxTicketBatchSize = 100 + InitialLivePaymentSeconds = 10 +) + // RemoteBatchSize retains the legacy minimum-credit floor of one ticket EV. // The fee is still debited from the balance after the tickets are created. // Adapted from Yondon Fu's go-livepeer/server/segment_rpc.go newBalanceUpdate @@ -36,7 +41,7 @@ func RemoteBatchSize(params TicketParams, fee, balance *big.Rat) (int, error) { } countRat := new(big.Rat).Quo(shortfall, ev) count, _ := new(big.Int).Divide(countRat.Num(), countRat.Denom(), nil, big.Ceil) - if !count.IsInt64() || count.Int64() > 100 { + if !count.IsInt64() || count.Int64() > MaxTicketBatchSize { return 0, errors.New("ticket batch exceeds 100") } return int(count.Int64()), nil diff --git a/redeemer/app.go b/redeemer/app.go index 6eafe63..56c7ce4 100644 --- a/redeemer/app.go +++ b/redeemer/app.go @@ -243,6 +243,7 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { logger.Error("redemption pass failed", "event", "redemption_pass", "error_kind", observability.ErrorKind(err)) } done() + worker.CollectFees(ctx) // Exhausting a processing batch is healthy progress. Probe the // dependencies with their own budget rather than its expired context. tick, done = context.WithTimeout(eth.WithRPCWork(ctx, "background"), 15*time.Second) diff --git a/redemption/fees.go b/redemption/fees.go new file mode 100644 index 0000000..3029e6b --- /dev/null +++ b/redemption/fees.go @@ -0,0 +1,192 @@ +package redemption + +import ( + "context" + "encoding/json" + "errors" + "math/big" + "net/http" + "slices" + "sync" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" +) + +const ( + feeWindow = 24 * time.Hour + maxFeeSamples = 2048 + minFeeSamples = 20 +) + +func (s *RedeemerDB) recordFee(ctx context.Context, hash common.Hash, receipt *types.Receipt, minedAt time.Time) error { + cutoff := time.Now().Add(-feeWindow) + if receipt.Status != types.ReceiptStatusSuccessful || receipt.GasUsed == 0 || + receipt.EffectiveGasPrice == nil || receipt.EffectiveGasPrice.Sign() <= 0 || !minedAt.After(cutoff) { + return nil + } + // Arbitrum charges for posting to L1 in the receipt's gas units. + wei := new(big.Int).Mul(new(big.Int).SetUint64(receipt.GasUsed), receipt.EffectiveGasPrice) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `INSERT INTO redemption_fee_samples(hash,block_time,fee) VALUES(?,?,?) + ON CONFLICT(hash) DO UPDATE SET block_time=excluded.block_time,fee=excluded.fee WHERE fee IS NULL`, hash.Hex(), minedAt.Unix(), wei.Bytes()); err != nil { + return err + } + _, err = tx.ExecContext(ctx, `DELETE FROM redemption_fee_samples WHERE block_time<=? OR hash IN + (SELECT hash FROM redemption_fee_samples WHERE fee IS NOT NULL ORDER BY block_time DESC,hash LIMIT -1 OFFSET ?)`, cutoff.Unix(), maxFeeSamples) + if err != nil { + return err + } + return tx.Commit() +} + +func (s *RedeemerDB) collectUsedFees(ctx context.Context, chain timedReceiptReader) error { + now := time.Now() + if _, err := s.db.ExecContext(ctx, "DELETE FROM redemption_fee_samples WHERE block_time<=?", now.Add(-feeWindow).Unix()); err != nil { + return err + } + rows, err := s.db.QueryContext(ctx, `SELECT hash FROM redemption_fee_samples + WHERE fee IS NULL AND block_time>? AND next_attempt<=? ORDER BY next_attempt,hash LIMIT 32`, now.Add(-feeWindow).Unix(), now.Unix()) + if err != nil { + return err + } + var hashes []string + for rows.Next() { + var hash string + if err := rows.Scan(&hash); err != nil { + rows.Close() + return err + } + hashes = append(hashes, hash) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + var result error + for _, hash := range hashes { + // Slow down repeated misses as an attempt ages, up to an hour. + if _, err := s.db.ExecContext(ctx, `UPDATE redemption_fee_samples + SET next_attempt=?1+min(3600,60+max(0,?1-block_time)/4) WHERE hash=?2`, time.Now().Unix(), hash); err != nil { + return errors.Join(result, err) + } + receipt, minedAt, err := chain.FinalizedReceiptWithTime(ctx, common.HexToHash(hash)) + if err == nil && receipt != nil { + err = s.recordFee(ctx, common.HexToHash(hash), receipt, minedAt) + } + if err == nil && receipt != nil { + _, err = s.db.ExecContext(ctx, "DELETE FROM redemption_fee_samples WHERE hash=? AND fee IS NULL", hash) + } + result = errors.Join(result, err) + } + return result +} + +type FeeEstimate struct { + Wei *big.Int + ExpiresAt time.Time +} + +func (s *RedeemerDB) FeeEstimate(ctx context.Context) (*FeeEstimate, error) { + now := time.Now() + rows, err := s.db.QueryContext(ctx, "SELECT block_time,fee FROM redemption_fee_samples WHERE fee IS NOT NULL AND block_time>? ORDER BY block_time DESC", now.Add(-feeWindow).Unix()) + if err != nil { + return nil, err + } + defer rows.Close() + var costs []*big.Int + expiresAt := now.Add(5 * time.Minute) + for rows.Next() { + var fee []byte + var blockTime int64 + if err := rows.Scan(&blockTime, &fee); err != nil { + return nil, err + } + costs = append(costs, new(big.Int).SetBytes(fee)) + if cutoff := time.Unix(blockTime, 0).Add(feeWindow); len(costs) == minFeeSamples && cutoff.Before(expiresAt) { + expiresAt = cutoff + } + } + if err := rows.Err(); err != nil { + return nil, err + } + if len(costs) < minFeeSamples { + return nil, nil + } + slices.SortFunc(costs, (*big.Int).Cmp) + return &FeeEstimate{Wei: costs[(95*len(costs)+99)/100-1], ExpiresAt: expiresAt}, nil +} + +type feeEstimateResponse struct { + Wei string `json:"fee_wei"` + ExpiresAt time.Time `json:"expires_at"` +} + +func (s *RedeemerDB) feeEstimateHandler() http.HandlerFunc { + var mu sync.Mutex + var cached *FeeEstimate + var cachedErr error + var refreshAt time.Time + estimate := func(ctx context.Context) (*FeeEstimate, error) { + mu.Lock() + defer mu.Unlock() + if now := time.Now(); !now.Before(refreshAt) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + defer cancel() + cached, cachedErr = s.FeeEstimate(ctx) + refreshAt = now.Add(30 * time.Second) + if cachedErr != nil { + refreshAt = now.Add(5 * time.Second) + } else if cached != nil && cached.ExpiresAt.Before(refreshAt) { + refreshAt = cached.ExpiresAt + } + } + return cached, cachedErr + } + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + fee, err := estimate(r.Context()) + if err != nil { + http.Error(w, "redemption fee estimate unavailable", http.StatusServiceUnavailable) + return + } + if fee == nil { + w.WriteHeader(http.StatusNoContent) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(feeEstimateResponse{Wei: fee.Wei.String(), ExpiresAt: fee.ExpiresAt.UTC()}) + } +} + +func (d *HTTPDestination) FeeEstimate(ctx context.Context) (*FeeEstimate, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.feeEndpoint, nil) + if err != nil { + return nil, err + } + res, err := d.client.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode == http.StatusNoContent { + return nil, nil + } + if res.StatusCode != http.StatusOK { + return nil, errors.New("redeemer fee estimate unavailable") + } + var body feeEstimateResponse + if err := decodeJSON(http.MaxBytesReader(nil, res.Body, 1024), &body); err != nil { + return nil, err + } + fee, ok := new(big.Int).SetString(body.Wei, 10) + if !ok || fee.Sign() <= 0 || fee.BitLen() > 256 || fee.String() != body.Wei || body.ExpiresAt.IsZero() { + return nil, errors.New("invalid redemption fee estimate") + } + return &FeeEstimate{Wei: fee, ExpiresAt: body.ExpiresAt}, nil +} diff --git a/redemption/fees_test.go b/redemption/fees_test.go new file mode 100644 index 0000000..b7c061a --- /dev/null +++ b/redemption/fees_test.go @@ -0,0 +1,146 @@ +package redemption + +import ( + "context" + "encoding/json" + "errors" + "math/big" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/stretchr/testify/require" +) + +type timedFeeReceipt func(context.Context, common.Hash) (*types.Receipt, time.Time, error) + +func (f timedFeeReceipt) FinalizedReceiptWithTime(ctx context.Context, hash common.Hash) (*types.Receipt, time.Time, error) { + return f(ctx, hash) +} + +func TestRedemptionFeeEstimate(t *testing.T) { + path := filepath.Join(t.TempDir(), "fees.sqlite") + store, err := OpenRedeemerDB(path) + require.NoError(t, err) + get := func(handler http.Handler) *httptest.ResponseRecorder { + response := httptest.NewRecorder() + handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/fee-estimate", nil)) + return response + } + now := time.Now().Truncate(time.Second) + older := now.Add(-feeWindow + 2*time.Minute) + empty := Handler(store) + require.Equal(t, http.StatusNoContent, get(empty).Code) + for i := int64(1); i <= 20; i++ { + hash := common.BigToHash(big.NewInt(i)) + receipt := &types.Receipt{Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(i)} + minedAt := now + if i == 1 { + minedAt = older + } + require.NoError(t, store.recordFee(t.Context(), hash, receipt, minedAt)) + require.NoError(t, store.recordFee(t.Context(), hash, receipt, now)) + } + require.Equal(t, http.StatusNoContent, get(empty).Code) + require.NoError(t, store.recordFee(t.Context(), common.Hash{2}, &types.Receipt{ + Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(1), + }, older.Add(-time.Minute))) + require.NoError(t, store.recordFee(t.Context(), common.Hash{1}, &types.Receipt{GasUsed: 10_000, EffectiveGasPrice: big.NewInt(500)}, now)) + require.NoError(t, store.Close()) + store, err = OpenRedeemerDB(path) + require.NoError(t, err) + defer store.Close() + handler := Handler(store) + client, disconnect := context.WithCancel(t.Context()) + disconnect() + response := httptest.NewRecorder() + handler.ServeHTTP(response, httptest.NewRequestWithContext(client, http.MethodGet, "/fee-estimate", nil)) + require.Equal(t, http.StatusOK, response.Code) + var estimate feeEstimateResponse + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &estimate)) + require.Equal(t, "1900", estimate.Wei) + require.True(t, estimate.ExpiresAt.Equal(older.Add(feeWindow))) + _, err = store.db.ExecContext(t.Context(), "UPDATE redemption_fee_samples SET block_time=?", now.Add(-feeWindow).Unix()) + require.NoError(t, err) + require.Equal(t, response.Body.String(), get(handler).Body.String()) + require.Equal(t, http.StatusNoContent, get(Handler(store)).Code) +} + +func TestFeeReceiptRemainsEligibleAfterFinalizedUse(t *testing.T) { + f := newRecoveryRPC(t) + store, ticket := f.store(t, 9) + chain := f.Chain(t) + prepared, err := chain.PrepareRedemption(t.Context(), recoveryKey(t), big.NewInt(1), redeemTicket(ticket)) + require.NoError(t, err) + require.NoError(t, store.RecordPrepared(t.Context(), ticket, prepared)) + finalized, err := chain.RedemptionSnapshot(t.Context(), "finalized") + require.NoError(t, err) + require.NoError(t, store.settle(t.Context(), ticket, "used", finalized)) + _, err = store.db.Exec("UPDATE redemption_fee_samples SET block_time=?", time.Now().Add(-time.Hour).Unix()) + require.NoError(t, err) + expired := common.Hash{1} + _, err = store.db.Exec("INSERT INTO redemption_fee_samples(hash,block_time) VALUES(?,?)", expired.Hex(), time.Now().Add(-feeWindow).Unix()) + require.NoError(t, err) + rpcErr := errors.New("receipt RPC unavailable") + require.ErrorIs(t, store.collectUsedFees(t.Context(), timedFeeReceipt(func(context.Context, common.Hash) (*types.Receipt, time.Time, error) { + return nil, time.Time{}, rpcErr + })), rpcErr) + count, err := store.WinningTicketCount(ticket.PayerAddress) + require.NoError(t, err) + require.Zero(t, count) + var nextAttempt int64 + require.NoError(t, store.db.QueryRow("SELECT next_attempt FROM redemption_fee_samples WHERE hash=?", prepared.Hash.Hex()).Scan(&nextAttempt)) + require.Greater(t, nextAttempt, time.Now().Add(5*time.Minute).Unix()) + require.NoError(t, store.db.QueryRow("SELECT count(*) FROM redemption_fee_samples WHERE hash=?", expired.Hex()).Scan(&count)) + require.Zero(t, count) + + _, err = store.db.Exec("UPDATE redemption_fee_samples SET next_attempt=0") + require.NoError(t, err) + minedAt := time.Now().Add(-time.Hour).Truncate(time.Second) + require.NoError(t, store.collectUsedFees(t.Context(), timedFeeReceipt(func(_ context.Context, hash common.Hash) (*types.Receipt, time.Time, error) { + require.Equal(t, prepared.Hash, hash) + return &types.Receipt{Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(4)}, minedAt, nil + }))) + var fee []byte + var blockTime int64 + require.NoError(t, store.db.QueryRow("SELECT fee,block_time FROM redemption_fee_samples WHERE hash=?", prepared.Hash.Hex()).Scan(&fee, &blockTime)) + require.Equal(t, int64(400), new(big.Int).SetBytes(fee).Int64()) + require.Equal(t, minedAt.Unix(), blockTime) +} + +func TestFeeWriteFailureDoesNotBlockReceiptSettlement(t *testing.T) { + for _, phase := range []string{"confirmed", "used"} { + t.Run(phase, func(t *testing.T) { + f := newRecoveryRPC(t) + store, ticket := f.store(t, 9) + chain := f.Chain(t) + prepared, err := chain.PrepareRedemption(t.Context(), recoveryKey(t), big.NewInt(1), redeemTicket(ticket)) + require.NoError(t, err) + require.NoError(t, store.RecordPrepared(t.Context(), ticket, prepared)) + finalized, err := chain.RedemptionSnapshot(t.Context(), "finalized") + require.NoError(t, err) + _, err = store.db.Exec(`CREATE TRIGGER disable_fee_writes BEFORE INSERT ON redemption_fee_samples + BEGIN SELECT RAISE(ABORT, 'test fee write failure'); END`) + require.NoError(t, err) + if phase == "used" { + require.NoError(t, store.settle(t.Context(), ticket, phase, finalized)) + } else { + receipt := &types.Receipt{ + Status: types.ReceiptStatusSuccessful, BlockNumber: finalized.Number, BlockHash: finalized.BlockHash, + GasUsed: 100, EffectiveGasPrice: big.NewInt(4), + } + require.NoError(t, store.confirmReceipt(t.Context(), ticket.Sig, prepared.Hash, receipt, time.Now())) + } + count, err := store.WinningTicketCount(ticket.PayerAddress) + require.NoError(t, err) + require.Zero(t, count) + var settledPhase string + require.NoError(t, store.db.QueryRow("SELECT phase FROM redemption_attempts WHERE sig=?", ticket.Sig).Scan(&settledPhase)) + require.Equal(t, phase, settledPhase) + }) + } +} diff --git a/redemption/http.go b/redemption/http.go index 021a82c..64d1dae 100644 --- a/redemption/http.go +++ b/redemption/http.go @@ -93,6 +93,7 @@ func Handler(s *RedeemerDB) http.Handler { // The ticket is nil if decoding fails. authorize must write any failure response. func HandlerWithAuthorization(s *RedeemerDB, authorize func(http.ResponseWriter, *http.Request, *TicketJSON) bool) http.Handler { mux := http.NewServeMux() + mux.HandleFunc("GET /fee-estimate", s.feeEstimateHandler()) slots := make(chan struct{}, 32) mux.HandleFunc("POST /tickets", func(w http.ResponseWriter, r *http.Request) { select { @@ -167,10 +168,11 @@ func (e *Rejection) Error() string { } type HTTPDestination struct { - endpoint string - client *http.Client - binding Binding - headers http.Header + endpoint string + feeEndpoint string + client *http.Client + binding Binding + headers http.Header } func NewHTTPDestination(u *url.URL, policy destination.Policy, b Binding, headers ...http.Header) (*HTTPDestination, error) { @@ -182,12 +184,16 @@ func NewHTTPDestination(u *url.URL, policy destination.Policy, b Binding, header if err != nil { return nil, err } + feeEndpoint, err := url.JoinPath(normalized.String(), "fee-estimate") + if err != nil { + return nil, err + } client := &http.Client{Transport: policy.Transport(15 * time.Second), Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} h := make(http.Header) if len(headers) > 0 && headers[0] != nil { h = headers[0].Clone() } - return &HTTPDestination{endpoint: endpoint, client: client, binding: b, headers: h}, nil + return &HTTPDestination{endpoint: endpoint, feeEndpoint: feeEndpoint, client: client, binding: b, headers: h}, nil } func (d *HTTPDestination) Close() { d.client.CloseIdleConnections() } diff --git a/redemption/migrations/006_fee_samples.sql b/redemption/migrations/006_fee_samples.sql new file mode 100644 index 0000000..fe27802 --- /dev/null +++ b/redemption/migrations/006_fee_samples.sql @@ -0,0 +1,8 @@ +-- UP +CREATE TABLE redemption_fee_samples ( + hash TEXT PRIMARY KEY, block_time INTEGER NOT NULL, fee BLOB, next_attempt INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX redemption_fee_samples_time ON redemption_fee_samples(block_time DESC,hash); +CREATE INDEX redemption_fee_samples_pending ON redemption_fee_samples(next_attempt,hash) WHERE fee IS NULL; +-- DOWN +DROP TABLE redemption_fee_samples; diff --git a/redemption/redeemer.go b/redemption/redeemer.go index edb261b..8c525e4 100644 --- a/redemption/redeemer.go +++ b/redemption/redeemer.go @@ -32,6 +32,28 @@ type ReceiptReader interface { FinalizedReceipt(context.Context, common.Hash) (*types.Receipt, error) } +type timedReceiptReader interface { + FinalizedReceiptWithTime(context.Context, common.Hash) (*types.Receipt, time.Time, error) +} + +func finalizedReceipt(ctx context.Context, chain ReceiptReader, hash common.Hash) (*types.Receipt, time.Time, error) { + if timed, ok := chain.(timedReceiptReader); ok { + return timed.FinalizedReceiptWithTime(ctx, hash) + } + receipt, err := chain.FinalizedReceipt(ctx, hash) + return receipt, time.Time{}, err +} + +func (s *RedeemerDB) confirmReceipt(ctx context.Context, sig []byte, hash common.Hash, receipt *types.Receipt, minedAt time.Time) error { + if err := s.finishTicket(ctx, sig, "confirmed", hash.Hex(), eth.ChainSnapshot{Number: receipt.BlockNumber, BlockHash: receipt.BlockHash}); err != nil { + return err + } + if err := s.recordFee(ctx, hash, receipt, minedAt); err != nil && s.logger != nil { + s.logger.Warn("redemption fee sample write failed", "event", "redemption_fee", "error", err) + } + return nil +} + // ReconcileSubmitted checks every retained identity, including old retry groups. // A finalized success wins over sibling failures; failed attempts alone cannot // release liability while another signed identity might still redeem the ticket. @@ -55,7 +77,7 @@ func ReconcileSubmitted(ctx context.Context, store *RedeemerDB, chain ReceiptRea } visited++ store.receiptCursor.after.Store(item.rowid) - receipt, err := chain.FinalizedReceipt(ctx, item.Hash) + receipt, minedAt, err := finalizedReceipt(ctx, chain, item.Hash) id := string(item.Signature) if err != nil { failures = append(failures, fmt.Errorf("receipt %s: %w", item.Hash.Hex(), err)) @@ -63,7 +85,7 @@ func ReconcileSubmitted(ctx context.Context, store *RedeemerDB, chain ReceiptRea } if receipt != nil && receipt.Status == types.ReceiptStatusSuccessful { successes[id] = true - err = store.finishTicket(ctx, item.Signature, "confirmed", item.Hash.Hex(), eth.ChainSnapshot{Number: receipt.BlockNumber, BlockHash: receipt.BlockHash}) + err = store.confirmReceipt(ctx, item.Signature, item.Hash, receipt, minedAt) } else if receipt != nil && receipt.Status == types.ReceiptStatusFailed { reverts[id] = item.Hash err = store.finishTicket(ctx, item.Signature, "reverted", item.Hash.Hex()) diff --git a/redemption/redeemer_db.go b/redemption/redeemer_db.go index a934606..e80d501 100644 --- a/redemption/redeemer_db.go +++ b/redemption/redeemer_db.go @@ -199,6 +199,16 @@ const receiptAdmissionQuery = `SELECT m.number,m.hash,EXISTS(SELECT 1 FROM winni // engine publishes replay guards or credit. Check exposure and liability in the // same transaction so redemption and concurrent receipts cannot race these gates. func (s *RedeemerDB) StoreWinningTickets(ctx context.Context, payer ethcommon.Address, randHash ethcommon.Hash, collateral *big.Int, tickets []*pm.SignedTicket, snapshot pm.ChainSnapshot) error { + return s.StoreFundedWinningTickets(ctx, payer, randHash, collateral, tickets, snapshot, nil) +} + +type ReceiptFunding struct { + Recipient ethcommon.Address + Reserve, FaceValue *big.Int +} + +// StoreFundedWinningTickets also checks the recipient's reserve when funding is present. +func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcommon.Address, randHash ethcommon.Hash, collateral *big.Int, tickets []*pm.SignedTicket, snapshot pm.ChainSnapshot, funding *ReceiptFunding) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err @@ -220,6 +230,21 @@ func (s *RedeemerDB) StoreWinningTickets(ctx context.Context, payer ethcommon.Ad if exposed != 0 { return ErrExposedRandomness } + if funding != nil { + pending, err := unsettledLiability(ctx, tx, payer, funding.Recipient) + if err != nil { + return err + } + if len(tickets) == 0 { + pending.Add(pending, funding.FaceValue) + } + for _, ticket := range tickets { + pending.Add(pending, ticket.FaceValue) + } + if pending.Cmp(funding.Reserve) > 0 { + return pm.ErrPayerUnavailable + } + } if len(tickets) > 0 { if err := s.capacity(ctx, tx, tickets[0].Recipient, len(tickets)); err != nil { return err diff --git a/redemption/redeemer_db_test.go b/redemption/redeemer_db_test.go index 5d54f20..0e491b0 100644 --- a/redemption/redeemer_db_test.go +++ b/redemption/redeemer_db_test.go @@ -187,10 +187,9 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { c, key := f.Chain(t), recoveryKey(t) files, err := fs.Sub(MigrationFiles, "migrations") require.NoError(t, err) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) + for range 5 { + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + } // Seed a genuine v1 database, then upgrade without changing its ticket identity. prepared, err := c.PrepareRedemption(t.Context(), key, big.NewInt(1), redeemTicket(ticket)) require.NoError(t, err) @@ -212,10 +211,9 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { require.NoError(t, s.db.QueryRow("SELECT phase FROM redemption_transactions WHERE hash=?", prepared.Hash.Hex()).Scan(&phase)) require.Equal(t, "submitted", phase) // A lossless rollback remains possible with the original representable state. - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) + for range 5 { + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + } require.NoError(t, migrations.Up(t.Context(), s.db, files)) _, err = s.db.Exec("UPDATE redemption_attempts SET phase='retryable' WHERE sig=?", ticket.Sig) require.NoError(t, err) @@ -223,9 +221,9 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { next.Hash = ethcommon.HexToHash("0xabcdef") next.Nonce = 1 require.NoError(t, s.RecordPrepared(t.Context(), ticket, next)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) + for range 4 { + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + } require.ErrorContains(t, migrations.Down(t.Context(), s.db, files), "cannot_downgrade_redemption_transaction_history") history, err = s.SubmittedRedemptions() require.NoError(t, err) @@ -253,9 +251,9 @@ func TestRedemptionRollbackPreservesTransactionProgress(t *testing.T) { require.EqualValues(t, 1, floor) files, err := fs.Sub(MigrationFiles, "migrations") require.NoError(t, err) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - require.NoError(t, migrations.Down(t.Context(), s.db, files)) + for range 4 { + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + } require.ErrorContains(t, migrations.Down(t.Context(), s.db, files), "cannot_downgrade_redemption_transaction_history") floor, err = s.SavedNonceFloor(t.Context(), key.Address()) require.NoError(t, err) @@ -263,3 +261,15 @@ func TestRedemptionRollbackPreservesTransactionProgress(t *testing.T) { }) } } + +func TestAdaptiveReserveChecksEveryWinningTicket(t *testing.T) { + f := newRecoveryRPC(t) + s, ticket := f.store(t, 9) + first, second := nextRecoveryTicket(ticket, 10), nextRecoveryTicket(ticket, 11) + reserve := new(big.Int).Mul(ticket.FaceValue, big.NewInt(2)) + collateral := new(big.Int).Mul(reserve, big.NewInt(10)) + funding := &ReceiptFunding{Recipient: ticket.Recipient, Reserve: reserve, FaceValue: ticket.FaceValue} + require.ErrorIs(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, first.RecipientRandHash, collateral, []*pm.SignedTicket{first, second}, f.CollateralSnapshot(), funding), pm.ErrPayerUnavailable) + require.NoError(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, first.RecipientRandHash, collateral, []*pm.SignedTicket{first}, f.CollateralSnapshot(), funding)) + require.ErrorIs(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, second.RecipientRandHash, collateral, nil, f.CollateralSnapshot(), funding), pm.ErrPayerUnavailable) +} diff --git a/redemption/redemption_store.go b/redemption/redemption_store.go index 1807904..fb6211c 100644 --- a/redemption/redemption_store.go +++ b/redemption/redemption_store.go @@ -335,6 +335,12 @@ func (s *RedeemerDB) finishTicket(ctx context.Context, sig []byte, phase string, return err } } + var feeHashes string + var feeErr error + if phase == "used" { + feeErr = tx.QueryRowContext(ctx, `SELECT json_group_array(hash) FROM redemption_transactions + WHERE sig=? AND phase NOT IN ('confirmed','reverted','superseded')`, sig).Scan(&feeHashes) + } if phase == "confirmed" || phase == "used" { if _, err := tx.ExecContext(ctx, "UPDATE ticket_state SET settled=1,settlement='used' WHERE hash=(SELECT ticket_hash FROM winning_tickets WHERE sig=?)", sig); err != nil { return err @@ -354,6 +360,15 @@ func (s *RedeemerDB) finishTicket(ctx context.Context, sig []byte, phase string, if err := commit(); err != nil { return err } + if phase == "used" { + if feeErr == nil && feeHashes != "[]" { + _, feeErr = s.db.ExecContext(ctx, `INSERT INTO redemption_fee_samples(hash,block_time) + SELECT value,? FROM json_each(?) WHERE true ON CONFLICT(hash) DO NOTHING`, time.Now().Unix(), feeHashes) + } + if feeErr != nil && s.logger != nil { + s.logger.Warn("redemption fee queue write failed", "event", "redemption_fee", "error", feeErr) + } + } if s.metrics != nil && observationErr == nil { if oldPhase != phase { s.observeTransition(phase, hash, nil) diff --git a/redemption/state.go b/redemption/state.go index d920f07..f560fe6 100644 --- a/redemption/state.go +++ b/redemption/state.go @@ -347,7 +347,23 @@ func (s *RedeemerDB) delivery(ctx context.Context, t *pm.SignedTicket, phase str } func (s *RedeemerDB) unsettledLiability(ctx context.Context, tx *sql.Tx, payer common.Address) (*big.Int, error) { - rows, err := tx.QueryContext(ctx, `SELECT w.face_value FROM ticket_state t JOIN winning_tickets w ON w.sig=t.sig WHERE w.payer_address=? AND w.redeemed_at IS NULL AND t.settled=0`, payer.Hex()) + return unsettledLiability(ctx, tx, payer, common.Address{}) +} + +func (s *RedeemerDB) RecipientLiability(ctx context.Context, payer, recipient common.Address) (*big.Int, error) { + return unsettledLiability(ctx, s.db, payer, recipient) +} + +func unsettledLiability(ctx context.Context, q interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +}, payer, recipient common.Address) (*big.Int, error) { + query := `SELECT w.face_value FROM ticket_state t JOIN winning_tickets w ON w.sig=t.sig WHERE w.payer_address=? AND w.redeemed_at IS NULL AND t.settled=0` + args := []any{payer.Hex()} + if recipient != (common.Address{}) { + query += " AND w.recipient=?" + args = append(args, recipient.Hex()) + } + rows, err := q.QueryContext(ctx, query, args...) if err != nil { return nil, err } diff --git a/redemption/worker.go b/redemption/worker.go index fb2fddd..0c6f830 100644 --- a/redemption/worker.go +++ b/redemption/worker.go @@ -61,6 +61,17 @@ func NewWorker(s *RedeemerDB, c eth.PaymentChain, d Destination) (*Worker, error return w, nil } +// CollectFees has a separate budget so a full redemption pass cannot starve fee sampling. +func (w *Worker) CollectFees(ctx context.Context) { + if _, local := w.destination.(*ChainDestination); local { + ctx, cancel := context.WithTimeout(eth.WithRPCWork(ctx, "background"), 5*time.Second) + defer cancel() + if err := w.store.collectUsedFees(ctx, w.chain); err != nil && w.store.logger != nil { + w.store.logger.Warn("redemption fee collection failed", "event", "redemption_fee", "error", err) + } + } +} + // Process performs a bounded, rotating pass. Inclusion recovery belongs to the // daemon lifetime; a slow payer cannot monopolize the next pass's starting point. func (w *Worker) Process(ctx context.Context) []error { diff --git a/signer/payment.go b/signer/payment.go index b7735a8..e527709 100644 --- a/signer/payment.go +++ b/signer/payment.go @@ -75,8 +75,8 @@ func (s *Service) preparePayment(ctx context.Context, paymentType, manifest stri seconds := int64(1) if paymentType == "live" { if oldSequence < 0 { - seconds = 10 - billableSecs = 10 + seconds = pm.InitialLivePaymentSeconds + billableSecs = pm.InitialLivePaymentSeconds } else { seconds = max(int64(math.Ceil(now.Sub(state.LastUpdate).Seconds())), 1) } diff --git a/signer/payment_test.go b/signer/payment_test.go index 10c8098..46164be 100644 --- a/signer/payment_test.go +++ b/signer/payment_test.go @@ -112,6 +112,138 @@ func (c collateralChain) PayerFunds(ctx context.Context, _, _ ethcommon.Address) return pm.PayerFunds{Snapshot: snapshot, Deposit: big.NewInt(10), Reserve: big.NewInt(10), WithdrawRound: c.withdraw}, err } +type adaptiveTestChain struct { + collateralChain + reserve int64 +} + +func (c *adaptiveTestChain) PayerFunds(ctx context.Context, payer, recipient ethcommon.Address) (pm.PayerFunds, error) { + funds, err := c.collateralChain.PayerFunds(ctx, payer, recipient) + funds.Deposit, funds.Reserve = big.NewInt(1e18), big.NewInt(c.reserve) + return funds, err +} + +func TestAdaptiveQuotesWithSigner(t *testing.T) { + key, _, _ := testSignerKey(t) + store, err := orchestrator.OpenRedeemerDB(filepath.Join(t.TempDir(), "adaptive.sqlite")) + require.NoError(t, err) + defer store.Close() + const baseline = 1_053_105_365_065_039 + chain := &adaptiveTestChain{collateralChain{new(big.Int)}, 1e18} + policy := pm.PayerPolicy{MaxTicketEV: big.NewRat(3e13, 1), MaxBatchEV: big.NewRat(3e15, 1), DepositMultiplier: 1} + engine, err := orchestrator.NewAdaptivePaymentEngine(store, chain, ethcommon.HexToAddress("0x1234"), big.NewInt(baseline), orchestrator.TicketSizing{PayerPolicy: policy, MeteredTicketSeconds: 3}) + require.NoError(t, err) + s := newService(key) + s.SetPaymentChain(chain) + s.payerPolicy = policy + now := time.Now() + quote := func(session, unit string, price int64) wire.OrchestratorInfo { + t.Helper() + _, err := engine.MakeChallenge(t.Context(), "runner", session, key.Address(), price, unit, "https://orch.example") + require.NoError(t, err) + info, err := engine.ChallengeInfo(session) + require.NoError(t, err) + return info + } + receive := func(draft draftPayment) error { + t.Helper() + payment, err := draft.Sign(t.Context(), key, nil) + require.NoError(t, err) + _, _, err = engine.Receive(t.Context(), "runner", string(draft.segment.ManifestID), payment.Payment, payment.SegCreds) + return err + } + for _, q := range []struct { + app string + price int64 + tickets int + }{ + {"ffmpeg", 1_426_507_434_855, 1}, + {"kling", 201_304_703_112_642, 7}, + {"ltx", 359_472_684_129_717, 12}, + {"seedance", 528_436_228_972_348, 18}, + } { + info := quote(q.app, "fixed", q.price) + draft, err := s.preparePayment(t.Context(), "fixed", q.app, info, paymentState{}, -1, now) + require.NoError(t, err) + require.Equal(t, q.tickets, draft.Usage.NumTickets) + require.NoError(t, receive(draft)) + require.NoError(t, engine.Charge(t.Context(), q.app, now)) + balance, err := engine.Balance(q.app) + require.NoError(t, err) + require.GreaterOrEqual(t, balance.Sign(), 0) + require.Less(t, balance.Cmp(big.NewRat(1, 1)), 0) + } + _, err = engine.MakeChallenge(t.Context(), "runner", "over", key.Address(), 3e15+1, "fixed", "https://orch.example") + require.ErrorContains(t, err, "within ticket EV and funding limits") + + liveRecipient := ethcommon.HexToAddress("0x9876") + engine, err = orchestrator.NewAdaptivePaymentEngine(store, chain, liveRecipient, big.NewInt(baseline), orchestrator.TicketSizing{PayerPolicy: policy, MeteredTicketSeconds: 3}) + require.NoError(t, err) + live := quote("live", "seconds", 1e9) + cheaper := quote("cheaper", "seconds", 1e8) + require.Equal(t, live.TicketParams.FaceValue, cheaper.TicketParams.FaceValue) + require.Less(t, new(big.Int).SetBytes(cheaper.TicketParams.WinProb).Cmp(new(big.Int).SetBytes(live.TicketParams.WinProb)), 0) + open, err := s.preparePayment(t.Context(), "live", "live", live, paymentState{}, -1, now) + require.NoError(t, err) + require.Equal(t, 4, open.Usage.NumTickets) + chain.reserve = baseline - 1 + require.ErrorIs(t, receive(open), pm.ErrPayerUnavailable) + chain.reserve = 1e16 + require.NoError(t, receive(open)) + require.NoError(t, engine.Charge(t.Context(), "live", now)) + for elapsed, count := range map[time.Duration]int{ + 3 * time.Second: 1, 6 * time.Second: 2, 300 * time.Second: 100, + } { + draft, err := s.preparePayment(t.Context(), "live", "live", live, open.State, 0, now.Add(elapsed)) + require.NoError(t, err) + require.Equal(t, count, draft.Usage.NumTickets) + } + _, err = s.preparePayment(t.Context(), "live", "live", live, open.State, 0, now.Add(303*time.Second)) + require.Error(t, err) + pending, err := store.RecipientLiability(t.Context(), key.Address(), liveRecipient) + require.NoError(t, err) + chain.reserve = baseline/2 + pending.Int64() + _, err = engine.RefreshChallenge(t.Context(), "live", key.Address(), "https://orch.example") + require.NoError(t, err) + refreshed, err := engine.ChallengeInfo("live") + require.NoError(t, err) + require.Equal(t, int64(baseline/2)/int64(open.Usage.NumTickets), new(big.Int).SetBytes(refreshed.TicketParams.FaceValue).Int64()) + draft, err := s.preparePayment(t.Context(), "live", "live", refreshed, open.State, 0, now.Add(5*time.Second)) + require.NoError(t, err) + require.Equal(t, 1, draft.Usage.NumTickets, "the carried two seconds of credit pay part of the top-up") + require.NoError(t, receive(draft)) + require.NoError(t, engine.Charge(t.Context(), "live", now.Add(15*time.Second))) + + chain.reserve = 1e18 + for _, tc := range []struct { + session string + duration int64 + opening int + topUps [2]int + }{{"three", 3, 4, [2]int{1, 2}}, {"five", 5, 2, [2]int{1, 2}}, {"ten", 10, 1, [2]int{1, 1}}} { + engine, err = orchestrator.NewAdaptivePaymentEngine(store, chain, liveRecipient, big.NewInt(baseline), orchestrator.TicketSizing{PayerPolicy: policy, MeteredTicketSeconds: tc.duration}) + require.NoError(t, err) + info := quote(tc.session, "seconds", 1e9) + draft, err := s.preparePayment(t.Context(), "live", tc.session, info, paymentState{}, -1, now) + require.NoError(t, err) + require.Equal(t, tc.opening, draft.Usage.NumTickets) + require.NoError(t, receive(draft)) + require.NoError(t, engine.Charge(t.Context(), tc.session, now)) + state := draft.State + for i, elapsed := range []time.Duration{3200 * time.Millisecond, 9800 * time.Millisecond} { + at := now.Add(elapsed) + require.NoError(t, engine.Charge(t.Context(), tc.session, at)) + next, err := s.preparePayment(t.Context(), "live", tc.session, info, state, int64(state.SequenceNumber), at) + require.NoError(t, err) + require.Equal(t, tc.topUps[i], next.Usage.NumTickets, "cadence %ds at %s", tc.duration, elapsed) + require.NoError(t, receive(next)) + state = next.State + } + require.NoError(t, engine.Charge(t.Context(), tc.session, now.Add(20*time.Second))) + require.ErrorIs(t, engine.Charge(t.Context(), tc.session, now.Add(35*time.Second)), orchestrator.ErrInsufficientBalance) + } +} + func TestRecipientReservesWinningLiabilityAcrossConcurrentSessions(t *testing.T) { key, _, _ := testSignerKey(t) store, err := orchestrator.OpenRedeemerDB(filepath.Join(t.TempDir(), "recipient.sqlite")) From 3a727e0e6c124f47bce144727d1b1512cd3b11a8 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:02:43 -0800 Subject: [PATCH 2/8] Use a configured baseline for ticket face value Base the Arbitrum example on finalized redemption costs. Remove fee sampling and the public estimate route while retaining quote-based EV and payer funding checks. --- configs/orchestrator/config.example.toml | 5 +- docs/http-api.md | 6 - docs/metrics.md | 1 - docs/orchestrator.md | 15 +- docs/payment-recovery.md | 7 - eth/payment.go | 24 +-- orchestrator/app.go | 21 +-- orchestrator/payment_engine.go | 3 - orchestrator/ticket_sizing.go | 18 +- orchestrator/ticket_sizing_test.go | 39 +++-- redeemer/app.go | 1 - redemption/fees.go | 192 ---------------------- redemption/fees_test.go | 146 ---------------- redemption/http.go | 16 +- redemption/http_test.go | 3 + redemption/migrations/006_fee_samples.sql | 8 - redemption/redeemer.go | 26 +-- redemption/redeemer_db_test.go | 26 +-- redemption/redemption_store.go | 15 -- redemption/worker.go | 11 -- 20 files changed, 66 insertions(+), 517 deletions(-) delete mode 100644 redemption/fees.go delete mode 100644 redemption/fees_test.go delete mode 100644 redemption/migrations/006_fee_samples.sql diff --git a/configs/orchestrator/config.example.toml b/configs/orchestrator/config.example.toml index 4ef932f..c192ec8 100644 --- a/configs/orchestrator/config.example.toml +++ b/configs/orchestrator/config.example.toml @@ -43,8 +43,9 @@ HealthGrants = [] # WeiPerUSD = "1000000000000000" # ETHUSDFeed = "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612" # Arbitrum default. # PriceMaxAge = "2h" -# Baseline payout for a winning ticket, in wei. -# TicketFaceValue = "1000000000000000" +# Budget 1.2e13 wei for an Arbitrum redemption. A 0.5% gas target gives this +# baseline payout, in wei. +# TicketFaceValue = "2400000000000000" # MaxTicketEV = "3000000000000" # MaxBatchEV = "20000000000000" # MeteredTicketSeconds = 3 diff --git a/docs/http-api.md b/docs/http-api.md index 15bdb3e..1e7657f 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -246,12 +246,6 @@ example `"X-List: a,b",Authorization: Bearer credential`. ## Redeemer HTTP -`GET /fee-estimate` requires no ticket submission credential. It returns -`fee_wei` (a decimal string) and `expires_at` (RFC 3339) for the 95th percentile -of successful, finalized redemption fees. It returns `204` when fewer than 20 -samples are available in the last 24 hours. Do not use an estimate after its -expiry. - `POST /tickets` submits one winning ticket to a standalone redeemer. Send a JSON object with `chain_id` (a decimal string), `controller` (an Ethereum address), and `ticket`. The chain and Controller must match the redeemer's configuration. diff --git a/docs/metrics.md b/docs/metrics.md index 1277ab7..945f9af 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -83,7 +83,6 @@ gauges; timestamps use Unix seconds. Most event families appear on first use. | Lifecycle | `runner_events_total{event}`, `runner_health_checks_total{outcome}`, `session_reservations_total{outcome}`, `session_ends_total{reason}`, `session_duration_seconds`, with app identity. Reservations include allocations pending payment; only activated sessions contribute lifetime observations. | | Streams | `trickle_channels{kind="control\|session"}`, `trickle_buffered_bytes` for retained published segment bytes; `stream_transfer_bytes_total{app,app_id,runner_id,mode,protocol,direction}`, `stream_errors_total{app,app_id,runner_id,mode,protocol,outcome}`. Trickle requests are transport activity, not extra app invocations. | | Payments | `payment_operations_total{operation,outcome}` for challenge/receive/refresh/charge; `payment_operation_duration_seconds{operation}` for challenge/receive/refresh; `payment_tickets_total{kind="accepted\|winning"}`, `payment_credit_eth_total`, `payment_charge_eth_total`, `payment_billed_seconds_total`, `payment_fixed_charges_total`, with app identity. Credit is accepted expected ticket value; charges are successfully debited service usage. | -| Ticket sizing | `payment_gas_target_unmet_total` counts quotes whose funded face value is below the gas target. `payment_fee_estimate_errors_total` counts failed estimate polls. Both are aggregate counters. | | Signer | `signer_payments_total{type,outcome}`, `signer_payment_duration_seconds{type}`, `signer_tickets_total{type}`, `signer_sign_operations_total{kind,outcome}`. Signing kinds are ticket, segment, state, and orchestrator_info. Partial signing before a failed request remains visible. Successful payment/ticket totals follow required outbox persistence, even if response delivery is interrupted. | | Authorization | `signer_auth_webhook_requests_total{status,outcome}`, `signer_auth_webhook_duration_seconds`, `signer_auth_cache_hits_total`. Status zero means no webhook response; outcomes distinguish success, denied, and error. | | Redeemer authorization | `redeemer_auth_webhook_requests_total{status,outcome}`, `redeemer_auth_webhook_duration_seconds`. Status is the upstream HTTP status, or zero without a response; outcomes are `success`, `denied`, and `error`. | diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 67be04c..23932aa 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -141,19 +141,18 @@ Incomplete paid configuration fails startup. The orchestrator address must be ac on the configured chain. Runner prices use USD per hour for live work or USD per fixed request. Hourly discovery prices are normalized to USD and wei per second. -Node sizes tickets when it issues or refreshes paid session parameters. Face -value is limited by the payer's deposit divided by `PayerDepositMultiplier` -(default 1) and by recipient-claimable reserve after locally known unsettled wins. +Node sizes tickets when it issues or refreshes paid session parameters. It +starts from `TicketFaceValue` and caps the payout by the payer's deposit divided +by `PayerDepositMultiplier` (default 1) and by the recipient's claimable reserve +after locally known unsettled wins. Available reserve must cover every ticket winning in a fixed-price quote or a metered session's ten-second opening batch. Node checks funding again when it receives tickets. Later metered top-ups may have more tickets than the opening batch. -Node aims to keep redemption gas costs at 0.5% of face value, using the 95th -percentile of recent finalized redemption fees. Node continues to quote if -funding limits prevent it from meeting that target. When the estimate is -missing or stale, Node uses the funded baseline. Arbitrum fees include the L1 -posting charge. +Set `TicketFaceValue` high enough to cover typical redemption costs on your +chain. The example config uses `2400000000000000` wei (0.0024 ETH), based on +a fixed Arbitrum redemption cost estimate of 0.000012 ETH and a 0.5% gas target. Fixed-price quotes use the fewest tickets that cover the price, up to 100. Metered tickets target `MeteredTicketSeconds` seconds of quoted usage (default diff --git a/docs/payment-recovery.md b/docs/payment-recovery.md index ea09e31..86bfe3b 100644 --- a/docs/payment-recovery.md +++ b/docs/payment-recovery.md @@ -71,13 +71,6 @@ data, including payment/accounting tables in the initial migrations. If downgrad is incompatible, retain the latest state for a compatible fix; restoring an old snapshot can lose events, winners, and transaction identities. -To roll back `006_fee_samples.sql`, stop each orchestrator and standalone -redeemer writer and back up its database. Use the newer binary's `migrate status` -to confirm migration 006 is the latest applied migration, then run `migrate down` -once with that binary and database path. This removes only fee sample history. -Restore the previous image and its matching configuration, and check migration -status with the previous binary before starting it. - ## Signer accounting recovery Keep `Kafka.OutboxDB` on persistent local storage, one file per replica. It uses diff --git a/eth/payment.go b/eth/payment.go index 280a856..bbd64ab 100644 --- a/eth/payment.go +++ b/eth/payment.go @@ -68,39 +68,31 @@ func (c PaymentChain) activeAt(ctx context.Context, address, recipient ethcommon // FinalizedReceipt retains canonical inclusion evidence for durable collateral admission. func (c PaymentChain) FinalizedReceipt(ctx context.Context, hash ethcommon.Hash) (*types.Receipt, error) { - receipt, _, err := c.FinalizedReceiptWithTime(ctx, hash) - return receipt, err -} - -func (c PaymentChain) FinalizedReceiptWithTime(ctx context.Context, hash ethcommon.Hash) (*types.Receipt, time.Time, error) { receipt, err := c.Contracts.RPC.TransactionReceipt(ctx, hash) if errors.Is(err, ethereum.NotFound) { - return nil, time.Time{}, nil + return nil, nil } if err != nil { - return nil, time.Time{}, err + return nil, err } finalized, err := c.Contracts.RPC.header(ctx, "finalized") if err != nil { - return nil, time.Time{}, err + return nil, err } if finalized.Number == nil { - return nil, time.Time{}, errors.New("invalid finalized header") + return nil, errors.New("invalid finalized header") } if (*big.Int)(finalized.Number).Cmp(receipt.BlockNumber) < 0 { - return nil, time.Time{}, nil + return nil, nil } canonical, err := c.Contracts.RPC.header(ctx, hexutil.EncodeBig(receipt.BlockNumber)) if err != nil { - return nil, time.Time{}, err + return nil, err } if canonical.Hash != receipt.BlockHash { - return nil, time.Time{}, nil - } - if canonical.Timestamp == nil { - return receipt, time.Time{}, nil + return nil, nil } - return receipt, time.Unix(int64(*canonical.Timestamp), 0), nil + return receipt, nil } // Address retention adapts livepeer/go-livepeer eth/client.go setContracts at diff --git a/orchestrator/app.go b/orchestrator/app.go index 832af3d..8d72f6b 100644 --- a/orchestrator/app.go +++ b/orchestrator/app.go @@ -512,7 +512,6 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { metricsMux.Handle("GET /metrics", registry.metrics.Handler()) ctx, cancel := signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM) defer cancel() - var readFeeEstimate func(context.Context) (*redemption.FeeEstimate, error) if engine != nil { var target redemption.Destination if p.RedeemerURL != nil { @@ -530,14 +529,12 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { } defer remote.Close() target = remote - readFeeEstimate = remote.FeeEstimate } else { local, e := redemption.NewChainDestination(eth.WithRPCWork(ctx, "background"), redeemerDB.RedeemerDB, paymentChain, redeemerKey, paymentChainID, redemption.RedemptionOptions{Timeout: p.RedeemerTxTimeout, MaxReplacements: p.RedeemerMaxTxReplacements}) if e != nil { return e } target = local - readFeeEstimate = redeemerDB.FeeEstimate } redemptionWorker, err = redemption.NewWorker(redeemerDB.RedeemerDB, paymentChain, target) if err != nil { @@ -574,19 +571,6 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { workers.Go(func() { app.runO2RKeepalives(ctx, 10*time.Second) }) if engine != nil { workers.Go(func() { observedChain.Observer.Run(ctx) }) - startWorker(time.Minute, 5*time.Second, func(ctx context.Context) { - fee, err := readFeeEstimate(ctx) - if err != nil { - registry.metrics.Add("payment_fee_estimate_errors_total", 1, nil) - return - } - if fee != nil { - if limit := time.Now().Add(5 * time.Minute); fee.ExpiresAt.After(limit) { - fee.ExpiresAt = limit - } - } - engine.redemptionFee.Store(fee) - }) startWorker(p.HeartbeatInterval, 30*time.Second, func(ctx context.Context) { readiness.check(ctx, redeemerDB, observedChain, engine, registry.metrics, logger) }) @@ -608,9 +592,8 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { logger.Error("payment retention", "event", "payment_retention", "operation", "prune", "outcome", "error", "error_kind", observability.ErrorKind(err)) } }) - startWorker(p.HeartbeatInterval, 30*time.Second, func(passCtx context.Context) { - failures := redemptionWorker.Process(passCtx) - redemptionWorker.CollectFees(ctx) + startWorker(p.HeartbeatInterval, 30*time.Second, func(ctx context.Context) { + failures := redemptionWorker.Process(ctx) for _, err := range failures { registry.metrics.Add("redemption_errors_total", 1, observability.Labels{"error_kind": observability.ErrorKind(err)}) logger.Error("redemption failed", "event", "redemption_pass", "operation", "redeem", "outcome", "error", "error_kind", observability.ErrorKind(err)) diff --git a/orchestrator/payment_engine.go b/orchestrator/payment_engine.go index 2aede1e..3a6972e 100644 --- a/orchestrator/payment_engine.go +++ b/orchestrator/payment_engine.go @@ -11,7 +11,6 @@ import ( "math/big" "strconv" "sync" - "sync/atomic" "time" ethcommon "github.com/ethereum/go-ethereum/common" @@ -37,8 +36,6 @@ type PaymentEngine struct { faceValue *big.Int winProb *big.Int sizing *TicketSizing - redemptionFee atomic.Pointer[redemption.FeeEstimate] - gasWarningAt atomic.Int64 secret [32]byte authSecret [32]byte sessions map[string]*paymentSession diff --git a/orchestrator/ticket_sizing.go b/orchestrator/ticket_sizing.go index 733035c..435efe7 100644 --- a/orchestrator/ticket_sizing.go +++ b/orchestrator/ticket_sizing.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "math/big" - "time" "github.com/ethereum/go-ethereum/common" "github.com/livepeer/node/pm" @@ -64,22 +63,7 @@ func (e *PaymentEngine) quoteTicket(ctx context.Context, payer common.Address, p if deposit.Sign() <= 0 { return pm.ChainSnapshot{}, nil, nil, pm.ErrPayerUnavailable } - now := time.Now() - desiredFace := e.faceValue - var gasTarget *big.Int - if estimate := e.redemptionFee.Load(); estimate != nil && now.Before(estimate.ExpiresAt) { - gasTarget = new(big.Int).Mul(estimate.Wei, big.NewInt(200)) - if gasTarget.Cmp(desiredFace) > 0 { - desiredFace = minBigInt(gasTarget, maxWinProb) - } - } - face, odds, err := e.sizing.ticketTerms(minBigInt(desiredFace, deposit), reserve, price, unit) - if err == nil && gasTarget != nil && face.Cmp(gasTarget) < 0 { - e.metrics.Add("payment_gas_target_unmet_total", 1, nil) - if last := e.gasWarningAt.Load(); e.store.logger != nil && now.Unix()-last >= 60 && e.gasWarningAt.CompareAndSwap(last, now.Unix()) { - e.store.logger.Warn("payment face value below redemption gas target", "event", "payment_challenge", "face_value", face, "target_face_value", gasTarget) - } - } + face, odds, err := e.sizing.ticketTerms(minBigInt(e.faceValue, deposit), reserve, price, unit) return funds.Snapshot, face, odds, err } diff --git a/orchestrator/ticket_sizing_test.go b/orchestrator/ticket_sizing_test.go index d778352..f0c4939 100644 --- a/orchestrator/ticket_sizing_test.go +++ b/orchestrator/ticket_sizing_test.go @@ -5,36 +5,39 @@ import ( "math/big" "path/filepath" "testing" - "time" "github.com/ethereum/go-ethereum/common" "github.com/livepeer/node/pm" - "github.com/livepeer/node/redemption" "github.com/stretchr/testify/require" ) -func TestAdaptiveFaceValue(t *testing.T) { +func TestQuoteFaceValueCaps(t *testing.T) { store, err := OpenRedeemerDB(filepath.Join(t.TempDir(), "tickets.sqlite")) require.NoError(t, err) defer store.Close() chain := &recipientTestChain{active: true, block: 50} - engine, err := NewAdaptivePaymentEngine(store, chain, common.HexToAddress("0x1234"), big.NewInt(1000), TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3}) + policy := pm.DefaultPayerPolicy() + policy.DepositMultiplier = 2 + engine, err := NewAdaptivePaymentEngine(store, chain, common.HexToAddress("0x1234"), big.NewInt(1000), TicketSizing{PayerPolicy: policy, MeteredTicketSeconds: 3}) require.NoError(t, err) - now := time.Now() - chain.funds = func(_ context.Context, funds pm.PayerFunds) (pm.PayerFunds, error) { - funds.Deposit, funds.Reserve = big.NewInt(6000), big.NewInt(5000) - return funds, nil - } - face := func() int64 { - _, face, _, err := engine.quoteTicket(t.Context(), common.HexToAddress("0x5678"), 10, "fixed") - require.NoError(t, err) - return face.Int64() + for _, tt := range []struct { + name string + deposit, reserve, face int64 + }{ + {"baseline", 6000, 5000, 1000}, + {"deposit multiplier", 1600, 5000, 800}, + {"claimable reserve", 6000, 700, 700}, + } { + t.Run(tt.name, func(t *testing.T) { + chain.funds = func(_ context.Context, funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.Deposit, funds.Reserve = big.NewInt(tt.deposit), big.NewInt(tt.reserve) + return funds, nil + } + _, face, _, err := engine.quoteTicket(t.Context(), common.HexToAddress("0x5678"), 10, "fixed") + require.NoError(t, err) + require.Equal(t, big.NewInt(tt.face), face) + }) } - require.EqualValues(t, 1000, face()) - engine.redemptionFee.Store(&redemption.FeeEstimate{Wei: big.NewInt(30), ExpiresAt: now.Add(time.Minute)}) - require.EqualValues(t, 5000, face()) - engine.redemptionFee.Store(&redemption.FeeEstimate{Wei: big.NewInt(30), ExpiresAt: now}) - require.EqualValues(t, 1000, face()) } func TestQuotedBatchFitsAvailableReserve(t *testing.T) { diff --git a/redeemer/app.go b/redeemer/app.go index 56c7ce4..6eafe63 100644 --- a/redeemer/app.go +++ b/redeemer/app.go @@ -243,7 +243,6 @@ func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { logger.Error("redemption pass failed", "event", "redemption_pass", "error_kind", observability.ErrorKind(err)) } done() - worker.CollectFees(ctx) // Exhausting a processing batch is healthy progress. Probe the // dependencies with their own budget rather than its expired context. tick, done = context.WithTimeout(eth.WithRPCWork(ctx, "background"), 15*time.Second) diff --git a/redemption/fees.go b/redemption/fees.go deleted file mode 100644 index 3029e6b..0000000 --- a/redemption/fees.go +++ /dev/null @@ -1,192 +0,0 @@ -package redemption - -import ( - "context" - "encoding/json" - "errors" - "math/big" - "net/http" - "slices" - "sync" - "time" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" -) - -const ( - feeWindow = 24 * time.Hour - maxFeeSamples = 2048 - minFeeSamples = 20 -) - -func (s *RedeemerDB) recordFee(ctx context.Context, hash common.Hash, receipt *types.Receipt, minedAt time.Time) error { - cutoff := time.Now().Add(-feeWindow) - if receipt.Status != types.ReceiptStatusSuccessful || receipt.GasUsed == 0 || - receipt.EffectiveGasPrice == nil || receipt.EffectiveGasPrice.Sign() <= 0 || !minedAt.After(cutoff) { - return nil - } - // Arbitrum charges for posting to L1 in the receipt's gas units. - wei := new(big.Int).Mul(new(big.Int).SetUint64(receipt.GasUsed), receipt.EffectiveGasPrice) - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer tx.Rollback() - if _, err := tx.ExecContext(ctx, `INSERT INTO redemption_fee_samples(hash,block_time,fee) VALUES(?,?,?) - ON CONFLICT(hash) DO UPDATE SET block_time=excluded.block_time,fee=excluded.fee WHERE fee IS NULL`, hash.Hex(), minedAt.Unix(), wei.Bytes()); err != nil { - return err - } - _, err = tx.ExecContext(ctx, `DELETE FROM redemption_fee_samples WHERE block_time<=? OR hash IN - (SELECT hash FROM redemption_fee_samples WHERE fee IS NOT NULL ORDER BY block_time DESC,hash LIMIT -1 OFFSET ?)`, cutoff.Unix(), maxFeeSamples) - if err != nil { - return err - } - return tx.Commit() -} - -func (s *RedeemerDB) collectUsedFees(ctx context.Context, chain timedReceiptReader) error { - now := time.Now() - if _, err := s.db.ExecContext(ctx, "DELETE FROM redemption_fee_samples WHERE block_time<=?", now.Add(-feeWindow).Unix()); err != nil { - return err - } - rows, err := s.db.QueryContext(ctx, `SELECT hash FROM redemption_fee_samples - WHERE fee IS NULL AND block_time>? AND next_attempt<=? ORDER BY next_attempt,hash LIMIT 32`, now.Add(-feeWindow).Unix(), now.Unix()) - if err != nil { - return err - } - var hashes []string - for rows.Next() { - var hash string - if err := rows.Scan(&hash); err != nil { - rows.Close() - return err - } - hashes = append(hashes, hash) - } - rows.Close() - if err := rows.Err(); err != nil { - return err - } - var result error - for _, hash := range hashes { - // Slow down repeated misses as an attempt ages, up to an hour. - if _, err := s.db.ExecContext(ctx, `UPDATE redemption_fee_samples - SET next_attempt=?1+min(3600,60+max(0,?1-block_time)/4) WHERE hash=?2`, time.Now().Unix(), hash); err != nil { - return errors.Join(result, err) - } - receipt, minedAt, err := chain.FinalizedReceiptWithTime(ctx, common.HexToHash(hash)) - if err == nil && receipt != nil { - err = s.recordFee(ctx, common.HexToHash(hash), receipt, minedAt) - } - if err == nil && receipt != nil { - _, err = s.db.ExecContext(ctx, "DELETE FROM redemption_fee_samples WHERE hash=? AND fee IS NULL", hash) - } - result = errors.Join(result, err) - } - return result -} - -type FeeEstimate struct { - Wei *big.Int - ExpiresAt time.Time -} - -func (s *RedeemerDB) FeeEstimate(ctx context.Context) (*FeeEstimate, error) { - now := time.Now() - rows, err := s.db.QueryContext(ctx, "SELECT block_time,fee FROM redemption_fee_samples WHERE fee IS NOT NULL AND block_time>? ORDER BY block_time DESC", now.Add(-feeWindow).Unix()) - if err != nil { - return nil, err - } - defer rows.Close() - var costs []*big.Int - expiresAt := now.Add(5 * time.Minute) - for rows.Next() { - var fee []byte - var blockTime int64 - if err := rows.Scan(&blockTime, &fee); err != nil { - return nil, err - } - costs = append(costs, new(big.Int).SetBytes(fee)) - if cutoff := time.Unix(blockTime, 0).Add(feeWindow); len(costs) == minFeeSamples && cutoff.Before(expiresAt) { - expiresAt = cutoff - } - } - if err := rows.Err(); err != nil { - return nil, err - } - if len(costs) < minFeeSamples { - return nil, nil - } - slices.SortFunc(costs, (*big.Int).Cmp) - return &FeeEstimate{Wei: costs[(95*len(costs)+99)/100-1], ExpiresAt: expiresAt}, nil -} - -type feeEstimateResponse struct { - Wei string `json:"fee_wei"` - ExpiresAt time.Time `json:"expires_at"` -} - -func (s *RedeemerDB) feeEstimateHandler() http.HandlerFunc { - var mu sync.Mutex - var cached *FeeEstimate - var cachedErr error - var refreshAt time.Time - estimate := func(ctx context.Context) (*FeeEstimate, error) { - mu.Lock() - defer mu.Unlock() - if now := time.Now(); !now.Before(refreshAt) { - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) - defer cancel() - cached, cachedErr = s.FeeEstimate(ctx) - refreshAt = now.Add(30 * time.Second) - if cachedErr != nil { - refreshAt = now.Add(5 * time.Second) - } else if cached != nil && cached.ExpiresAt.Before(refreshAt) { - refreshAt = cached.ExpiresAt - } - } - return cached, cachedErr - } - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - fee, err := estimate(r.Context()) - if err != nil { - http.Error(w, "redemption fee estimate unavailable", http.StatusServiceUnavailable) - return - } - if fee == nil { - w.WriteHeader(http.StatusNoContent) - return - } - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(feeEstimateResponse{Wei: fee.Wei.String(), ExpiresAt: fee.ExpiresAt.UTC()}) - } -} - -func (d *HTTPDestination) FeeEstimate(ctx context.Context) (*FeeEstimate, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.feeEndpoint, nil) - if err != nil { - return nil, err - } - res, err := d.client.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode == http.StatusNoContent { - return nil, nil - } - if res.StatusCode != http.StatusOK { - return nil, errors.New("redeemer fee estimate unavailable") - } - var body feeEstimateResponse - if err := decodeJSON(http.MaxBytesReader(nil, res.Body, 1024), &body); err != nil { - return nil, err - } - fee, ok := new(big.Int).SetString(body.Wei, 10) - if !ok || fee.Sign() <= 0 || fee.BitLen() > 256 || fee.String() != body.Wei || body.ExpiresAt.IsZero() { - return nil, errors.New("invalid redemption fee estimate") - } - return &FeeEstimate{Wei: fee, ExpiresAt: body.ExpiresAt}, nil -} diff --git a/redemption/fees_test.go b/redemption/fees_test.go deleted file mode 100644 index b7c061a..0000000 --- a/redemption/fees_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package redemption - -import ( - "context" - "encoding/json" - "errors" - "math/big" - "net/http" - "net/http/httptest" - "path/filepath" - "testing" - "time" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/stretchr/testify/require" -) - -type timedFeeReceipt func(context.Context, common.Hash) (*types.Receipt, time.Time, error) - -func (f timedFeeReceipt) FinalizedReceiptWithTime(ctx context.Context, hash common.Hash) (*types.Receipt, time.Time, error) { - return f(ctx, hash) -} - -func TestRedemptionFeeEstimate(t *testing.T) { - path := filepath.Join(t.TempDir(), "fees.sqlite") - store, err := OpenRedeemerDB(path) - require.NoError(t, err) - get := func(handler http.Handler) *httptest.ResponseRecorder { - response := httptest.NewRecorder() - handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/fee-estimate", nil)) - return response - } - now := time.Now().Truncate(time.Second) - older := now.Add(-feeWindow + 2*time.Minute) - empty := Handler(store) - require.Equal(t, http.StatusNoContent, get(empty).Code) - for i := int64(1); i <= 20; i++ { - hash := common.BigToHash(big.NewInt(i)) - receipt := &types.Receipt{Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(i)} - minedAt := now - if i == 1 { - minedAt = older - } - require.NoError(t, store.recordFee(t.Context(), hash, receipt, minedAt)) - require.NoError(t, store.recordFee(t.Context(), hash, receipt, now)) - } - require.Equal(t, http.StatusNoContent, get(empty).Code) - require.NoError(t, store.recordFee(t.Context(), common.Hash{2}, &types.Receipt{ - Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(1), - }, older.Add(-time.Minute))) - require.NoError(t, store.recordFee(t.Context(), common.Hash{1}, &types.Receipt{GasUsed: 10_000, EffectiveGasPrice: big.NewInt(500)}, now)) - require.NoError(t, store.Close()) - store, err = OpenRedeemerDB(path) - require.NoError(t, err) - defer store.Close() - handler := Handler(store) - client, disconnect := context.WithCancel(t.Context()) - disconnect() - response := httptest.NewRecorder() - handler.ServeHTTP(response, httptest.NewRequestWithContext(client, http.MethodGet, "/fee-estimate", nil)) - require.Equal(t, http.StatusOK, response.Code) - var estimate feeEstimateResponse - require.NoError(t, json.Unmarshal(response.Body.Bytes(), &estimate)) - require.Equal(t, "1900", estimate.Wei) - require.True(t, estimate.ExpiresAt.Equal(older.Add(feeWindow))) - _, err = store.db.ExecContext(t.Context(), "UPDATE redemption_fee_samples SET block_time=?", now.Add(-feeWindow).Unix()) - require.NoError(t, err) - require.Equal(t, response.Body.String(), get(handler).Body.String()) - require.Equal(t, http.StatusNoContent, get(Handler(store)).Code) -} - -func TestFeeReceiptRemainsEligibleAfterFinalizedUse(t *testing.T) { - f := newRecoveryRPC(t) - store, ticket := f.store(t, 9) - chain := f.Chain(t) - prepared, err := chain.PrepareRedemption(t.Context(), recoveryKey(t), big.NewInt(1), redeemTicket(ticket)) - require.NoError(t, err) - require.NoError(t, store.RecordPrepared(t.Context(), ticket, prepared)) - finalized, err := chain.RedemptionSnapshot(t.Context(), "finalized") - require.NoError(t, err) - require.NoError(t, store.settle(t.Context(), ticket, "used", finalized)) - _, err = store.db.Exec("UPDATE redemption_fee_samples SET block_time=?", time.Now().Add(-time.Hour).Unix()) - require.NoError(t, err) - expired := common.Hash{1} - _, err = store.db.Exec("INSERT INTO redemption_fee_samples(hash,block_time) VALUES(?,?)", expired.Hex(), time.Now().Add(-feeWindow).Unix()) - require.NoError(t, err) - rpcErr := errors.New("receipt RPC unavailable") - require.ErrorIs(t, store.collectUsedFees(t.Context(), timedFeeReceipt(func(context.Context, common.Hash) (*types.Receipt, time.Time, error) { - return nil, time.Time{}, rpcErr - })), rpcErr) - count, err := store.WinningTicketCount(ticket.PayerAddress) - require.NoError(t, err) - require.Zero(t, count) - var nextAttempt int64 - require.NoError(t, store.db.QueryRow("SELECT next_attempt FROM redemption_fee_samples WHERE hash=?", prepared.Hash.Hex()).Scan(&nextAttempt)) - require.Greater(t, nextAttempt, time.Now().Add(5*time.Minute).Unix()) - require.NoError(t, store.db.QueryRow("SELECT count(*) FROM redemption_fee_samples WHERE hash=?", expired.Hex()).Scan(&count)) - require.Zero(t, count) - - _, err = store.db.Exec("UPDATE redemption_fee_samples SET next_attempt=0") - require.NoError(t, err) - minedAt := time.Now().Add(-time.Hour).Truncate(time.Second) - require.NoError(t, store.collectUsedFees(t.Context(), timedFeeReceipt(func(_ context.Context, hash common.Hash) (*types.Receipt, time.Time, error) { - require.Equal(t, prepared.Hash, hash) - return &types.Receipt{Status: types.ReceiptStatusSuccessful, GasUsed: 100, EffectiveGasPrice: big.NewInt(4)}, minedAt, nil - }))) - var fee []byte - var blockTime int64 - require.NoError(t, store.db.QueryRow("SELECT fee,block_time FROM redemption_fee_samples WHERE hash=?", prepared.Hash.Hex()).Scan(&fee, &blockTime)) - require.Equal(t, int64(400), new(big.Int).SetBytes(fee).Int64()) - require.Equal(t, minedAt.Unix(), blockTime) -} - -func TestFeeWriteFailureDoesNotBlockReceiptSettlement(t *testing.T) { - for _, phase := range []string{"confirmed", "used"} { - t.Run(phase, func(t *testing.T) { - f := newRecoveryRPC(t) - store, ticket := f.store(t, 9) - chain := f.Chain(t) - prepared, err := chain.PrepareRedemption(t.Context(), recoveryKey(t), big.NewInt(1), redeemTicket(ticket)) - require.NoError(t, err) - require.NoError(t, store.RecordPrepared(t.Context(), ticket, prepared)) - finalized, err := chain.RedemptionSnapshot(t.Context(), "finalized") - require.NoError(t, err) - _, err = store.db.Exec(`CREATE TRIGGER disable_fee_writes BEFORE INSERT ON redemption_fee_samples - BEGIN SELECT RAISE(ABORT, 'test fee write failure'); END`) - require.NoError(t, err) - if phase == "used" { - require.NoError(t, store.settle(t.Context(), ticket, phase, finalized)) - } else { - receipt := &types.Receipt{ - Status: types.ReceiptStatusSuccessful, BlockNumber: finalized.Number, BlockHash: finalized.BlockHash, - GasUsed: 100, EffectiveGasPrice: big.NewInt(4), - } - require.NoError(t, store.confirmReceipt(t.Context(), ticket.Sig, prepared.Hash, receipt, time.Now())) - } - count, err := store.WinningTicketCount(ticket.PayerAddress) - require.NoError(t, err) - require.Zero(t, count) - var settledPhase string - require.NoError(t, store.db.QueryRow("SELECT phase FROM redemption_attempts WHERE sig=?", ticket.Sig).Scan(&settledPhase)) - require.Equal(t, phase, settledPhase) - }) - } -} diff --git a/redemption/http.go b/redemption/http.go index 64d1dae..021a82c 100644 --- a/redemption/http.go +++ b/redemption/http.go @@ -93,7 +93,6 @@ func Handler(s *RedeemerDB) http.Handler { // The ticket is nil if decoding fails. authorize must write any failure response. func HandlerWithAuthorization(s *RedeemerDB, authorize func(http.ResponseWriter, *http.Request, *TicketJSON) bool) http.Handler { mux := http.NewServeMux() - mux.HandleFunc("GET /fee-estimate", s.feeEstimateHandler()) slots := make(chan struct{}, 32) mux.HandleFunc("POST /tickets", func(w http.ResponseWriter, r *http.Request) { select { @@ -168,11 +167,10 @@ func (e *Rejection) Error() string { } type HTTPDestination struct { - endpoint string - feeEndpoint string - client *http.Client - binding Binding - headers http.Header + endpoint string + client *http.Client + binding Binding + headers http.Header } func NewHTTPDestination(u *url.URL, policy destination.Policy, b Binding, headers ...http.Header) (*HTTPDestination, error) { @@ -184,16 +182,12 @@ func NewHTTPDestination(u *url.URL, policy destination.Policy, b Binding, header if err != nil { return nil, err } - feeEndpoint, err := url.JoinPath(normalized.String(), "fee-estimate") - if err != nil { - return nil, err - } client := &http.Client{Transport: policy.Transport(15 * time.Second), Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} h := make(http.Header) if len(headers) > 0 && headers[0] != nil { h = headers[0].Clone() } - return &HTTPDestination{endpoint: endpoint, feeEndpoint: feeEndpoint, client: client, binding: b, headers: h}, nil + return &HTTPDestination{endpoint: endpoint, client: client, binding: b, headers: h}, nil } func (d *HTTPDestination) Close() { d.client.CloseIdleConnections() } diff --git a/redemption/http_test.go b/redemption/http_test.go index 5a436c0..b905489 100644 --- a/redemption/http_test.go +++ b/redemption/http_test.go @@ -61,6 +61,9 @@ func TestHTTPAdmissionIdentityCapacityAndScope(t *testing.T) { s, b := boundStore(t, "redeemer", "chain", Limits{Pending: 2, PerRecipient: 1}) calls := 0 handler := HandlerWithAuthorization(s, func(http.ResponseWriter, *http.Request, *TicketJSON) bool { calls++; return true }) + feeEstimate := httptest.NewRecorder() + handler.ServeHTTP(feeEstimate, httptest.NewRequest(http.MethodGet, "/fee-estimate", nil)) + require.Equal(t, http.StatusNotFound, feeEstimate.Code) submit := func(req TicketRequest) *httptest.ResponseRecorder { raw, err := json.Marshal(req) require.NoError(t, err) diff --git a/redemption/migrations/006_fee_samples.sql b/redemption/migrations/006_fee_samples.sql deleted file mode 100644 index fe27802..0000000 --- a/redemption/migrations/006_fee_samples.sql +++ /dev/null @@ -1,8 +0,0 @@ --- UP -CREATE TABLE redemption_fee_samples ( - hash TEXT PRIMARY KEY, block_time INTEGER NOT NULL, fee BLOB, next_attempt INTEGER NOT NULL DEFAULT 0 -); -CREATE INDEX redemption_fee_samples_time ON redemption_fee_samples(block_time DESC,hash); -CREATE INDEX redemption_fee_samples_pending ON redemption_fee_samples(next_attempt,hash) WHERE fee IS NULL; --- DOWN -DROP TABLE redemption_fee_samples; diff --git a/redemption/redeemer.go b/redemption/redeemer.go index 8c525e4..edb261b 100644 --- a/redemption/redeemer.go +++ b/redemption/redeemer.go @@ -32,28 +32,6 @@ type ReceiptReader interface { FinalizedReceipt(context.Context, common.Hash) (*types.Receipt, error) } -type timedReceiptReader interface { - FinalizedReceiptWithTime(context.Context, common.Hash) (*types.Receipt, time.Time, error) -} - -func finalizedReceipt(ctx context.Context, chain ReceiptReader, hash common.Hash) (*types.Receipt, time.Time, error) { - if timed, ok := chain.(timedReceiptReader); ok { - return timed.FinalizedReceiptWithTime(ctx, hash) - } - receipt, err := chain.FinalizedReceipt(ctx, hash) - return receipt, time.Time{}, err -} - -func (s *RedeemerDB) confirmReceipt(ctx context.Context, sig []byte, hash common.Hash, receipt *types.Receipt, minedAt time.Time) error { - if err := s.finishTicket(ctx, sig, "confirmed", hash.Hex(), eth.ChainSnapshot{Number: receipt.BlockNumber, BlockHash: receipt.BlockHash}); err != nil { - return err - } - if err := s.recordFee(ctx, hash, receipt, minedAt); err != nil && s.logger != nil { - s.logger.Warn("redemption fee sample write failed", "event", "redemption_fee", "error", err) - } - return nil -} - // ReconcileSubmitted checks every retained identity, including old retry groups. // A finalized success wins over sibling failures; failed attempts alone cannot // release liability while another signed identity might still redeem the ticket. @@ -77,7 +55,7 @@ func ReconcileSubmitted(ctx context.Context, store *RedeemerDB, chain ReceiptRea } visited++ store.receiptCursor.after.Store(item.rowid) - receipt, minedAt, err := finalizedReceipt(ctx, chain, item.Hash) + receipt, err := chain.FinalizedReceipt(ctx, item.Hash) id := string(item.Signature) if err != nil { failures = append(failures, fmt.Errorf("receipt %s: %w", item.Hash.Hex(), err)) @@ -85,7 +63,7 @@ func ReconcileSubmitted(ctx context.Context, store *RedeemerDB, chain ReceiptRea } if receipt != nil && receipt.Status == types.ReceiptStatusSuccessful { successes[id] = true - err = store.confirmReceipt(ctx, item.Signature, item.Hash, receipt, minedAt) + err = store.finishTicket(ctx, item.Signature, "confirmed", item.Hash.Hex(), eth.ChainSnapshot{Number: receipt.BlockNumber, BlockHash: receipt.BlockHash}) } else if receipt != nil && receipt.Status == types.ReceiptStatusFailed { reverts[id] = item.Hash err = store.finishTicket(ctx, item.Signature, "reverted", item.Hash.Hex()) diff --git a/redemption/redeemer_db_test.go b/redemption/redeemer_db_test.go index 0e491b0..497350a 100644 --- a/redemption/redeemer_db_test.go +++ b/redemption/redeemer_db_test.go @@ -187,9 +187,10 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { c, key := f.Chain(t), recoveryKey(t) files, err := fs.Sub(MigrationFiles, "migrations") require.NoError(t, err) - for range 5 { - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - } + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) // Seed a genuine v1 database, then upgrade without changing its ticket identity. prepared, err := c.PrepareRedemption(t.Context(), key, big.NewInt(1), redeemTicket(ticket)) require.NoError(t, err) @@ -211,9 +212,10 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { require.NoError(t, s.db.QueryRow("SELECT phase FROM redemption_transactions WHERE hash=?", prepared.Hash.Hex()).Scan(&phase)) require.Equal(t, "submitted", phase) // A lossless rollback remains possible with the original representable state. - for range 5 { - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - } + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) require.NoError(t, migrations.Up(t.Context(), s.db, files)) _, err = s.db.Exec("UPDATE redemption_attempts SET phase='retryable' WHERE sig=?", ticket.Sig) require.NoError(t, err) @@ -221,9 +223,9 @@ func TestRedemptionMigrationHistoryAndRollback(t *testing.T) { next.Hash = ethcommon.HexToHash("0xabcdef") next.Nonce = 1 require.NoError(t, s.RecordPrepared(t.Context(), ticket, next)) - for range 4 { - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - } + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) require.ErrorContains(t, migrations.Down(t.Context(), s.db, files), "cannot_downgrade_redemption_transaction_history") history, err = s.SubmittedRedemptions() require.NoError(t, err) @@ -251,9 +253,9 @@ func TestRedemptionRollbackPreservesTransactionProgress(t *testing.T) { require.EqualValues(t, 1, floor) files, err := fs.Sub(MigrationFiles, "migrations") require.NoError(t, err) - for range 4 { - require.NoError(t, migrations.Down(t.Context(), s.db, files)) - } + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) + require.NoError(t, migrations.Down(t.Context(), s.db, files)) require.ErrorContains(t, migrations.Down(t.Context(), s.db, files), "cannot_downgrade_redemption_transaction_history") floor, err = s.SavedNonceFloor(t.Context(), key.Address()) require.NoError(t, err) diff --git a/redemption/redemption_store.go b/redemption/redemption_store.go index fb6211c..1807904 100644 --- a/redemption/redemption_store.go +++ b/redemption/redemption_store.go @@ -335,12 +335,6 @@ func (s *RedeemerDB) finishTicket(ctx context.Context, sig []byte, phase string, return err } } - var feeHashes string - var feeErr error - if phase == "used" { - feeErr = tx.QueryRowContext(ctx, `SELECT json_group_array(hash) FROM redemption_transactions - WHERE sig=? AND phase NOT IN ('confirmed','reverted','superseded')`, sig).Scan(&feeHashes) - } if phase == "confirmed" || phase == "used" { if _, err := tx.ExecContext(ctx, "UPDATE ticket_state SET settled=1,settlement='used' WHERE hash=(SELECT ticket_hash FROM winning_tickets WHERE sig=?)", sig); err != nil { return err @@ -360,15 +354,6 @@ func (s *RedeemerDB) finishTicket(ctx context.Context, sig []byte, phase string, if err := commit(); err != nil { return err } - if phase == "used" { - if feeErr == nil && feeHashes != "[]" { - _, feeErr = s.db.ExecContext(ctx, `INSERT INTO redemption_fee_samples(hash,block_time) - SELECT value,? FROM json_each(?) WHERE true ON CONFLICT(hash) DO NOTHING`, time.Now().Unix(), feeHashes) - } - if feeErr != nil && s.logger != nil { - s.logger.Warn("redemption fee queue write failed", "event", "redemption_fee", "error", feeErr) - } - } if s.metrics != nil && observationErr == nil { if oldPhase != phase { s.observeTransition(phase, hash, nil) diff --git a/redemption/worker.go b/redemption/worker.go index 9cffd55..f0d7ba7 100644 --- a/redemption/worker.go +++ b/redemption/worker.go @@ -60,17 +60,6 @@ func NewWorker(s *RedeemerDB, c eth.PaymentChain, d Destination) (*Worker, error return w, nil } -// CollectFees has a separate budget so a full redemption pass cannot starve fee sampling. -func (w *Worker) CollectFees(ctx context.Context) { - if _, local := w.destination.(*ChainDestination); local { - ctx, cancel := context.WithTimeout(eth.WithRPCWork(ctx, "background"), 5*time.Second) - defer cancel() - if err := w.store.collectUsedFees(ctx, w.chain); err != nil && w.store.logger != nil { - w.store.logger.Warn("redemption fee collection failed", "event", "redemption_fee", "error", err) - } - } -} - // Process performs a bounded, rotating pass. Inclusion recovery belongs to the // daemon lifetime; a slow payer cannot monopolize the next pass's starting point. func (w *Worker) Process(ctx context.Context) []error { From 7416879bd861363d5a54dfaaef99fdc0a853088e Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:22:32 -0800 Subject: [PATCH 3/8] Validate quote funding and preserve exact ticket EV Check the collateral watermark with pending liability before quoting. If normal quotes fail at a signer ceiling, use the largest funded face value that can encode the exact EV. --- docs/orchestrator.md | 2 + orchestrator/ticket_rounding.go | 118 +++++++++++++++++++++++++ orchestrator/ticket_sizing.go | 65 ++++++++++---- orchestrator/ticket_sizing_test.go | 50 +++++++++++ redemption/redeemer_db.go | 15 +++- redemption/redemption_recovery_test.go | 15 +++- redemption/state.go | 28 +++--- signer/payment_test.go | 4 +- 8 files changed, 267 insertions(+), 30 deletions(-) create mode 100644 orchestrator/ticket_rounding.go diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 23932aa..4388ec2 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -155,6 +155,8 @@ chain. The example config uses `2400000000000000` wei (0.0024 ETH), based on a fixed Arbitrum redemption cost estimate of 0.000012 ETH and a 0.5% gas target. Fixed-price quotes use the fewest tickets that cover the price, up to 100. +If rounding blocks a quote at an EV ceiling, Node tries a smaller payout +that can encode the exact EV. Metered tickets target `MeteredTicketSeconds` seconds of quoted usage (default 3). The signer bills elapsed time and carries forward credit. Set `MaxTicketEV` and `MaxBatchEV` to match the signer's limits, in wei. Their defaults are diff --git a/orchestrator/ticket_rounding.go b/orchestrator/ticket_rounding.go new file mode 100644 index 0000000..c22e2c4 --- /dev/null +++ b/orchestrator/ticket_rounding.go @@ -0,0 +1,118 @@ +package orchestrator + +import ( + "math/big" + "slices" + "sort" +) + +var winProbabilityDivisors = func() []*big.Int { + // Prime factors of 2^256-1, the denominator of the encoded win probability. + factors := []string{ + "3", "5", "17", "257", "641", "65537", "274177", "6700417", + "67280421310721", "59649589127497217", "5704689200685129054721", + } + primes := make([]*big.Int, 0, len(factors)) + for _, factor := range factors { + prime, _ := new(big.Int).SetString(factor, 10) + primes = append(primes, prime) + } + return divisorsFromPrimes(primes) +}() + +func exactTicketFace(ev *big.Rat, limit *big.Int, feeDivisors []*big.Int) *big.Int { + // For EV a/b in lowest terms, face × encoded odds must equal a × (M/b), + // where M is maxWinProb. Split each face divisor across the two factors. + var remainder big.Int + scaled, _ := new(big.Int).QuoRem(maxWinProb, ev.Denom(), &remainder) + if remainder.Sign() != 0 { + return nil + } + var oddsDivisors []*big.Int + for _, divisor := range winProbabilityDivisors { + if remainder.Mod(scaled, divisor).Sign() == 0 { + oddsDivisors = append(oddsDivisors, divisor) + } + } + best := new(big.Int) + for _, divisor := range feeDivisors { + if divisor.Cmp(limit) > 0 { + break + } + if remainder.Mod(ev.Num(), divisor).Sign() != 0 { + continue + } + remaining := new(big.Int).Quo(limit, divisor) + index := sort.Search(len(oddsDivisors), func(i int) bool { + return oddsDivisors[i].Cmp(remaining) > 0 + }) + face := new(big.Int).Mul(divisor, oddsDivisors[index-1]) + if face.Cmp(best) > 0 { + best = face + } + } + if ev.Cmp(new(big.Rat).SetInt(best)) >= 0 { + return nil + } + return best +} + +func divisorsFromPrimes(primes []*big.Int) []*big.Int { + slices.SortFunc(primes, (*big.Int).Cmp) + divisors := []*big.Int{big.NewInt(1)} + var power big.Int + var base []*big.Int + for i, prime := range primes { + if i == 0 || prime.Cmp(primes[i-1]) != 0 { + base = divisors + power.SetInt64(1) + } + power.Mul(&power, prime) + for _, divisor := range base { + divisors = append(divisors, new(big.Int).Mul(divisor, &power)) + } + } + slices.SortFunc(divisors, (*big.Int).Cmp) + return divisors +} + +func primeFactors(n *big.Int) []*big.Int { + if n.Cmp(big.NewInt(1)) <= 0 { + return nil + } + if n.ProbablyPrime(8) { + return []*big.Int{n} + } + factor := findFactor(n) + return append(primeFactors(factor), primeFactors(new(big.Int).Quo(n, factor))...) +} + +func findFactor(n *big.Int) *big.Int { + var x, y, divisor big.Int + for _, p := range []int64{2, 3, 5} { + prime := big.NewInt(p) + if divisor.Mod(n, prime).Sign() == 0 { + return prime + } + } + // Pollard's rho factors the integer quote without scanning up to its square root. + one := big.NewInt(1) + for c := big.NewInt(1); ; c.Add(c, one) { + step := func(x *big.Int) { x.Mul(x, x).Add(x, c).Mod(x, n) } + x.SetInt64(2) + y.Set(&x) + for { + step(&x) + step(&y) + step(&y) + divisor.Sub(&x, &y) + divisor.GCD(nil, nil, &divisor, n) + if divisor.Cmp(n) == 0 { + break + } + if divisor.Cmp(one) > 0 { + return &divisor + } + } + } +} diff --git a/orchestrator/ticket_sizing.go b/orchestrator/ticket_sizing.go index 435efe7..a099ebd 100644 --- a/orchestrator/ticket_sizing.go +++ b/orchestrator/ticket_sizing.go @@ -51,7 +51,7 @@ func (e *PaymentEngine) quoteTicket(ctx context.Context, payer common.Address, p if err := pm.ValidatePayerFunds(funds); err != nil { return pm.ChainSnapshot{}, nil, nil, fmt.Errorf("%w: %v", pm.ErrPayerUnavailable, err) } - pending, err := e.store.RecipientLiability(ctx, payer, e.recipient) + pending, err := e.store.RecipientLiability(ctx, payer, e.recipient, funds.Snapshot) if err != nil { return pm.ChainSnapshot{}, nil, nil, err } @@ -82,38 +82,71 @@ func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit meteredEV = new(big.Rat).Mul(fee, big.NewRat(s.MeteredTicketSeconds, 1)) fee.Mul(fee, big.NewRat(pm.InitialLivePaymentSeconds, 1)) } - if fee.Cmp(s.MaxBatchEV) > 0 { + // A batch's EV is strictly below its total face value. + if fee.Cmp(s.MaxBatchEV) > 0 || fee.Num().Cmp(reserve) >= 0 { return nil, nil, errQuoteUnpayable } - maxValidOdds := new(big.Int).Sub(maxWinProb, big.NewInt(1)) + type exactQuote struct { + faceLimit *big.Int + ev *big.Rat + } + var exactQuotes []exactQuote for count := int64(1); count <= pm.MaxTicketBatchSize; count++ { // Every ticket in the quoted batch may win. face := minBigInt(faceLimit, new(big.Int).Quo(reserve, big.NewInt(count))) if face.Sign() == 0 { break } - maxOdds := minBigInt(ticketProbability(s.MaxTicketEV, face, big.Floor), maxValidOdds) - if metered { - maxOdds = minBigInt(maxOdds, ticketProbability(meteredEV, face, big.Ceil)) - } tickets := big.NewRat(count, 1) - minOdds := ticketProbability(new(big.Rat).Quo(fee, tickets), face, big.Ceil) - if minOdds.Cmp(maxOdds) > 0 { + requiredEV := new(big.Rat).Quo(fee, tickets) + limitEV := new(big.Rat).Quo(s.MaxBatchEV, tickets) + if s.MaxTicketEV.Cmp(limitEV) < 0 { + limitEV = s.MaxTicketEV + } + limit := requiredEV.Cmp(limitEV) + if limit > 0 { continue } - batchOdds := ticketProbability(new(big.Rat).Quo(s.MaxBatchEV, tickets), face, big.Floor) - if minOdds.Cmp(batchOdds) <= 0 { - if metered { - // Aim for the cadence EV, with enough room for the signer to open - // the session without exceeding its batch limit. - return face, minBigInt(maxOdds, batchOdds), nil + if odds := selectTicketOdds(face, requiredEV, limitEV, meteredEV); odds != nil { + return face, odds, nil + } + if limit == 0 { + exactQuotes = append(exactQuotes, exactQuote{face, requiredEV}) + } + } + // Prefer the funded baseline. At the ceiling, try a smaller face value + // that can encode the exact fee when every normal quote failed. + if len(exactQuotes) == 0 { + return nil, nil, errQuoteUnpayable + } + feeDivisors := divisorsFromPrimes(primeFactors(fee.Num())) + for _, quote := range exactQuotes { + face := exactTicketFace(quote.ev, quote.faceLimit, feeDivisors) + if face != nil { + if odds := selectTicketOdds(face, quote.ev, quote.ev, meteredEV); odds != nil { + return face, odds, nil } - return face, minOdds, nil } } return nil, nil, errQuoteUnpayable } +func selectTicketOdds(face *big.Int, requiredEV, limitEV, meteredEV *big.Rat) *big.Int { + maxOdds := minBigInt(ticketProbability(limitEV, face, big.Floor), new(big.Int).Sub(maxWinProb, big.NewInt(1))) + if meteredEV != nil { + maxOdds = minBigInt(maxOdds, ticketProbability(meteredEV, face, big.Ceil)) + } + minOdds := ticketProbability(requiredEV, face, big.Ceil) + if minOdds.Cmp(maxOdds) > 0 { + return nil + } + if meteredEV != nil { + // Aim for the cadence EV while fitting the full opening batch. + return maxOdds + } + return minOdds +} + func ticketProbability(ev *big.Rat, face *big.Int, rounding big.RoundingMode) *big.Int { scaled := new(big.Int).Mul(ev.Num(), maxWinProb) denominator := new(big.Int).Mul(ev.Denom(), face) diff --git a/orchestrator/ticket_sizing_test.go b/orchestrator/ticket_sizing_test.go index f0c4939..03c8782 100644 --- a/orchestrator/ticket_sizing_test.go +++ b/orchestrator/ticket_sizing_test.go @@ -80,3 +80,53 @@ func TestMeteredOpeningFitsBatchLimit(t *testing.T) { _, _, err = sizing.ticketTerms(limit, reserve, 2_000_000_000_001, "seconds") require.ErrorIs(t, err, errQuoteUnpayable) } + +func TestQuoteAtExactBatchEVLimit(t *testing.T) { + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + for _, tc := range []struct { + name, unit string + price, faceLimit int64 + count int + }{ + {"fixed", "fixed", 20_000_000_000_000, 2_400_000_000_000_000, 8}, + {"metered", "seconds", 2_000_000_000_000, 2_400_000_000_000_000, 8}, + {"smaller face limit", "fixed", 20_000_000_000_000, 1_675_104_250_001, 12}, + } { + t.Run(tc.name, func(t *testing.T) { + limit := big.NewInt(tc.faceLimit) + reserve := new(big.Int).Mul(limit, big.NewInt(pm.MaxTicketBatchSize)) + face, odds, err := sizing.ticketTerms(limit, reserve, tc.price, tc.unit) + require.NoError(t, err) + count, err := pm.RemoteBatchSize(pm.TicketParams{FaceValue: face, WinProb: odds}, sizing.MaxBatchEV, new(big.Rat)) + require.NoError(t, err) + require.Equal(t, tc.count, count) + ev := new(big.Rat).SetFrac(new(big.Int).Mul(face, odds), maxWinProb) + require.LessOrEqual(t, ev.Cmp(sizing.MaxTicketEV), 0) + require.Zero(t, new(big.Rat).Mul(ev, big.NewRat(int64(count), 1)).Cmp(sizing.MaxBatchEV)) + }) + } + _, _, err := sizing.ticketTerms(big.NewInt(2_400_000_000_000_000), sizing.MaxBatchEV.Num(), 20_000_000_000_000, "fixed") + require.ErrorIs(t, err, errQuoteUnpayable) +} + +func TestExactTicketAtTightFundingLimit(t *testing.T) { + const composite = 1_000_003 * 1_000_033 + for _, tt := range []struct { + name string + price, limit, reserve, face int64 + }{ + {"large probability denominator", 65_536, 65_538, 65_538, 65_537}, + {"composite price", composite, 3*composite + 1, 400 * composite, 3 * composite}, + } { + t.Run(tt.name, func(t *testing.T) { + ceiling := big.NewRat(tt.price, 1) + policy := pm.PayerPolicy{MaxTicketEV: ceiling, MaxBatchEV: ceiling, DepositMultiplier: 1} + sizing := TicketSizing{PayerPolicy: policy, MeteredTicketSeconds: 3} + face, odds, err := sizing.ticketTerms(big.NewInt(tt.limit), big.NewInt(tt.reserve), tt.price, "fixed") + require.NoError(t, err) + require.Equal(t, big.NewInt(tt.face), face) + ev := new(big.Rat).SetFrac(new(big.Int).Mul(face, odds), maxWinProb) + require.Zero(t, ev.Cmp(ceiling)) + }) + } +} diff --git a/redemption/redeemer_db.go b/redemption/redeemer_db.go index e80d501..163bbda 100644 --- a/redemption/redeemer_db.go +++ b/redemption/redeemer_db.go @@ -222,7 +222,7 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom if err := tx.StmtContext(ctx, s.admission).QueryRowContext(ctx, randHash.Hex()).Scan(&number, &hash, &exposed); err != nil { return err } - if number.Valid && (snapshot.Number == nil || snapshot.Number.Cmp(big.NewInt(number.Int64)) < 0 || (snapshot.Number.Cmp(big.NewInt(number.Int64)) == 0 && snapshot.BlockHash.Hex() != hash.String)) { + if !coversCollateralWatermark(snapshot, number, hash) { return pm.ErrPayerUnavailable } // Once redemption can reveal randomness, this epoch must never accept @@ -255,7 +255,7 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom return err } } - pending, err := s.unsettledLiability(ctx, tx, payer) + pending, err := unsettledLiability(ctx, tx, payer, ethcommon.Address{}) if err != nil { return err } @@ -268,6 +268,17 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom return tx.Commit() } +func coversCollateralWatermark(snapshot pm.ChainSnapshot, number sql.NullInt64, hash sql.NullString) bool { + if !number.Valid { + return true + } + if snapshot.Number == nil { + return false + } + height := snapshot.Number.Cmp(big.NewInt(number.Int64)) + return height > 0 || (height == 0 && snapshot.BlockHash.Hex() == hash.String) +} + func validStoredTicket(t *pm.SignedTicket) error { if t == nil || t.Ticket == nil || t.FaceValue == nil || t.WinProb == nil || t.ParamsExpirationBlock == nil || t.RecipientRand == nil || len(t.Sig) == 0 { return errors.New("incomplete signed ticket") diff --git a/redemption/redemption_recovery_test.go b/redemption/redemption_recovery_test.go index 8991a51..4f3f6e0 100644 --- a/redemption/redemption_recovery_test.go +++ b/redemption/redemption_recovery_test.go @@ -1011,8 +1011,14 @@ func TestCollateralWatermarkSurvivesSettlementAndRestart(t *testing.T) { admit := func(snapshot eth.ChainSnapshot) error { return store.StoreWinningTickets(t.Context(), ticket.PayerAddress, next.RecipientRandHash, new(big.Int).Set(ticket.FaceValue), []*pm.SignedTicket{next}, snapshot) } + liability := func(snapshot eth.ChainSnapshot) (*big.Int, error) { + return store.RecipientLiability(t.Context(), ticket.PayerAddress, ticket.Recipient, snapshot) + } + pending, err := liability(captured) + require.NoError(t, err) + require.Equal(t, ticket.FaceValue, pending) require.ErrorContains(t, store.finishTicket(t.Context(), ticket.Sig, "used", ""), "block evidence required") - _, err := store.db.Exec(`CREATE TRIGGER fail_settlement BEFORE UPDATE OF redeemed_at ON winning_tickets BEGIN SELECT RAISE(ABORT,'storage failure'); END`) + _, err = store.db.Exec(`CREATE TRIGGER fail_settlement BEFORE UPDATE OF redeemed_at ON winning_tickets BEGIN SELECT RAISE(ABORT,'storage failure'); END`) require.NoError(t, err) require.Error(t, store.finishTicket(t.Context(), ticket.Sig, "used", "", settled)) var floors, redeemed int @@ -1032,6 +1038,13 @@ func TestCollateralWatermarkSurvivesSettlementAndRestart(t *testing.T) { wrongFork := settled wrongFork.BlockHash = common.HexToHash("0xbad") require.ErrorIs(t, admit(wrongFork), pm.ErrPayerUnavailable) + _, err = liability(captured) + require.ErrorIs(t, err, eth.ErrObservationUnavailable) + _, err = liability(wrongFork) + require.ErrorIs(t, err, eth.ErrObservationUnavailable) + pending, err = liability(settled) + require.NoError(t, err) + require.Zero(t, pending.Sign()) require.ErrorContains(t, store.finishTicket(t.Context(), ticket.Sig, "used", "", wrongFork), "conflicting finalized") require.NoError(t, admit(settled), "post-settlement collateral can cover the next winner") require.Error(t, admit(settled), "durable settlement must retain signature replay protection") diff --git a/redemption/state.go b/redemption/state.go index f560fe6..30fe7fa 100644 --- a/redemption/state.go +++ b/redemption/state.go @@ -346,24 +346,32 @@ func (s *RedeemerDB) delivery(ctx context.Context, t *pm.SignedTicket, phase str return err } -func (s *RedeemerDB) unsettledLiability(ctx context.Context, tx *sql.Tx, payer common.Address) (*big.Int, error) { - return unsettledLiability(ctx, tx, payer, common.Address{}) -} - -func (s *RedeemerDB) RecipientLiability(ctx context.Context, payer, recipient common.Address) (*big.Int, error) { - return unsettledLiability(ctx, s.db, payer, recipient) +// RecipientLiability reads pending wins against the same collateral watermark. +func (s *RedeemerDB) RecipientLiability(ctx context.Context, payer, recipient common.Address, snapshot pm.ChainSnapshot) (*big.Int, error) { + tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return nil, err + } + defer tx.Rollback() + var number sql.NullInt64 + var hash sql.NullString + if err := tx.QueryRowContext(ctx, "SELECT number,hash FROM (SELECT 1) LEFT JOIN collateral_watermark ON id=1").Scan(&number, &hash); err != nil { + return nil, err + } + if !coversCollateralWatermark(snapshot, number, hash) { + return nil, eth.ErrObservationUnavailable + } + return unsettledLiability(ctx, tx, payer, recipient) } -func unsettledLiability(ctx context.Context, q interface { - QueryContext(context.Context, string, ...any) (*sql.Rows, error) -}, payer, recipient common.Address) (*big.Int, error) { +func unsettledLiability(ctx context.Context, tx *sql.Tx, payer, recipient common.Address) (*big.Int, error) { query := `SELECT w.face_value FROM ticket_state t JOIN winning_tickets w ON w.sig=t.sig WHERE w.payer_address=? AND w.redeemed_at IS NULL AND t.settled=0` args := []any{payer.Hex()} if recipient != (common.Address{}) { query += " AND w.recipient=?" args = append(args, recipient.Hex()) } - rows, err := q.QueryContext(ctx, query, args...) + rows, err := tx.QueryContext(ctx, query, args...) if err != nil { return nil, err } diff --git a/signer/payment_test.go b/signer/payment_test.go index 46164be..39c3615 100644 --- a/signer/payment_test.go +++ b/signer/payment_test.go @@ -200,7 +200,9 @@ func TestAdaptiveQuotesWithSigner(t *testing.T) { } _, err = s.preparePayment(t.Context(), "live", "live", live, open.State, 0, now.Add(303*time.Second)) require.Error(t, err) - pending, err := store.RecipientLiability(t.Context(), key.Address(), liveRecipient) + snapshot, err := chain.Snapshot(t.Context()) + require.NoError(t, err) + pending, err := store.RecipientLiability(t.Context(), key.Address(), liveRecipient, snapshot) require.NoError(t, err) chain.reserve = baseline/2 + pending.Int64() _, err = engine.RefreshChallenge(t.Context(), "live", key.Address(), "https://orch.example") From 17537091e14279b50da6783a3fb02d6f944af7d9 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:31:26 -0800 Subject: [PATCH 4/8] Cover ticket challenge funding failures Check failed challenge and refresh responses over HTTP. Clarify that fixed quotes keep the funded face value when a batch fits within signer limits. --- docs/orchestrator.md | 6 +-- orchestrator/payment_recipient_test.go | 63 ++++++++++++++++++++++++++ orchestrator/ticket_sizing_test.go | 12 +++++ 3 files changed, 78 insertions(+), 3 deletions(-) diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 4388ec2..31d40fc 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -154,9 +154,9 @@ Set `TicketFaceValue` high enough to cover typical redemption costs on your chain. The example config uses `2400000000000000` wei (0.0024 ETH), based on a fixed Arbitrum redemption cost estimate of 0.000012 ETH and a 0.5% gas target. -Fixed-price quotes use the fewest tickets that cover the price, up to 100. -If rounding blocks a quote at an EV ceiling, Node tries a smaller payout -that can encode the exact EV. +Fixed-price quotes use the fewest tickets that cover the price at the funded +face value, up to 100. If rounding at an EV ceiling rules out every batch at +that face value, Node tries a smaller payout that can encode the exact EV. Metered tickets target `MeteredTicketSeconds` seconds of quoted usage (default 3). The signer bills elapsed time and carries forward credit. Set `MaxTicketEV` and `MaxBatchEV` to match the signer's limits, in wei. Their defaults are diff --git a/orchestrator/payment_recipient_test.go b/orchestrator/payment_recipient_test.go index 185f091..cfae599 100644 --- a/orchestrator/payment_recipient_test.go +++ b/orchestrator/payment_recipient_test.go @@ -1,6 +1,7 @@ package orchestrator import ( + "bytes" "context" "crypto/ecdsa" "encoding/base64" @@ -8,6 +9,7 @@ import ( "encoding/json" "errors" "math/big" + "net/http" "net/http/httptest" "os" "path/filepath" @@ -515,6 +517,67 @@ func TestPaidFailureOutcomes(t *testing.T) { } +func TestAdaptiveChallengeAndRefreshFundingFailures(t *testing.T) { + for _, tc := range []struct { + name string + funds func(pm.PayerFunds) (pm.PayerFunds, error) + status int + }{ + {"payer RPC", func(pm.PayerFunds) (pm.PayerFunds, error) { + return pm.PayerFunds{}, errors.New("RPC unavailable") + }, http.StatusBadGateway}, + {"empty deposit", func(funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.Deposit.SetInt64(0) + return funds, nil + }, http.StatusBadRequest}, + {"unlocking funds", func(funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.WithdrawRound.Add(funds.Snapshot.Round, big.NewInt(1)) + return funds, nil + }, http.StatusBadRequest}, + {"reserve committed to a pending win", func(funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.Reserve.SetInt64(10) + return funds, nil + }, http.StatusBadRequest}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy, chain, key, _ := newRecipientTestEngine(t) + require.NoError(t, receiveRecipientPayment(t, legacy, key, issueRecipientParams(t, legacy, key), 1)) + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + engine, err := NewAdaptivePaymentEngine(legacy.store, chain, legacy.recipient, big.NewInt(100), sizing) + require.NoError(t, err) + registry, server := reviewServer(t, "http://127.0.0.1:1") + defer server.Close() + registry.SetWeiPerUSD(big.NewRat(1, 1)) + require.NoError(t, registry.AddStatic(StaticRunner{ID: "runner", App: "model", Mode: "single-shot", RunnerURL: "http://127.0.0.1:1", Capacity: 1, PriceInfo: priceInfo{Price: "9", Currency: "usd", Unit: "fixed"}})) + server.SetPayment(engine) + payer := crypto.PubkeyToAddress(key.PublicKey).Hex() + requestChallenge := func() *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodPost, "/apps/runner/app", nil) + request.Header.Set("Livepeer-Payer-Address", payer) + response := httptest.NewRecorder() + server.ServeHTTP(response, request) + return response + } + response := requestChallenge() + require.Equal(t, http.StatusPaymentRequired, response.Code, response.Body.String()) + var original Challenge + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &original)) + + chain.funds = func(_ context.Context, funds pm.PayerFunds) (pm.PayerFunds, error) { return tc.funds(funds) } + response = requestChallenge() + require.Equal(t, tc.status, response.Code, response.Body.String()) + require.Len(t, engine.sessions, 1, "a failed challenge must leave the session map unchanged") + refresh := mustJSON(t, map[string]string{"sender": payer, "manifest_id": original.ManifestID}) + response = httptest.NewRecorder() + server.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/refresh-payment", bytes.NewReader(refresh))) + require.Equal(t, tc.status, response.Code, response.Body.String()) + current, err := engine.ChallengeForManifest("runner", original.ManifestID, registry.service) + require.NoError(t, err) + require.Equal(t, original, current) + }) + } +} + func TestLiveChargeObservesOnlyDebitAttempts(t *testing.T) { e, _, key, _ := newRecipientTestEngine(t) e.metrics = observability.New("orchestrator") diff --git a/orchestrator/ticket_sizing_test.go b/orchestrator/ticket_sizing_test.go index 03c8782..8a423f5 100644 --- a/orchestrator/ticket_sizing_test.go +++ b/orchestrator/ticket_sizing_test.go @@ -109,6 +109,18 @@ func TestQuoteAtExactBatchEVLimit(t *testing.T) { require.ErrorIs(t, err, errQuoteUnpayable) } +func TestQuoteKeepsFundedFaceValueWhenBatchFits(t *testing.T) { + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + baseline := big.NewInt(2_400_000_000_000_000) + reserve := new(big.Int).Mul(baseline, big.NewInt(2)) + face, odds, err := sizing.ticketTerms(baseline, reserve, 3_000_000_000_000, "fixed") + require.NoError(t, err) + require.Equal(t, baseline, face) + count, err := pm.RemoteBatchSize(pm.TicketParams{FaceValue: face, WinProb: odds}, sizing.MaxTicketEV, new(big.Rat)) + require.NoError(t, err) + require.Equal(t, 2, count) +} + func TestExactTicketAtTightFundingLimit(t *testing.T) { const composite = 1_000_003 * 1_000_033 for _, tt := range []struct { From a6308dd651e3ade9e3fbd172ce9463d2e672d6ec Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:41:45 -0800 Subject: [PATCH 5/8] Frame ticket commitment fields independently Use the same unambiguous encoding when issuing and validating ticket parameters. Verify the encoding with independent commitment vectors. --- orchestrator/payment_recipient.go | 17 +++++++++-------- orchestrator/payment_recipient_test.go | 7 +++---- orchestrator/testdata/recipient-hmac.json | 12 ++++++------ 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/orchestrator/payment_recipient.go b/orchestrator/payment_recipient.go index b9e50db..be7bb00 100644 --- a/orchestrator/payment_recipient.go +++ b/orchestrator/payment_recipient.go @@ -3,6 +3,7 @@ package orchestrator import ( "crypto/hmac" "crypto/sha256" + "encoding/binary" "math/big" ethcommon "github.com/ethereum/go-ethereum/common" @@ -13,16 +14,16 @@ import ( // Ported from go-livepeer/pm/recipient.go at bd645a09266833fb859053445d9ac85846330756. // Originally by Yondon Fu, with parameter authentication by Nico Vergauwen: // 3159761196f5cafca93cdd6b6b40bead5e4ce80c and 5933bc2cfd57a54799d355aa7c78aa1094074c42. -// Preserve the HMAC inputs and their encoding: this derives the private lottery -// value and authenticates the advertised parameters without persisting them. +// Length-prefix variable-width integers so the HMAC authenticates each value +// while deriving the private lottery value without persisting the parameters. func (e *PaymentEngine) recipientRand(seed *big.Int, payer ethcommon.Address, faceValue *big.Int, winProb *big.Int, expirationBlock *big.Int, price *big.Rat, ticketExpirationParams *pm.TicketExpirationParams) *big.Int { h := hmac.New(sha256.New, e.secret[:]) - msg := append(seed.Bytes(), payer.Bytes()...) - msg = append(msg, faceValue.Bytes()...) - msg = append(msg, winProb.Bytes()...) - msg = append(msg, expirationBlock.Bytes()...) - msg = append(msg, price.Num().Bytes()...) - msg = append(msg, price.Denom().Bytes()...) + msg := payer.Bytes() + for _, value := range []*big.Int{seed, faceValue, winProb, expirationBlock, price.Num(), price.Denom()} { + field := value.Bytes() + msg = binary.AppendUvarint(msg, uint64(len(field))) + msg = append(msg, field...) + } msg = append(msg, ticketExpirationParams.AuxData()...) h.Write(msg) return new(big.Int).SetBytes(h.Sum(nil)) diff --git a/orchestrator/payment_recipient_test.go b/orchestrator/payment_recipient_test.go index cfae599..a954fef 100644 --- a/orchestrator/payment_recipient_test.go +++ b/orchestrator/payment_recipient_test.go @@ -30,10 +30,9 @@ import ( "github.com/stretchr/testify/require" ) -// These vectors were produced by running recipient.rand, expiration AuxData, -// and orchestrator.AuthToken extracted from the pinned go-livepeer revision. -// Those routines were authored by Yondon Fu and Nico Vergauwen; see payment_recipient.go. -func TestRecipientHMACMatchesGoLivepeer(t *testing.T) { +// The inputs and auth tokens come from the pinned go-livepeer vectors. The +// lottery values and commitments use Node's length-prefixed encoding. +func TestRecipientCommitmentVectors(t *testing.T) { data, err := os.ReadFile("testdata/recipient-hmac.json") require.NoError(t, err) var fixture struct { diff --git a/orchestrator/testdata/recipient-hmac.json b/orchestrator/testdata/recipient-hmac.json index 25c8a86..a116f76 100644 --- a/orchestrator/testdata/recipient-hmac.json +++ b/orchestrator/testdata/recipient-hmac.json @@ -13,8 +13,8 @@ "Session": "manifest", "Round": 5, "AuthExpiration": 2000000000, - "Random": "c9ea77c660280ee4b98869238e67b642270b03d3c754ce737fced0dbcc900cf3", - "Commitment": "0x919c6a0ded2b13dc2a36d35d86e95efe5485e491aaef48dad356a016c47fb394", + "Random": "ff358bf2cbddaf2731ae0397a1018ce3693d01c376d6dc082c514d17700267c7", + "Commitment": "0x49242636a44f588039c4cb5840f89f09b51b0feeb2aeb964590c80d62056c2f8", "Token": "d2913fedef229250d33b8075857113b8a2389003c8921d1e3f0dc7f47e5ffb8a" }, { @@ -28,8 +28,8 @@ "Session": "runner/session-2", "Round": 4096, "AuthExpiration": 2100000001, - "Random": "ea16f47ac2e48ed1198a2d9ef20a48806fad253d7332b65b1f0acf6e2ffe96d8", - "Commitment": "0x8bc2bc825f02abe55d7d86d821fab0391a79990babb8b03057aa80b2184d2308", + "Random": "9a9a8a054e88e2e29bf96a7a51bbe312f164c3feb3a3b5d03fa4e430beb3a4d2", + "Commitment": "0xa1ae3643bd37d74af5fb043afca30440aa17953fd7202ff9fe583feda1336c4c", "Token": "dbff885b3b27681d39f80efc1c001b62dabb4bd5c2025ea7f5794105ac67c016" }, { @@ -43,8 +43,8 @@ "Session": "s", "Round": 1, "AuthExpiration": 1, - "Random": "ce17e478b8864fc19e65f9102467916e0b9c16ec423789c275caa3e82306b292", - "Commitment": "0x6407d4377963bfd6fe062f8c3511196b776fff6e577b43e2f4297ac1ea623c24", + "Random": "6dedf64656cdd5c5d078166917173d4b31958c1860985971c724c51f0c5f0ab1", + "Commitment": "0xc1bae85c32eda3f9ac3f605db6399ee95198340d047b1b9f7accbd97e33d09d4", "Token": "1f06377654537f6a715d860457df6996630ec333f90178ea29b0bb6dd7fd6f5a" } ] From b53a13e2fc4ed884dcd162d8769a0ea9e3797e1e Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:50:47 -0800 Subject: [PATCH 6/8] Check full payment batches before admission Use the whole signed batch to check funding and queue capacity. Persist liability only for winning tickets. --- docs/orchestrator.md | 6 ++-- orchestrator/payment_engine.go | 4 ++- redemption/redeemer_db.go | 54 +++++++++++++++++++++------------- redemption/redeemer_db_test.go | 22 ++++++++++---- signer/payment_test.go | 2 +- 5 files changed, 58 insertions(+), 30 deletions(-) diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 31d40fc..457c256 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -146,9 +146,9 @@ starts from `TicketFaceValue` and caps the payout by the payer's deposit divided by `PayerDepositMultiplier` (default 1) and by the recipient's claimable reserve after locally known unsettled wins. Available reserve must cover every ticket winning in a fixed-price quote or a -metered session's ten-second opening batch. Node checks funding again when it -receives tickets. Later metered top-ups may have more tickets than the opening -batch. +metered session's ten-second opening batch. On receipt, Node checks that funding +and queue capacity can cover the full batch, including for metered top-ups. +Only winning tickets count toward outstanding liability after admission. Set `TicketFaceValue` high enough to cover typical redemption costs on your chain. The example config uses `2400000000000000` wei (0.0024 ETH), based on diff --git a/orchestrator/payment_engine.go b/orchestrator/payment_engine.go index 3a6972e..7a7d823 100644 --- a/orchestrator/payment_engine.go +++ b/orchestrator/payment_engine.go @@ -354,7 +354,9 @@ func (e *PaymentEngine) Receive(ctx context.Context, appID, manifest, paymentHea balance := new(big.Rat).Add(session.balance, batchCredit) var funding *redemption.ReceiptFunding if e.sizing != nil { - funding = &redemption.ReceiptFunding{Recipient: e.recipient, Reserve: funds.Reserve, FaceValue: params.FaceValue} + funding = &redemption.ReceiptFunding{ + Recipient: e.recipient, Reserve: funds.Reserve, FaceValue: params.FaceValue, BatchSize: len(payment.PayerParams), + } } if err := e.store.storeWinningTickets(ctx, payer, params.RecipientRandHash, funds, winners, funding); err != nil { return ethcommon.Address{}, nil, err diff --git a/redemption/redeemer_db.go b/redemption/redeemer_db.go index 163bbda..fea2da7 100644 --- a/redemption/redeemer_db.go +++ b/redemption/redeemer_db.go @@ -205,9 +205,10 @@ func (s *RedeemerDB) StoreWinningTickets(ctx context.Context, payer ethcommon.Ad type ReceiptFunding struct { Recipient ethcommon.Address Reserve, FaceValue *big.Int + BatchSize int } -// StoreFundedWinningTickets also checks the recipient's reserve when funding is present. +// StoreFundedWinningTickets checks the full batch when funding is present. func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcommon.Address, randHash ethcommon.Hash, collateral *big.Int, tickets []*pm.SignedTicket, snapshot pm.ChainSnapshot, funding *ReceiptFunding) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { @@ -230,23 +231,34 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom if exposed != 0 { return ErrExposedRandomness } + count := len(tickets) + var recipient ethcommon.Address + if count > 0 { + recipient = tickets[0].Recipient + } if funding != nil { - pending, err := unsettledLiability(ctx, tx, payer, funding.Recipient) - if err != nil { - return err - } - if len(tickets) == 0 { - pending.Add(pending, funding.FaceValue) + if funding.BatchSize < count || funding.BatchSize < 1 || funding.BatchSize > pm.MaxTicketBatchSize { + return errors.New("invalid receipt batch size") } - for _, ticket := range tickets { - pending.Add(pending, ticket.FaceValue) - } - if pending.Cmp(funding.Reserve) > 0 { - return pm.ErrPayerUnavailable + // Check worst-case exposure for the signed batch. Only actual winners + // are stored as liability. + count, recipient = funding.BatchSize, funding.Recipient + exposure := new(big.Int).Mul(funding.FaceValue, big.NewInt(int64(count))) + for _, limit := range []struct { + recipient ethcommon.Address + funds *big.Int + }{{recipient, funding.Reserve}, {ethcommon.Address{}, collateral}} { + pending, err := unsettledLiability(ctx, tx, payer, limit.recipient) + if err != nil { + return err + } + if pending.Add(pending, exposure).Cmp(limit.funds) > 0 { + return pm.ErrPayerUnavailable + } } } - if len(tickets) > 0 { - if err := s.capacity(ctx, tx, tickets[0].Recipient, len(tickets)); err != nil { + if count > 0 { + if err := s.capacity(ctx, tx, recipient, count); err != nil { return err } } @@ -255,12 +267,14 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom return err } } - pending, err := unsettledLiability(ctx, tx, payer, ethcommon.Address{}) - if err != nil { - return err - } - if pending.Cmp(collateral) > 0 { - return pm.ErrPayerUnavailable + if funding == nil { + pending, err := unsettledLiability(ctx, tx, payer, ethcommon.Address{}) + if err != nil { + return err + } + if pending.Cmp(collateral) > 0 { + return pm.ErrPayerUnavailable + } } if err := snapshot.Validate(); err != nil { return err diff --git a/redemption/redeemer_db_test.go b/redemption/redeemer_db_test.go index 497350a..8b2e3fc 100644 --- a/redemption/redeemer_db_test.go +++ b/redemption/redeemer_db_test.go @@ -264,14 +264,26 @@ func TestRedemptionRollbackPreservesTransactionProgress(t *testing.T) { } } -func TestAdaptiveReserveChecksEveryWinningTicket(t *testing.T) { +func TestAdaptiveAdmissionChecksFullBatch(t *testing.T) { f := newRecoveryRPC(t) s, ticket := f.store(t, 9) first, second := nextRecoveryTicket(ticket, 10), nextRecoveryTicket(ticket, 11) reserve := new(big.Int).Mul(ticket.FaceValue, big.NewInt(2)) collateral := new(big.Int).Mul(reserve, big.NewInt(10)) - funding := &ReceiptFunding{Recipient: ticket.Recipient, Reserve: reserve, FaceValue: ticket.FaceValue} - require.ErrorIs(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, first.RecipientRandHash, collateral, []*pm.SignedTicket{first, second}, f.CollateralSnapshot(), funding), pm.ErrPayerUnavailable) - require.NoError(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, first.RecipientRandHash, collateral, []*pm.SignedTicket{first}, f.CollateralSnapshot(), funding)) - require.ErrorIs(t, s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, second.RecipientRandHash, collateral, nil, f.CollateralSnapshot(), funding), pm.ErrPayerUnavailable) + funding := &ReceiptFunding{Recipient: ticket.Recipient, Reserve: reserve, FaceValue: ticket.FaceValue, BatchSize: 2} + admit := func(tickets []*pm.SignedTicket) error { + return s.StoreFundedWinningTickets(t.Context(), ticket.PayerAddress, first.RecipientRandHash, collateral, tickets, f.CollateralSnapshot(), funding) + } + for _, tickets := range [][]*pm.SignedTicket{nil, {first}, {first, second}} { + require.ErrorIs(t, admit(tickets), pm.ErrPayerUnavailable) + } + funding.Reserve.Add(funding.Reserve, ticket.FaceValue) + limits := s.limits + s.limits = Limits{Pending: 2, PerRecipient: 2} + require.ErrorIs(t, admit(nil), ErrCapacity) + s.limits = limits + require.NoError(t, admit([]*pm.SignedTicket{first})) + count, err := s.WinningTicketCount(ticket.PayerAddress) + require.NoError(t, err) + require.Equal(t, 2, count, "admission stores only actual wins") } diff --git a/signer/payment_test.go b/signer/payment_test.go index 39c3615..5566ad2 100644 --- a/signer/payment_test.go +++ b/signer/payment_test.go @@ -186,7 +186,7 @@ func TestAdaptiveQuotesWithSigner(t *testing.T) { open, err := s.preparePayment(t.Context(), "live", "live", live, paymentState{}, -1, now) require.NoError(t, err) require.Equal(t, 4, open.Usage.NumTickets) - chain.reserve = baseline - 1 + chain.reserve = baseline // A single payout still fits, but the opening batch does not. require.ErrorIs(t, receive(open), pm.ErrPayerUnavailable) chain.reserve = 1e16 require.NoError(t, receive(open)) From 0edb6c8e92779dbaca4b3429e53e4a7819d811e1 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 19:59:34 -0800 Subject: [PATCH 7/8] Set an Arbitrum redemption floor for ticket quotes Use the fixed redemption estimate on Arbitrum One when sizing initial quotes and exact-EV fallbacks. Keep the transaction-specific cost check at redemption. --- docs/orchestrator.md | 2 ++ orchestrator/app.go | 3 +++ orchestrator/ticket_sizing.go | 9 +++++++-- orchestrator/ticket_sizing_test.go | 18 ++++++++++++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 457c256..259a733 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -153,6 +153,8 @@ Only winning tickets count toward outstanding liability after admission. Set `TicketFaceValue` high enough to cover typical redemption costs on your chain. The example config uses `2400000000000000` wei (0.0024 ETH), based on a fixed Arbitrum redemption cost estimate of 0.000012 ETH and a 0.5% gas target. +On Arbitrum One, Node requires a payout above that estimated cost. The redeemer +checks the actual transaction cost estimate again before submitting. Fixed-price quotes use the fewest tickets that cover the price at the funded face value, up to 100. If rounding at an EV ceiling rules out every batch at diff --git a/orchestrator/app.go b/orchestrator/app.go index 8d72f6b..2b63bab 100644 --- a/orchestrator/app.go +++ b/orchestrator/app.go @@ -91,6 +91,9 @@ func (p Params) paymentsRequested() bool { func (p Params) ticketSizing() TicketSizing { sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + if p.ChainID != nil && *p.ChainID == 42161 { + sizing.MinFaceValue = arbitrumRedemptionFeeWei + 1 + } if p.MaxTicketEV != nil { sizing.MaxTicketEV = p.MaxTicketEV } diff --git a/orchestrator/ticket_sizing.go b/orchestrator/ticket_sizing.go index a099ebd..1d4ee62 100644 --- a/orchestrator/ticket_sizing.go +++ b/orchestrator/ticket_sizing.go @@ -14,8 +14,12 @@ import ( type TicketSizing struct { pm.PayerPolicy MeteredTicketSeconds int64 + MinFaceValue int64 } +// Fixed estimate from finalized Arbitrum One redemption receipts. +const arbitrumRedemptionFeeWei int64 = 12_000_000_000_000 + func (s TicketSizing) validate() error { if s.MeteredTicketSeconds < 1 { return errors.New("metered ticket duration must be positive") @@ -91,10 +95,11 @@ func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit ev *big.Rat } var exactQuotes []exactQuote + minimumFace := big.NewInt(max(1, s.MinFaceValue)) for count := int64(1); count <= pm.MaxTicketBatchSize; count++ { // Every ticket in the quoted batch may win. face := minBigInt(faceLimit, new(big.Int).Quo(reserve, big.NewInt(count))) - if face.Sign() == 0 { + if face.Cmp(minimumFace) < 0 { break } tickets := big.NewRat(count, 1) @@ -122,7 +127,7 @@ func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit feeDivisors := divisorsFromPrimes(primeFactors(fee.Num())) for _, quote := range exactQuotes { face := exactTicketFace(quote.ev, quote.faceLimit, feeDivisors) - if face != nil { + if face != nil && face.Cmp(minimumFace) >= 0 { if odds := selectTicketOdds(face, quote.ev, quote.ev, meteredEV); odds != nil { return face, odds, nil } diff --git a/orchestrator/ticket_sizing_test.go b/orchestrator/ticket_sizing_test.go index 8a423f5..d0d533b 100644 --- a/orchestrator/ticket_sizing_test.go +++ b/orchestrator/ticket_sizing_test.go @@ -121,6 +121,18 @@ func TestQuoteKeepsFundedFaceValueWhenBatchFits(t *testing.T) { require.Equal(t, 2, count) } +func TestArbitrumQuotesRequireFaceAboveEstimatedFee(t *testing.T) { + sizing := Params{ChainID: new(uint64(42161))}.ticketSizing() + baseline := big.NewInt(2_400_000_000_000_000) + reserve := big.NewInt(arbitrumRedemptionFeeWei) + _, _, err := sizing.ticketTerms(baseline, reserve, 1_000_000_000, "fixed") + require.ErrorIs(t, err, errQuoteUnpayable) + reserve.Add(reserve, big.NewInt(1)) + face, _, err := sizing.ticketTerms(baseline, reserve, 1_000_000_000, "fixed") + require.NoError(t, err) + require.Equal(t, reserve, face) +} + func TestExactTicketAtTightFundingLimit(t *testing.T) { const composite = 1_000_003 * 1_000_033 for _, tt := range []struct { @@ -139,6 +151,12 @@ func TestExactTicketAtTightFundingLimit(t *testing.T) { require.Equal(t, big.NewInt(tt.face), face) ev := new(big.Rat).SetFrac(new(big.Int).Mul(face, odds), maxWinProb) require.Zero(t, ev.Cmp(ceiling)) + + if tt.reserve == tt.limit { + sizing.MinFaceValue = tt.limit + _, _, err = sizing.ticketTerms(big.NewInt(tt.limit), big.NewInt(tt.reserve), tt.price, "fixed") + require.ErrorIs(t, err, errQuoteUnpayable, "exact odds must not reduce the face below the minimum") + } }) } } From 2b3e1bbcfc233c23933783e92223cf9d7f7135b7 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Fri, 4 Dec 2026 20:07:07 -0800 Subject: [PATCH 8/8] Use the same collateral limits for quotes and receipts Account for outstanding wins across recipients when quoting available payer collateral, using the same calculation as receipt admission. --- docs/orchestrator.md | 4 +++- orchestrator/payment_recipient_test.go | 22 ++++++++++++++++++++++ orchestrator/ticket_sizing.go | 13 ++++++------- redemption/redeemer_db.go | 17 ++++++----------- redemption/redemption_recovery_test.go | 17 +++++++++-------- redemption/state.go | 26 ++++++++++++++++++++++---- signer/payment_test.go | 6 +++--- 7 files changed, 71 insertions(+), 34 deletions(-) diff --git a/docs/orchestrator.md b/docs/orchestrator.md index 259a733..ea1e344 100644 --- a/docs/orchestrator.md +++ b/docs/orchestrator.md @@ -144,7 +144,9 @@ fixed request. Hourly discovery prices are normalized to USD and wei per second. Node sizes tickets when it issues or refreshes paid session parameters. It starts from `TicketFaceValue` and caps the payout by the payer's deposit divided by `PayerDepositMultiplier` (default 1) and by the recipient's claimable reserve -after locally known unsettled wins. +after locally known unsettled wins. The payer's deposit plus that reserve must +also cover the batch and their unsettled wins across all recipients in the +payment database. Available reserve must cover every ticket winning in a fixed-price quote or a metered session's ten-second opening batch. On receipt, Node checks that funding and queue capacity can cover the full batch, including for metered top-ups. diff --git a/orchestrator/payment_recipient_test.go b/orchestrator/payment_recipient_test.go index a954fef..32b023d 100644 --- a/orchestrator/payment_recipient_test.go +++ b/orchestrator/payment_recipient_test.go @@ -577,6 +577,28 @@ func TestAdaptiveChallengeAndRefreshFundingFailures(t *testing.T) { } } +func TestQuoteAccountsForOtherRecipientLiability(t *testing.T) { + legacy, chain, key, _ := newRecipientTestEngine(t) + info := issueRecipientParams(t, legacy, key) + var nonces []uint32 + for nonce := uint32(1); nonce <= 16; nonce++ { + nonces = append(nonces, nonce) + } + require.NoError(t, receiveRecipientPayment(t, legacy, key, info, nonces...)) + + chain.funds = func(_ context.Context, funds pm.PayerFunds) (pm.PayerFunds, error) { + funds.Deposit.SetInt64(100) + funds.Reserve.SetInt64(100) + return funds, nil + } + sizing := TicketSizing{PayerPolicy: pm.DefaultPayerPolicy(), MeteredTicketSeconds: 3} + engine, err := NewAdaptivePaymentEngine(legacy.store, chain, ethcommon.HexToAddress("0x5678"), big.NewInt(100), sizing) + require.NoError(t, err) + quote := issueRecipientParams(t, engine, key) + require.Equal(t, big.NewInt(40).Bytes(), quote.TicketParams.FaceValue) + require.NoError(t, receiveRecipientPayment(t, engine, key, quote, 1)) +} + func TestLiveChargeObservesOnlyDebitAttempts(t *testing.T) { e, _, key, _ := newRecipientTestEngine(t) e.metrics = observability.New("orchestrator") diff --git a/orchestrator/ticket_sizing.go b/orchestrator/ticket_sizing.go index 1d4ee62..181cee9 100644 --- a/orchestrator/ticket_sizing.go +++ b/orchestrator/ticket_sizing.go @@ -55,19 +55,18 @@ func (e *PaymentEngine) quoteTicket(ctx context.Context, payer common.Address, p if err := pm.ValidatePayerFunds(funds); err != nil { return pm.ChainSnapshot{}, nil, nil, fmt.Errorf("%w: %v", pm.ErrPayerUnavailable, err) } - pending, err := e.store.RecipientLiability(ctx, payer, e.recipient, funds.Snapshot) + available, err := e.store.AvailableCollateral(ctx, payer, e.recipient, funds) if err != nil { return pm.ChainSnapshot{}, nil, nil, err } - reserve := new(big.Int).Sub(funds.Reserve, pending) - if reserve.Sign() <= 0 { + if available.Sign() <= 0 { return pm.ChainSnapshot{}, nil, nil, pm.ErrPayerUnavailable } deposit := new(big.Int).Quo(funds.Deposit, big.NewInt(e.sizing.DepositMultiplier)) if deposit.Sign() <= 0 { return pm.ChainSnapshot{}, nil, nil, pm.ErrPayerUnavailable } - face, odds, err := e.sizing.ticketTerms(minBigInt(e.faceValue, deposit), reserve, price, unit) + face, odds, err := e.sizing.ticketTerms(minBigInt(e.faceValue, deposit), available, price, unit) return funds.Snapshot, face, odds, err } @@ -78,7 +77,7 @@ func minBigInt(a, b *big.Int) *big.Int { return b } -func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit string) (*big.Int, *big.Int, error) { +func (s TicketSizing) ticketTerms(faceLimit, available *big.Int, price int64, unit string) (*big.Int, *big.Int, error) { metered := unit == "seconds" fee := big.NewRat(price, 1) var meteredEV *big.Rat @@ -87,7 +86,7 @@ func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit fee.Mul(fee, big.NewRat(pm.InitialLivePaymentSeconds, 1)) } // A batch's EV is strictly below its total face value. - if fee.Cmp(s.MaxBatchEV) > 0 || fee.Num().Cmp(reserve) >= 0 { + if fee.Cmp(s.MaxBatchEV) > 0 || fee.Num().Cmp(available) >= 0 { return nil, nil, errQuoteUnpayable } type exactQuote struct { @@ -98,7 +97,7 @@ func (s TicketSizing) ticketTerms(faceLimit, reserve *big.Int, price int64, unit minimumFace := big.NewInt(max(1, s.MinFaceValue)) for count := int64(1); count <= pm.MaxTicketBatchSize; count++ { // Every ticket in the quoted batch may win. - face := minBigInt(faceLimit, new(big.Int).Quo(reserve, big.NewInt(count))) + face := minBigInt(faceLimit, new(big.Int).Quo(available, big.NewInt(count))) if face.Cmp(minimumFace) < 0 { break } diff --git a/redemption/redeemer_db.go b/redemption/redeemer_db.go index fea2da7..2c44da4 100644 --- a/redemption/redeemer_db.go +++ b/redemption/redeemer_db.go @@ -244,17 +244,12 @@ func (s *RedeemerDB) StoreFundedWinningTickets(ctx context.Context, payer ethcom // are stored as liability. count, recipient = funding.BatchSize, funding.Recipient exposure := new(big.Int).Mul(funding.FaceValue, big.NewInt(int64(count))) - for _, limit := range []struct { - recipient ethcommon.Address - funds *big.Int - }{{recipient, funding.Reserve}, {ethcommon.Address{}, collateral}} { - pending, err := unsettledLiability(ctx, tx, payer, limit.recipient) - if err != nil { - return err - } - if pending.Add(pending, exposure).Cmp(limit.funds) > 0 { - return pm.ErrPayerUnavailable - } + available, err := availableCollateral(ctx, tx, payer, recipient, funding.Reserve, collateral) + if err != nil { + return err + } + if exposure.Cmp(available) > 0 { + return pm.ErrPayerUnavailable } } if count > 0 { diff --git a/redemption/redemption_recovery_test.go b/redemption/redemption_recovery_test.go index 4f3f6e0..56b7a7c 100644 --- a/redemption/redemption_recovery_test.go +++ b/redemption/redemption_recovery_test.go @@ -1011,12 +1011,13 @@ func TestCollateralWatermarkSurvivesSettlementAndRestart(t *testing.T) { admit := func(snapshot eth.ChainSnapshot) error { return store.StoreWinningTickets(t.Context(), ticket.PayerAddress, next.RecipientRandHash, new(big.Int).Set(ticket.FaceValue), []*pm.SignedTicket{next}, snapshot) } - liability := func(snapshot eth.ChainSnapshot) (*big.Int, error) { - return store.RecipientLiability(t.Context(), ticket.PayerAddress, ticket.Recipient, snapshot) + availableCollateral := func(snapshot eth.ChainSnapshot) (*big.Int, error) { + funds := pm.PayerFunds{Deposit: ticket.FaceValue, Reserve: ticket.FaceValue, Snapshot: snapshot} + return store.AvailableCollateral(t.Context(), ticket.PayerAddress, ticket.Recipient, funds) } - pending, err := liability(captured) + available, err := availableCollateral(captured) require.NoError(t, err) - require.Equal(t, ticket.FaceValue, pending) + require.Zero(t, available.Sign()) require.ErrorContains(t, store.finishTicket(t.Context(), ticket.Sig, "used", ""), "block evidence required") _, err = store.db.Exec(`CREATE TRIGGER fail_settlement BEFORE UPDATE OF redeemed_at ON winning_tickets BEGIN SELECT RAISE(ABORT,'storage failure'); END`) require.NoError(t, err) @@ -1038,13 +1039,13 @@ func TestCollateralWatermarkSurvivesSettlementAndRestart(t *testing.T) { wrongFork := settled wrongFork.BlockHash = common.HexToHash("0xbad") require.ErrorIs(t, admit(wrongFork), pm.ErrPayerUnavailable) - _, err = liability(captured) + _, err = availableCollateral(captured) require.ErrorIs(t, err, eth.ErrObservationUnavailable) - _, err = liability(wrongFork) + _, err = availableCollateral(wrongFork) require.ErrorIs(t, err, eth.ErrObservationUnavailable) - pending, err = liability(settled) + available, err = availableCollateral(settled) require.NoError(t, err) - require.Zero(t, pending.Sign()) + require.Equal(t, ticket.FaceValue, available) require.ErrorContains(t, store.finishTicket(t.Context(), ticket.Sig, "used", "", wrongFork), "conflicting finalized") require.NoError(t, admit(settled), "post-settlement collateral can cover the next winner") require.Error(t, admit(settled), "durable settlement must retain signature replay protection") diff --git a/redemption/state.go b/redemption/state.go index 30fe7fa..d32705f 100644 --- a/redemption/state.go +++ b/redemption/state.go @@ -346,8 +346,8 @@ func (s *RedeemerDB) delivery(ctx context.Context, t *pm.SignedTicket, phase str return err } -// RecipientLiability reads pending wins against the same collateral watermark. -func (s *RedeemerDB) RecipientLiability(ctx context.Context, payer, recipient common.Address, snapshot pm.ChainSnapshot) (*big.Int, error) { +// AvailableCollateral checks both funding limits against the same settlement watermark. +func (s *RedeemerDB) AvailableCollateral(ctx context.Context, payer, recipient common.Address, funds pm.PayerFunds) (*big.Int, error) { tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) if err != nil { return nil, err @@ -358,10 +358,28 @@ func (s *RedeemerDB) RecipientLiability(ctx context.Context, payer, recipient co if err := tx.QueryRowContext(ctx, "SELECT number,hash FROM (SELECT 1) LEFT JOIN collateral_watermark ON id=1").Scan(&number, &hash); err != nil { return nil, err } - if !coversCollateralWatermark(snapshot, number, hash) { + if !coversCollateralWatermark(funds.Snapshot, number, hash) { return nil, eth.ErrObservationUnavailable } - return unsettledLiability(ctx, tx, payer, recipient) + collateral := new(big.Int).Add(funds.Deposit, funds.Reserve) + return availableCollateral(ctx, tx, payer, recipient, funds.Reserve, collateral) +} + +func availableCollateral(ctx context.Context, tx *sql.Tx, payer, recipient common.Address, reserve, collateral *big.Int) (*big.Int, error) { + recipientPending, err := unsettledLiability(ctx, tx, payer, recipient) + if err != nil { + return nil, err + } + payerPending, err := unsettledLiability(ctx, tx, payer, common.Address{}) + if err != nil { + return nil, err + } + recipientAvailable := recipientPending.Sub(reserve, recipientPending) + payerAvailable := payerPending.Sub(collateral, payerPending) + if recipientAvailable.Cmp(payerAvailable) < 0 { + return recipientAvailable, nil + } + return payerAvailable, nil } func unsettledLiability(ctx context.Context, tx *sql.Tx, payer, recipient common.Address) (*big.Int, error) { diff --git a/signer/payment_test.go b/signer/payment_test.go index 5566ad2..b728f95 100644 --- a/signer/payment_test.go +++ b/signer/payment_test.go @@ -200,11 +200,11 @@ func TestAdaptiveQuotesWithSigner(t *testing.T) { } _, err = s.preparePayment(t.Context(), "live", "live", live, open.State, 0, now.Add(303*time.Second)) require.Error(t, err) - snapshot, err := chain.Snapshot(t.Context()) + funds, err := chain.PayerFunds(t.Context(), key.Address(), liveRecipient) require.NoError(t, err) - pending, err := store.RecipientLiability(t.Context(), key.Address(), liveRecipient, snapshot) + available, err := store.AvailableCollateral(t.Context(), key.Address(), liveRecipient, funds) require.NoError(t, err) - chain.reserve = baseline/2 + pending.Int64() + chain.reserve = baseline/2 + funds.Reserve.Int64() - available.Int64() _, err = engine.RefreshChallenge(t.Context(), "live", key.Address(), "https://orch.example") require.NoError(t, err) refreshed, err := engine.ChallengeInfo("live")