Skip to content
6 changes: 5 additions & 1 deletion cmd/livepeer/testdata/cli/orchestrator-help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 9 additions & 6 deletions configs/orchestrator/config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -43,10 +43,13 @@ 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"
# 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
# PayerDepositMultiplier = 1

# Remote redemption: set a public recipient address and omit local wallet/tx settings.
# OrchestratorAddress = "0xYOUR_REGISTERED_ORCHESTRATOR"
Expand Down
29 changes: 27 additions & 2 deletions docs/orchestrator.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` /
Expand All @@ -142,6 +141,32 @@ 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. 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. 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.
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
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
`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
Expand Down
51 changes: 41 additions & 10 deletions orchestrator/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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"`
Expand All @@ -80,7 +85,28 @@ 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.ChainID != nil && *p.ChainID == 42161 {
sizing.MinFaceValue = arbitrumRedemptionFeeWei + 1
}
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 {
Expand All @@ -107,8 +133,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 {
Expand All @@ -127,11 +153,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")
Expand Down Expand Up @@ -298,6 +327,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) {
Expand Down Expand Up @@ -423,9 +454,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
Expand Down
3 changes: 3 additions & 0 deletions orchestrator/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,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"
Expand Down
3 changes: 2 additions & 1 deletion orchestrator/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
20 changes: 18 additions & 2 deletions orchestrator/payment.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading