diff --git a/.dockerignore b/.dockerignore index 0c9bb2c..4ed50b4 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,6 +16,7 @@ !orchestrator/ !pm/ !redeemer/ +!rewardcaller/ !redemption/ !signer/ !trickle/ diff --git a/.github/scripts/docker-smoke.sh b/.github/scripts/docker-smoke.sh index ab5f9b0..2265a64 100644 --- a/.github/scripts/docker-smoke.sh +++ b/.github/scripts/docker-smoke.sh @@ -23,7 +23,7 @@ docker run --rm --network none --read-only --cap-drop=ALL \ cd /tmp expected="livepeer $1 ($2)" test "$(livepeer version)" = "$expected" - for component in orchestrator signer chain discovery redeemer; do + for component in orchestrator signer chain discovery redeemer reward-caller; do test "$("livepeer-$component" --version)" = "livepeer-$component version $expected" test "$(livepeer "$component" --version)" = "livepeer-$component version $expected" "livepeer-$component" --help > direct-help diff --git a/.github/scripts/release-smoke.sh b/.github/scripts/release-smoke.sh index f4fd143..2394920 100644 --- a/.github/scripts/release-smoke.sh +++ b/.github/scripts/release-smoke.sh @@ -28,7 +28,7 @@ export PATH=/tmp/install/bin:/usr/bin:/bin unset GOROOT GOPATH GOTOOLCHAIN GOENV GOWORK GOFLAGS test "$(livepeer version)" = "livepeer $version ($commit)" -for component in orchestrator signer chain discovery redeemer; do +for component in orchestrator signer chain discovery redeemer reward-caller; do "livepeer-$component" --version | grep -F "livepeer $version ($commit)" livepeer "$component" --version | grep -F "livepeer $version ($commit)" "livepeer-$component" --help > direct-help diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index aa91ce9..375f094 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -87,7 +87,7 @@ jobs: cache-from: type=gha,scope=docker-${{ matrix.arch }} - name: Verify static binaries run: | - for binary in livepeer livepeer-orchestrator livepeer-signer livepeer-chain livepeer-discovery livepeer-redeemer; do + for binary in livepeer livepeer-orchestrator livepeer-signer livepeer-chain livepeer-discovery livepeer-redeemer livepeer-reward-caller; do path="$RUNNER_TEMP/bin/$binary" # A static ELF must have neither an interpreter nor shared-library dependencies. readelf --program-headers "$path" > "$RUNNER_TEMP/program-headers" diff --git a/Makefile b/Makefile index 70a0dfb..c8481db 100644 --- a/Makefile +++ b/Makefile @@ -14,6 +14,7 @@ build: $(GO) build -ldflags '$(LDFLAGS)' -o bin/livepeer-chain ./cmd/livepeer-chain $(GO) build -ldflags '$(LDFLAGS)' -o bin/livepeer-discovery ./cmd/livepeer-discovery $(GO) build -ldflags '$(LDFLAGS)' -o bin/livepeer-redeemer ./cmd/livepeer-redeemer + $(GO) build -ldflags '$(LDFLAGS)' -o bin/livepeer-reward-caller ./cmd/livepeer-reward-caller test: $(GO) test -race ./... diff --git a/README.md b/README.md index 60b403c..03cae94 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ protocol commands for the Livepeer network. | `livepeer` | Runs the bundled component commands. | | `livepeer-orchestrator` | Registers runners, reserves sessions, proxies traffic, and redeems payment tickets. | | `livepeer-redeemer` | Accepts winning tickets from orchestrators and redeems them using a dedicated wallet. | +| `livepeer-reward-caller` | Calls reward every round for orchestrators that authorized its dedicated wallet. | | `livepeer-discovery` | Collects and caches orchestrator runner inventories without running an orchestrator. | | `livepeer-signer` | Signs identities and payments, discovers orchestrators, and optionally publishes accounting events. | | `livepeer-chain` | Inspects accounts and contracts, manages wallets, staking, earnings, funds, and governance, and signs files locally. | diff --git a/chain/actions.go b/chain/actions.go index 7804d1a..45ff0bb 100644 --- a/chain/actions.go +++ b/chain/actions.go @@ -404,6 +404,13 @@ func (p RewardParams) actions() ([]action, error) { if target == from { return contractAction("bondingManager", "reward"), nil } + caller, err := s.Call(ctx, "bondingManager", "transcoderToRewardCaller", target) + if err != nil { + return nil, err + } + if caller[0].(common.Address) != from { + return nil, fmt.Errorf("%s is not the reward caller for %s; the orchestrator must run 'livepeer chain orchestrator reward-caller set %s --submit'", from.Hex(), target.Hex(), from.Hex()) + } return contractAction("bondingManager", "rewardForTranscoder", target), nil }), nil } diff --git a/chain/management_test.go b/chain/management_test.go index 6c0f41f..9dc7a79 100644 --- a/chain/management_test.go +++ b/chain/management_test.go @@ -568,8 +568,13 @@ func TestNoOpsAndPrerequisiteErrors(t *testing.T) { }) } f := newManagementFixture(t) - f.failSimulation = "rewardForTranscoderWithHint" _, err := f.run(t, "reward", "call", "--orchestrator", "0x0000000000000000000000000000000000001234") + require.ErrorContains(t, err, "is not the reward caller for 0x0000000000000000000000000000000000001234") + require.Empty(t, f.simulations, "an unauthorized caller is refused before simulation") + f = newManagementFixture(t) + f.reads["transcoderToRewardCaller"] = []any{common.HexToAddress(testAccount)} + f.failSimulation = "rewardForTranscoderWithHint" + _, err = f.run(t, "reward", "call", "--orchestrator", "0x0000000000000000000000000000000000001234") require.ErrorContains(t, err, "simulation failed") } diff --git a/cmd/livepeer-reward-caller/main.go b/cmd/livepeer-reward-caller/main.go new file mode 100644 index 0000000..13daf6f --- /dev/null +++ b/cmd/livepeer-reward-caller/main.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "os" + + "github.com/livepeer/node/rewardcaller" +) + +func main() { + if err := rewardcaller.Root(os.Stdout, os.Stderr).Execute(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } +} diff --git a/cmd/livepeer/imports_test.go b/cmd/livepeer/imports_test.go index 54fb97d..611391c 100644 --- a/cmd/livepeer/imports_test.go +++ b/cmd/livepeer/imports_test.go @@ -72,9 +72,10 @@ func forbiddenImport(file, dep string) string { if local == "discovery/shared" { return "" } - for _, component := range []string{"orchestrator", "signer", "chain", "discovery", "redeemer"} { + // Package directory -> component command name. + for component, command := range map[string]string{"orchestrator": "orchestrator", "signer": "signer", "chain": "chain", "discovery": "discovery", "redeemer": "redeemer", "rewardcaller": "reward-caller"} { if local == component || strings.HasPrefix(local, component+"/") { - if strings.HasPrefix(file, "cmd/livepeer-"+component+"/") || strings.HasPrefix(file, component+"/") { + if strings.HasPrefix(file, "cmd/livepeer-"+command+"/") || strings.HasPrefix(file, component+"/") { continue } return "cross-component or shared-to-component import" diff --git a/cmd/livepeer/integration_test.go b/cmd/livepeer/integration_test.go index 659311c..0ae3791 100644 --- a/cmd/livepeer/integration_test.go +++ b/cmd/livepeer/integration_test.go @@ -40,7 +40,7 @@ func TestRealBinaryOffchainFlow(t *testing.T) { require.True(t, ok) root := filepath.Clean(filepath.Join(filepath.Dir(file), "../..")) install := t.TempDir() - for _, name := range []string{"livepeer", "livepeer-orchestrator", "livepeer-signer", "livepeer-chain", "livepeer-discovery", "livepeer-redeemer"} { + for _, name := range []string{"livepeer", "livepeer-orchestrator", "livepeer-signer", "livepeer-chain", "livepeer-discovery", "livepeer-redeemer", "livepeer-reward-caller"} { build := exec.Command("go", "build", "-o", filepath.Join(install, name), "./cmd/"+name) build.Dir = root output, err := build.CombinedOutput() @@ -56,7 +56,7 @@ func TestRealBinaryOffchainFlow(t *testing.T) { completion, err := exec.Command(dispatcher, "completion", "orchestrator", "bash").CombinedOutput() require.NoError(t, err, string(completion)) require.Contains(t, string(completion), "bash completion") - for _, component := range []string{"orchestrator", "signer", "chain", "discovery", "redeemer"} { + for _, component := range []string{"orchestrator", "signer", "chain", "discovery", "redeemer", "reward-caller"} { direct := filepath.Join(install, "livepeer-"+component) for _, arguments := range [][]string{{"--help"}, {"completion", "bash"}, {"completion", "zsh"}, {"completion", "fish"}, {"completion", "powershell"}} { actual, err := exec.Command(direct, arguments...).CombinedOutput() diff --git a/cmd/livepeer/main.go b/cmd/livepeer/main.go index 43721b7..7cf5389 100644 --- a/cmd/livepeer/main.go +++ b/cmd/livepeer/main.go @@ -29,11 +29,11 @@ func run(args []string) int { return 0 case "completion": if len(args) < 2 { - fmt.Fprintln(os.Stderr, "usage: livepeer completion ") + fmt.Fprintln(os.Stderr, "usage: livepeer completion ") return 2 } return dispatch(args[1], append([]string{"completion"}, args[2:]...)) - case "orchestrator", "signer", "chain", "discovery", "redeemer": + case "orchestrator", "signer", "chain", "discovery", "redeemer", "reward-caller": return dispatch(args[0], args[1:]) default: fmt.Fprintf(os.Stderr, "unknown livepeer command %q\n", args[0]) @@ -43,7 +43,7 @@ func run(args []string) int { } func usage() { - fmt.Fprintln(os.Stdout, "Usage: livepeer [args...]") + fmt.Fprintln(os.Stdout, "Usage: livepeer [args...]") fmt.Fprintln(os.Stdout) fmt.Fprintln(os.Stdout, "Run 'livepeer help ' for component options.") } @@ -68,7 +68,7 @@ func bundledExecutable(component string) (string, error) { func dispatch(component string, args []string) int { switch component { - case "orchestrator", "signer", "chain", "discovery", "redeemer": + case "orchestrator", "signer", "chain", "discovery", "redeemer", "reward-caller": default: fmt.Fprintf(os.Stderr, "unknown livepeer component %q\n", component) return 2 diff --git a/cmd/livepeer/testdata/cli/reward-caller-completion-bash.golden b/cmd/livepeer/testdata/cli/reward-caller-completion-bash.golden new file mode 100644 index 0000000..5a3eef9 --- /dev/null +++ b/cmd/livepeer/testdata/cli/reward-caller-completion-bash.golden @@ -0,0 +1 @@ +626c93e08f0cb1bc7e392315dabaf3c8be4d1b0ad02608bc0c6c9e525fd8a550 diff --git a/cmd/livepeer/testdata/cli/reward-caller-completion-fish.golden b/cmd/livepeer/testdata/cli/reward-caller-completion-fish.golden new file mode 100644 index 0000000..f3bf82d --- /dev/null +++ b/cmd/livepeer/testdata/cli/reward-caller-completion-fish.golden @@ -0,0 +1 @@ +724beb5c5f6f0dc7e5b8001dca422a3ce1dc70d7344e844a59495d81a3f629b2 diff --git a/cmd/livepeer/testdata/cli/reward-caller-completion-powershell.golden b/cmd/livepeer/testdata/cli/reward-caller-completion-powershell.golden new file mode 100644 index 0000000..5b47dca --- /dev/null +++ b/cmd/livepeer/testdata/cli/reward-caller-completion-powershell.golden @@ -0,0 +1 @@ +93772964f1e2f435a9dd454ce0c21a0ac0a74dd8f2bc7c228948cee2061bf10f diff --git a/cmd/livepeer/testdata/cli/reward-caller-completion-zsh.golden b/cmd/livepeer/testdata/cli/reward-caller-completion-zsh.golden new file mode 100644 index 0000000..12b18ea --- /dev/null +++ b/cmd/livepeer/testdata/cli/reward-caller-completion-zsh.golden @@ -0,0 +1 @@ +3a2d03ae3df69f2d59495c5ce4e82b7068e5e3c61c43e4341d200ea6328f328c diff --git a/cmd/livepeer/testdata/cli/reward-caller-help.golden b/cmd/livepeer/testdata/cli/reward-caller-help.golden new file mode 100644 index 0000000..fe0483a --- /dev/null +++ b/cmd/livepeer/testdata/cli/reward-caller-help.golden @@ -0,0 +1,28 @@ +Standalone delegated reward caller + +Usage: + livepeer-reward-caller [flags] + +Flags: + -c, --config string Configuration file; empty disables discovery (env: LIVEPEER_REWARD_CALLER_CONFIG) (default "config.toml") + -n, --network string Network name (custom networks require explicit chain settings) (env: LIVEPEER_REWARD_CALLER_NETWORK) (default "arbitrum-one-mainnet") + -d, --data-dir string Component data directory; defaults to ~/.lpData// (env: LIVEPEER_REWARD_CALLER_DATA_DIR) (default "$HOME/.lpData/arbitrum-one-mainnet/reward-caller") + -m, --metrics-listen string Metrics and probe listener (env: LIVEPEER_REWARD_CALLER_METRICS_LISTEN) (default "127.0.0.1:8943") + -a, --account string Dedicated reward caller wallet; must not be an orchestrator or hold bonded stake (env: LIVEPEER_REWARD_CALLER_ACCOUNT) + -o, --orchestrators strings Orchestrator addresses that authorized this wallet as their reward caller (env: LIVEPEER_REWARD_CALLER_ORCHESTRATORS) + -k, --keystore-file string Encrypted geth reward caller account JSON file (env: LIVEPEER_REWARD_CALLER_KEYSTORE_FILE) + --keystore-password-file string Owner-only file containing exact password bytes (env: LIVEPEER_REWARD_CALLER_KEYSTORE_PASSWORD_FILE) + --rpc-url-file string (env: LIVEPEER_REWARD_CALLER_RPC_URL_FILE) + --chain-id uint (env: LIVEPEER_REWARD_CALLER_CHAIN_ID) + --controller-address string (env: LIVEPEER_REWARD_CALLER_CONTROLLER_ADDRESS) + -p, --poll-interval duration Interval between reward checks (env: LIVEPEER_REWARD_CALLER_POLL_INTERVAL) (default 1m0s) + --reward-tx-timeout duration Transaction inclusion timeout (env: LIVEPEER_REWARD_CALLER_REWARD_TX_TIMEOUT) (default 5m0s) + --reward-max-tx-replacements int Maximum fee replacements per transaction (env: LIVEPEER_REWARD_CALLER_REWARD_MAX_TX_REPLACEMENTS) (default 1) + --reward-max-fee-per-gas string Optional maximum fee in wei per gas (env: LIVEPEER_REWARD_CALLER_REWARD_MAX_FEE_PER_GAS) + --print-config[=true|false] Print audited redacted TOML configuration + -h, --help[=true|false] help for livepeer-reward-caller + -v, --version[=true|false] version for livepeer-reward-caller + +Environment Variables: + LIVEPEER_REWARD_CALLER_KEYSTORE_PASSWORD Keystore decryption password + LIVEPEER_REWARD_CALLER_RPC_URL diff --git a/configs/reward-caller/config.example.toml b/configs/reward-caller/config.example.toml new file mode 100644 index 0000000..0b1e3b7 --- /dev/null +++ b/configs/reward-caller/config.example.toml @@ -0,0 +1,18 @@ +# Use a dedicated wallet: not a registered or active orchestrator, with no bonded stake. +# Each orchestrator authorizes it once from its own wallet: +# livepeer chain orchestrator reward-caller set 0xYOUR_DEDICATED_WALLET --submit +Network = "arbitrum-one-mainnet" +MetricsListen = "127.0.0.1:8943" +# DataDir = "/var/lib/livepeer/reward-caller" +# Account = "0xYOUR_DEDICATED_WALLET" # Select among shared keystore accounts. +KeystoreFile = "/run/secrets/livepeer-reward-caller-keystore.json" +KeystorePasswordFile = "/run/secrets/livepeer-reward-caller-password" +RPCURLFile = "/run/secrets/livepeer-rpc-url" +Orchestrators = ["0xYOUR_ORCHESTRATOR"] +# Files containing credentials must be owner-only. Password bytes are exact. +# ChainID = 42161 +# Controller = "0xD8E8328501E9645d16Cf49539efC04f734606ee4" +PollInterval = "1m" +RewardTxTimeout = "5m" +RewardMaxTxReplacements = 1 +# RewardMaxFeePerGas = "1000000000" # Optional ceiling, wei per gas. diff --git a/docs/README.md b/docs/README.md index 4b0c71b..6a820e6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,6 +10,7 @@ Start with [installation](../README.md#install) and the | [Configuration and secrets](configuration.md) | Set TOML, environment variables, flags, and credentials. | | [Orchestrator](orchestrator.md) | Register runners, configure networking and proxies, and enable payments. | | [Standalone redeemer](redeemer.md) | Redeem winning tickets using a dedicated wallet and configure orchestrator forwarding. | +| [Reward caller](reward-caller.md) | Call reward every round for orchestrators from a dedicated, delegated wallet. | | [Discovery](discovery.md) | Collect and advertise orchestrator inventories without local runners or payments. | | [Signer](signer.md) | Configure price limits, authorization, discovery, and Kafka accounting. | | [Chain commands](chain.md) | Inspect accounts, manage stake and funds, and submit transactions. | diff --git a/docs/chain.md b/docs/chain.md index 719effe..17ecaab 100644 --- a/docs/chain.md +++ b/docs/chain.md @@ -128,7 +128,10 @@ governance proposal vote ID against|for|abstain [--reason TEXT] Claims default to the current round, which must be initialized. Unbonding and fee withdrawal claim earnings automatically. Fee withdrawals default to the configured account as recipient. Reward calls also default to the configured -account; the target must be active and the caller authorized. +account; the target must be active and the caller authorized, which is checked +before simulation. To call reward every round, run a +[reward caller](reward-caller.md) with a dedicated wallet rather than scheduling +this command with the orchestrator wallet. ## Sign files locally diff --git a/docs/configuration.md b/docs/configuration.md index 3624988..adc7b25 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -5,7 +5,8 @@ commands read only their relevant settings. Use the [orchestrator](../configs/orchestrator/config.example.toml), [signer](../configs/signer/config.example.toml), [discovery](../configs/discovery/config.example.toml), -[redeemer](../configs/redeemer/config.example.toml), and +[redeemer](../configs/redeemer/config.example.toml), +[reward caller](../configs/reward-caller/config.example.toml), and [chain](../configs/chain/config.example.toml) examples as starting points. ## Select configuration and storage @@ -15,7 +16,7 @@ are ignored. Select a file with `--config FILE` or the component's `CONFIG` environment variable. An explicit config can set `Network` and `DataDir`. `--config=""` disables config discovery. -`Network` defaults to `arbitrum-one-mainnet` for chain, signer, redeemer, and the +`Network` defaults to `arbitrum-one-mainnet` for chain, signer, redeemer, reward caller, and the orchestrator's `redemptions` and `migrate` commands. The orchestrator service defaults to `offchain`. Arbitrum supplies chain, Controller, and ETH/USD feed defaults. Custom networks require explicit chain and Controller settings. @@ -96,7 +97,7 @@ Redeemer webhook URL and headers files must be owner-only regular files. ## Ethereum keystores -Chain, signer, redeemer, and orchestrators redeeming locally discover geth +Chain, signer, redeemer, reward caller, and orchestrators redeeming locally discover geth accounts in the keystore directory described above. A sole account is selected automatically; use `Account` / `--account` to select among accounts or `KeystoreFile` / `--keystore-file` to bypass discovery. @@ -110,7 +111,7 @@ Keystore and password files must be regular files readable only by their owner; target files meet these requirements. Password files follow the exact-byte rules above; supply an empty file for a keystore without a password. -Signer, redeemer, and orchestrators redeeming locally require these credentials +Signer, redeemer, reward caller, and orchestrators redeeming locally require these credentials at startup; chain needs them for submissions and local signing. Credential changes require a restart or a new chain invocation. diff --git a/docs/metrics.md b/docs/metrics.md index 945f9af..16591d3 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -85,6 +85,7 @@ gauges; timestamps use Unix seconds. Most event families appear on first use. | 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. | | 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. | +| Reward caller | `reward_caller_checks_total{orchestrator,outcome}`, `reward_caller_last_reward_round{orchestrator}`, `reward_caller_authorized{orchestrator}`, `reward_caller_gas_balance_eth`, `reward_caller_last_pass_timestamp_seconds`; see [reward caller](reward-caller.md#probes-and-metrics). | | 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`. | | Outbox | Existing `signer_kafka_pending_events`, `signer_kafka_pending_bytes`, `signer_kafka_oldest_event_age_seconds`, `signer_kafka_outbox_healthy`, `signer_kafka_publish_errors_total`, `signer_kafka_enqueue_errors_total`, and `signer_kafka_storage_errors_total`. New `signer_kafka_delivered_events_total` and `signer_kafka_last_delivery_timestamp_seconds` follow successful local acknowledgement; delivery remains at least once. | | Redemption queue | `redemption_queue_tickets{state}`, `redemption_oldest_ticket_timestamp_seconds{state}`: parameter-expiry `waiting`, clock-eligible `eligible`, `in_flight`, `awaiting_finality`, rejected remote submissions (`rejected`), invalid or reverted local attempts (`blocked`), or `unknown` without a fresh clock observation. Each logical ticket counts once, regardless of signatures or replacements. | diff --git a/docs/reward-caller.md b/docs/reward-caller.md new file mode 100644 index 0000000..7de5d04 --- /dev/null +++ b/docs/reward-caller.md @@ -0,0 +1,74 @@ +# Running a reward caller + +A reward caller calls reward every round for one or more orchestrators from a +dedicated wallet, so no orchestrator key stays unlocked on a machine. It uses +delegated reward calls: each orchestrator authorizes the wallet once, and the +service only ever calls `rewardForTranscoder`, never `reward`. + +The wallet must not be a registered or active orchestrator and must hold no +bonded stake. The service refuses to start otherwise, checks again every pass, +and checks the signer of every transaction before broadcasting it. Fund the +wallet with a small amount of ETH for gas. + +## Set up + +1. Create the wallet; see [keystore setup](configuration.md#prepare-a-keystore): + + ```sh + livepeer chain account create + ``` + +2. Authorize it from each orchestrator wallet, once: + + ```sh + livepeer chain orchestrator reward-caller set 0xREWARD_CALLER_WALLET --submit + ``` + +3. List the orchestrators in + [the example configuration](../configs/reward-caller/config.example.toml), + set the wallet's keystore and RPC connection, then run: + + ```sh + livepeer reward-caller --config /etc/livepeer/reward-caller.toml + ``` + +Startup fails if no listed orchestrator authorizes the wallet. Orchestrators +that have not authorized it are skipped and logged with the command to fix it. + +## How it works + +Every `PollInterval` (default `1m`) the service checks the listed orchestrators +in order. It skips an orchestrator whose reward caller is no longer this wallet, +that is inactive, that was already rewarded this round, or whose round is not +initialized yet. Otherwise it simulates, signs, broadcasts, and waits for the +delegated reward call, replacing the fee up to `RewardMaxTxReplacements` times. + +State is read from the chain on every pass, so restarts are safe and no database +is needed. The service does not initialize rounds; reward calls wait until +someone has. + +## Probes and metrics + +`MetricsListen` defaults to `127.0.0.1:8943` and serves `/healthz`, `/readyz`, +and `/metrics`. Readiness requires a dedicated wallet with a positive gas +balance, at least one orchestrator that authorizes it, and a recent pass. + +| Metric | Meaning | +| --- | --- | +| `reward_caller_checks_total{orchestrator,outcome}` | One per orchestrator per pass: `rewarded`, `already_rewarded`, `round_not_initialized`, `inactive`, `unauthorized`, or `failed`. | +| `reward_caller_last_reward_round{orchestrator}` | Last round rewarded onchain. | +| `reward_caller_authorized{orchestrator}` | `1` while the orchestrator authorizes this wallet. | +| `reward_caller_gas_balance_eth` | Wallet balance. | +| `reward_caller_last_pass_timestamp_seconds` | Completion time of the last pass. | + +Alert on growing `failed` outcomes, an active orchestrator whose last reward +round stays behind late in a round, or a low gas balance. Failure logs carry a +`stage` (`status`, `simulate`, `sign`, `broadcast`, or `confirm`) and an +`error_kind`. + +## Manual reward calls + +`livepeer chain reward call` still works with an orchestrator wallet for a +one-off call. Do not schedule it with the orchestrator wallet; that leaves the +key and its password on the machine. Run this service with a dedicated wallet +instead. diff --git a/eth/contracts.go b/eth/contracts.go index d1dbc1a..ca42c99 100644 --- a/eth/contracts.go +++ b/eth/contracts.go @@ -233,6 +233,17 @@ func (c *Contracts) SetNonceFloor(address ethcommon.Address, floor uint64) { state.next = max(state.next, floor) } +// ResetNonceReservation makes the next Prepare for address use the pending nonce +// the RPC reports. Only a sender that prepares one transaction at a time may call +// it after a failed submission: a transaction the node accepted is already in its +// pending count, and one it never received leaves no nonce gap. +func (c *Contracts) ResetNonceReservation(address ethcommon.Address) { + state := c.nonceState(address) + state.Lock() + defer state.Unlock() + state.next = 0 +} + type SignedTransaction struct { Hash ethcommon.Hash Raw []byte diff --git a/eth/rewardcaller.go b/eth/rewardcaller.go new file mode 100644 index 0000000..88f16af --- /dev/null +++ b/eth/rewardcaller.go @@ -0,0 +1,96 @@ +package eth + +import ( + "context" + "errors" + "math/big" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" +) + +var ( + ErrDedicatedWalletIsOrchestrator = errors.New("wallet is registered or active as an orchestrator") + ErrDedicatedWalletHasStake = errors.New("wallet has bonded stake") +) + +// CheckDedicatedWallet refuses an account that controls stake: a registered or +// active orchestrator, or any account with bonded stake. It is service policy, +// not a protocol restriction; BondingManager accepts reward calls from any +// authorized caller. +func (c *Contracts) CheckDedicatedWallet(ctx context.Context, account common.Address) error { + s, err := c.Inspect(ctx) + if err != nil { + return err + } + bonding, err := s.bonding(ctx) + if err != nil { + return err + } + opts := &bind.CallOpts{Context: ctx} + registered, err := bonding.IsRegisteredTranscoder(opts, account) + if err != nil { + return err + } + active, err := bonding.IsActiveTranscoder(opts, account) + if err != nil { + return err + } + if registered || active { + return ErrDedicatedWalletIsOrchestrator + } + delegator, err := bonding.GetDelegator(opts, account) + if err != nil { + return err + } + if delegator.BondedAmount.Sign() > 0 { + return ErrDedicatedWalletHasStake + } + return nil +} + +// RewardStatus is one orchestrator's reward state at a single canonical block. +type RewardStatus struct { + Round *big.Int + Initialized bool + Active bool + LastRewardRound *big.Int + RewardCaller common.Address +} + +// Rewarded reports whether reward was already called for the current round. +func (s RewardStatus) Rewarded() bool { return s.LastRewardRound.Cmp(s.Round) >= 0 } + +func (c *Contracts) RewardStatus(ctx context.Context, orchestrator common.Address) (RewardStatus, error) { + var result RewardStatus + s, err := c.Inspect(ctx) + if err != nil { + return result, err + } + if result.Round, err = s.number(ctx, "roundsManager", "currentRound"); err != nil { + return result, err + } + initialized, err := s.Call(ctx, "roundsManager", "currentRoundInitialized") + if err != nil { + return result, err + } + var ok bool + if result.Initialized, ok = initialized[0].(bool); !ok { + return result, errors.New("invalid round initialization result") + } + bonding, err := s.bonding(ctx) + if err != nil { + return result, err + } + opts := &bind.CallOpts{Context: ctx} + if result.Active, err = bonding.IsActiveTranscoder(opts, orchestrator); err != nil { + return result, err + } + transcoder, err := bonding.GetTranscoder(opts, orchestrator) + if err != nil { + return result, err + } + result.LastRewardRound = transcoder.LastRewardRound + result.RewardCaller, err = bonding.TranscoderToRewardCaller(opts, orchestrator) + return result, err +} diff --git a/eth/rewardcaller_test.go b/eth/rewardcaller_test.go new file mode 100644 index 0000000..d54de27 --- /dev/null +++ b/eth/rewardcaller_test.go @@ -0,0 +1,110 @@ +package eth + +import ( + "encoding/json" + "math/big" + "strings" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" +) + +type rewardChain struct { + registered, active, initialized bool + bonded, round, lastReward int64 + rewardCaller common.Address +} + +func rewardChainContracts(t *testing.T, state rewardChain) *Contracts { + t.Helper() + controller, bonding, rounds := common.HexToAddress("0x2000"), common.HexToAddress("0x2001"), common.HexToAddress("0x2002") + boolean := func(v bool) string { + if v { + return "0x" + word(1) + } + return "0x" + word(0) + } + rpc := testRPC(t, func(method string, params []json.RawMessage) any { + switch method { + case "eth_getBlockByNumber": + return &types.Header{Number: big.NewInt(1), Difficulty: new(big.Int), BaseFee: big.NewInt(1)} + case "eth_call": + default: + t.Fatalf("unexpected RPC method %s", method) + } + var call struct { + To common.Address + Input string + } + require.NoError(t, json.Unmarshal(params[0], &call)) + require.NotEqual(t, `"pending"`, string(params[1]), "reads must not simulate") + sig := func(s string) bool { return strings.HasPrefix(call.Input, calldata(s)) } + switch { + case call.To == controller: + for name, address := range map[string]common.Address{"BondingManager": bonding, "RoundsManager": rounds} { + if call.Input == calldata("getContract(bytes32)", hexutil.Encode(crypto.Keccak256([]byte(name)))[2:]) { + return "0x" + addressWord(address) + } + } + case sig("isRegisteredTranscoder(address)"): + return boolean(state.registered) + case sig("isActiveTranscoder(address)"): + return boolean(state.active) + case sig("getDelegator(address)"): + return "0x" + word(state.bonded) + strings.Repeat(word(0), 6) + case sig("currentRound()"): + require.Equal(t, rounds, call.To) + return "0x" + word(state.round) + case sig("currentRoundInitialized()"): + return boolean(state.initialized) + case sig("getTranscoder(address)"): + return "0x" + word(state.lastReward) + strings.Repeat(word(0), 9) + case sig("transcoderToRewardCaller(address)"): + require.Equal(t, bonding, call.To) + return "0x" + addressWord(state.rewardCaller) + } + t.Fatalf("unexpected contract call %s", call.Input) + return nil + }) + c, err := NewContracts(rpc, controller) + require.NoError(t, err) + return c +} + +func TestCheckDedicatedWallet(t *testing.T) { + wallet := common.HexToAddress("0x0100") + for _, tc := range []struct { + name string + state rewardChain + want error + }{ + {"dedicated", rewardChain{}, nil}, + {"registered orchestrator", rewardChain{registered: true}, ErrDedicatedWalletIsOrchestrator}, + {"active orchestrator", rewardChain{active: true}, ErrDedicatedWalletIsOrchestrator}, + {"delegator", rewardChain{bonded: 1}, ErrDedicatedWalletHasStake}, + } { + t.Run(tc.name, func(t *testing.T) { + err := rewardChainContracts(t, tc.state).CheckDedicatedWallet(t.Context(), wallet) + if tc.want == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tc.want) + } + }) + } +} + +func TestRewardStatus(t *testing.T) { + caller := common.HexToAddress("0x0100") + c := rewardChainContracts(t, rewardChain{active: true, initialized: true, round: 9, lastReward: 8, rewardCaller: caller}) + status, err := c.RewardStatus(t.Context(), common.HexToAddress("0x1003")) + require.NoError(t, err) + require.Equal(t, RewardStatus{Round: big.NewInt(9), Initialized: true, Active: true, LastRewardRound: big.NewInt(8), RewardCaller: caller}, status) + require.False(t, status.Rewarded()) + status.LastRewardRound = big.NewInt(9) + require.True(t, status.Rewarded()) +} diff --git a/internal/test/redemptionrpc.go b/internal/test/redemptionrpc.go index 078528b..a8b71d2 100644 --- a/internal/test/redemptionrpc.go +++ b/internal/test/redemptionrpc.go @@ -51,6 +51,10 @@ type RedemptionRPC struct { NonceBarrier chan struct{} ReceiptHeader *types.Header Server *httptest.Server + // Delegated reward reads; the orchestrator is any address but Wallet. + RewardCaller common.Address + Bonded, LastRewardRound int64 + RoundUninitialized bool } // Header returns the same latest execution header served by the fixture. @@ -116,6 +120,24 @@ func (f *RedemptionRPC) Serve(w http.ResponseWriter, r *http.Request) { result = fmt.Sprintf("0x%064x", 1) } } + if selector("getDelegator(address)") { + result = fmt.Sprintf("0x%064x%s", f.Bonded, strings.Repeat(fmt.Sprintf("%064x", 0), 6)) + } + if selector("currentRoundInitialized()") && f.RoundUninitialized { + result = fmt.Sprintf("0x%064x", 0) + } + if selector("getTranscoder(address)") { + result = fmt.Sprintf("0x%064x%s", f.LastRewardRound, strings.Repeat(fmt.Sprintf("%064x", 0), 9)) + } + if selector("getTranscoderEarningsPoolForRound(address,uint256)") { + result = fmt.Sprintf("0x%064x%s", 1, strings.Repeat(fmt.Sprintf("%064x", 0), 4)) + } + if selector("transcoderToRewardCaller(address)") { + result = fmt.Sprintf("0x%064x", f.RewardCaller.Bytes()) + } + if selector("getNextTranscoderInPool(address)") { + result = fmt.Sprintf("0x%064x", 0) + } if selector("usedTickets(bytes32)") { hash := common.HexToHash("0x" + call.Input[10:]) Used := f.Used[hash] diff --git a/nodeconfig/config.go b/nodeconfig/config.go index df23d41..4a7c164 100644 --- a/nodeconfig/config.go +++ b/nodeconfig/config.go @@ -61,7 +61,7 @@ func defaultDataDir(network, component string) (string, error) { // Command applies shared source and discovery policy using Boa's merge pipeline. // Parameters must embed Settings or PersistentSettings. func Command[P any](component, network string, cmd boa.Cmd[P], config *string) boa.Cmd[P] { - cmd.ParamEnrich = boa.ParamEnricherCombine(boa.ParamEnricherDefault, boa.ParamEnricherEnv, boa.ParamEnricherEnvPrefix("LIVEPEER_"+strings.ToUpper(component)), + cmd.ParamEnrich = boa.ParamEnricherCombine(boa.ParamEnricherDefault, boa.ParamEnricherEnv, boa.ParamEnricherEnvPrefix("LIVEPEER_"+strings.ReplaceAll(strings.ToUpper(component), "-", "_")), func(_ []boa.Parameter, param boa.Parameter, name string) error { if param.IsBaseDir() { if dir, err := defaultDataDir(network, component); err == nil { diff --git a/rewardcaller/app.go b/rewardcaller/app.go new file mode 100644 index 0000000..d37ec59 --- /dev/null +++ b/rewardcaller/app.go @@ -0,0 +1,307 @@ +// Package rewardcaller runs the standalone delegated reward-calling service. +package rewardcaller + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "math/big" + "net" + "net/http" + "net/url" + "os/signal" + "slices" + "sync" + "syscall" + "time" + + "github.com/BurntSushi/toml" + "github.com/ethereum/go-ethereum/common" + "github.com/holiman/uint256" + "github.com/j0sh/boa/pkg/boa" + "github.com/livepeer/node/cmd/version" + "github.com/livepeer/node/destination" + "github.com/livepeer/node/eth" + "github.com/livepeer/node/internal/observability" + "github.com/livepeer/node/nodeconfig" + "github.com/spf13/cobra" +) + +type Params struct { + ConfigFile string `name:"config" configfile:"optional-default" basepath:"source" default:"config.toml" boa:"noconfig" descr:"Configuration file; empty disables discovery"` + nodeconfig.Settings + MetricsListen boa.HTTPBind `default:"127.0.0.1:8943" descr:"Metrics and probe listener"` + Account *common.Address `descr:"Dedicated reward caller wallet; must not be an orchestrator or hold bonded stake"` + Orchestrators []string `optional:"true" descr:"Orchestrator addresses that authorized this wallet as their reward caller"` + KeystoreFile string `basepath:"source" optional:"true" descr:"Encrypted geth reward caller account JSON file"` + KeystorePassword *string `secret:"true" optional:"true" descr:"Keystore decryption password"` + KeystorePasswordFile string `basepath:"source" secretfor:"KeystorePassword" descr:"Owner-only file containing exact password bytes"` + RPCURL *url.URL `name:"rpc-url" secret:"true" optional:"true"` + RPCURLFile string `basepath:"source" name:"rpc-url-file" secretfor:"RPCURL"` + ChainID *uint64 `min:"1"` + Controller *common.Address `name:"controller-address"` + PollInterval time.Duration `default:"1m" descr:"Interval between reward checks"` + RewardTxTimeout time.Duration `default:"5m" descr:"Transaction inclusion timeout"` + RewardMaxTxReplacements int `default:"1" min:"0" descr:"Maximum fee replacements per transaction"` + RewardMaxFeePerGas *uint256.Int `descr:"Optional maximum fee in wei per gas"` + PrintConfig bool `optional:"true" boa:"noconfig,noenv" descr:"Print audited redacted TOML configuration"` +} + +func (p Params) Validate() error { + if p.Network == "offchain" { + return errors.New("reward caller requires an on-chain network") + } + if p.ChainID == nil || *p.ChainID == 0 || p.Controller == nil || *p.Controller == (common.Address{}) { + return errors.New("reward caller requires chain-id and controller-address") + } + if p.KeystorePassword == nil && p.KeystorePasswordFile == "" { + return errors.New("reward caller requires a keystore password or password file") + } + if !p.MetricsListen.IsValid() { + return errors.New("metrics-listen requires an IP:port address") + } + if err := destination.ValidateURL(p.RPCURL); err != nil { + return errors.New("reward caller requires a valid RPC URL") + } + if _, err := p.orchestrators(); err != nil { + return err + } + if p.PollInterval < time.Second || p.RewardTxTimeout <= 0 || p.RewardMaxTxReplacements < 0 { + return errors.New("poll interval must be at least 1s; transaction timeout must be positive and replacements nonnegative") + } + if p.RewardMaxFeePerGas != nil && p.RewardMaxFeePerGas.IsZero() { + return errors.New("maximum reward fee must be positive") + } + return nil +} + +func (p Params) orchestrators() ([]common.Address, error) { + if len(p.Orchestrators) == 0 { + return nil, errors.New("reward caller requires at least one orchestrator address") + } + addresses := make([]common.Address, 0, len(p.Orchestrators)) + for _, text := range p.Orchestrators { + if !common.IsHexAddress(text) || common.HexToAddress(text) == (common.Address{}) { + return nil, fmt.Errorf("invalid orchestrator address %q", text) + } + address := common.HexToAddress(text) + if slices.Contains(addresses, address) { + return nil, fmt.Errorf("duplicate orchestrator address %s", address) + } + addresses = append(addresses, address) + } + return addresses, nil +} + +func Root(out, errOut io.Writer) *cobra.Command { + p := new(Params) + cmd := nodeconfig.Command("reward-caller", nodeconfig.Mainnet, boa.Cmd[Params]{Use: "livepeer-reward-caller", Short: "Standalone delegated reward caller", Version: version.String(), Params: p, RejectUnknown: true, Args: cobra.NoArgs, + PostConfigFuncCtx: func(ctx *boa.HookContext, p *Params, _ *cobra.Command, _ []string) error { + if p.Network == nodeconfig.Mainnet { + nodeconfig.Default(ctx, &p.ChainID, new(uint64(42161))) + nodeconfig.Default(ctx, &p.Controller, new(nodeconfig.Controller)) + } + return nil + }, RunFuncCtxE: func(ctx *boa.HookContext, p *Params, cmd *cobra.Command, _ []string) error { + if p.PrintConfig { + return toml.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{"Network": p.Network, "MetricsListen": p.MetricsListen.String(), "Account": p.Account, "Orchestrators": p.Orchestrators, "ChainID": p.ChainID, "Controller": p.Controller, "PollInterval": p.PollInterval.String(), "RewardTxTimeout": p.RewardTxTimeout.String(), "RewardMaxTxReplacements": p.RewardMaxTxReplacements, "RewardMaxFeePerGas": p.RewardMaxFeePerGas}) + } + if err := p.Validate(); err != nil { + return boa.NewUserInputError(err) + } + return Serve(cmd.Context(), *p, cmd.ErrOrStderr()) + }}, &p.ConfigFile).ToCobra() + cmd.SetOut(out) + cmd.SetErr(errOut) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.InitDefaultCompletionCmd() + return cmd +} + +func authorizationHint(wallet common.Address) string { + return fmt.Sprintf("run 'livepeer chain orchestrator reward-caller set %s --submit' with the orchestrator wallet", wallet.Hex()) +} + +func Serve(parent context.Context, p Params, logOut io.Writer) (result error) { + if err := p.Validate(); err != nil { + return err + } + orchestrators, _ := p.orchestrators() + ctx, cancel := signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM) + defer cancel() + logger := slog.New(slog.NewTextHandler(logOut, nil)).With("component", "reward-caller") + metrics := observability.New("reward-caller") + key, err := eth.OpenAccount(p.KeystoreDir(), p.KeystoreFile, p.KeystorePassword, p.KeystorePasswordFile, p.Account) + if err != nil { + return fmt.Errorf("open reward caller wallet: %w", err) + } + wallet := key.Address() + if slices.Contains(orchestrators, wallet) { + return fmt.Errorf("reward caller wallet %s is a configured orchestrator; use a dedicated wallet", wallet) + } + rpc, err := eth.NewRPC(p.RPCURL, nil) + if err != nil { + return err + } + defer rpc.Close() + rpc.SetObserver(metrics.RPC) + id := new(big.Int).SetUint64(*p.ChainID) + if err = rpc.CheckChainID(ctx, id); err != nil { + return err + } + contracts, err := eth.NewContracts(rpc, *p.Controller) + if err != nil { + return err + } + if p.RewardMaxFeePerGas != nil { + contracts.MaxFeePerGas = p.RewardMaxFeePerGas.ToBig() + } + if err = contracts.CheckDedicatedWallet(ctx, wallet); err != nil { + return fmt.Errorf("check dedicated reward caller wallet: %w", err) + } + authorized := 0 + for _, orchestrator := range orchestrators { + status, err := contracts.RewardStatus(ctx, orchestrator) + if err != nil { + return fmt.Errorf("read reward status for %s: %w", orchestrator, err) + } + if status.RewardCaller == wallet { + authorized++ + continue + } + logger.Warn("orchestrator has not authorized this wallet; skipping it", "event", "unauthorized", "orchestrator", orchestrator, "reward_caller", status.RewardCaller, "fix", authorizationHint(wallet)) + } + if authorized == 0 { + return fmt.Errorf("no configured orchestrator authorizes %s as its reward caller; %s", wallet, authorizationHint(wallet)) + } + contracts.BeforeBroadcast = broadcastPolicy(contracts, id) + caller := protocol{Contracts: contracts, key: key, chainID: id, wait: eth.WaitOptions{Timeout: p.RewardTxTimeout, MaxReplacements: uint64(p.RewardMaxTxReplacements)}} + + // A pass may wait for every transaction, including fee replacements. + staleAfter := 2*p.PollInterval + time.Duration(len(orchestrators)*(p.RewardMaxTxReplacements+1))*p.RewardTxTimeout + var status struct { + sync.Mutex + completed time.Time + ready bool + } + isReady := func() bool { + status.Lock() + defer status.Unlock() + return status.ready && time.Since(status.completed) < staleAfter + } + metricListener, err := net.Listen("tcp", p.MetricsListen.String()) + if err != nil { + return err + } + defer metricListener.Close() + probe := http.NewServeMux() + probe.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok\n") }) + probe.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) { + if !isReady() { + http.Error(w, "reward caller dependencies unavailable", http.StatusServiceUnavailable) + return + } + _, _ = io.WriteString(w, "ready\n") + }) + probe.Handle("GET /metrics", metrics.Handler()) + server := &http.Server{Handler: probe, ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 1 << 16, MaxHeaderValueCount: 128} + var workers sync.WaitGroup + errs := make(chan error, 1) + workers.Go(func() { errs <- server.Serve(metricListener) }) + workers.Go(func() { + ticker := time.NewTicker(p.PollInterval) + defer ticker.Stop() + previous := map[common.Address]string{} + for { + work := eth.WithRPCWork(ctx, "background") + check, done := context.WithTimeout(work, 30*time.Second) + walletErr := contracts.CheckDedicatedWallet(check, wallet) + done() + var results []rewardCheck + if walletErr != nil { + reason := observability.ErrorKind(walletErr) + if errors.Is(walletErr, eth.ErrDedicatedWalletIsOrchestrator) || errors.Is(walletErr, eth.ErrDedicatedWalletHasStake) { + reason = "wallet_not_dedicated" + } + logger.Error("reward caller wallet check failed; skipping pass", "event", "wallet_check", "error_kind", reason) + } else { + results = pass(work, caller, wallet, orchestrators) + } + for _, r := range results { + labels := observability.Labels{"orchestrator": r.Orchestrator.Hex()} + metrics.Add("reward_caller_checks_total", 1, labels.With("outcome", r.Outcome)) + if r.Round != nil { + metrics.Gauge("reward_caller_authorized", labels).Set(observability.Bool(r.Outcome != outcomeUnauthorized)) + } + if r.LastRewardRound != nil { + metrics.Gauge("reward_caller_last_reward_round", labels).Set(float64(r.LastRewardRound.Uint64())) + } + logResult(logger, r, previous[r.Orchestrator], wallet) + previous[r.Orchestrator] = r.Outcome + } + check, done = context.WithTimeout(work, 15*time.Second) + balance, balanceErr := rpc.BalanceAt(check, wallet, nil) + done() + funded := balanceErr == nil && balance.Sign() > 0 + if balanceErr == nil { + metrics.Gauge("reward_caller_gas_balance_eth", nil).Set(observability.ETH(new(big.Rat).SetInt(balance))) + } + status.Lock() + status.completed = time.Now() + status.ready = walletErr == nil && funded && authorizedCount(results) > 0 + status.Unlock() + metrics.Gauge("reward_caller_last_pass_timestamp_seconds", nil).Set(float64(time.Now().Unix())) + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } + }) + logger.Info("reward caller started", "event", "started", "wallet", wallet, "orchestrators", len(orchestrators), "authorized", authorized, "metrics_listen", p.MetricsListen) + select { + case <-ctx.Done(): + case err := <-errs: + if !errors.Is(err, http.ErrServerClosed) { + result = err + } + } + cancel() + shutdown, done := context.WithTimeout(context.Background(), 15*time.Second) + defer done() + if err = server.Shutdown(shutdown); err != nil { + result = errors.Join(result, err) + _ = server.Close() + } + workers.Wait() + return result +} + +// logResult logs transactions and failures every time, and steady states only +// when they change, so a skipped orchestrator does not log every poll. +func logResult(logger *slog.Logger, r rewardCheck, previous string, wallet common.Address) { + attrs := []any{"event", "reward_check", "orchestrator", r.Orchestrator, "outcome", r.Outcome} + if r.Round != nil { + attrs = append(attrs, "round", r.Round.String()) + } + switch r.Outcome { + case outcomeRewarded: + logger.Info("called reward", append(attrs, "transaction", r.Transaction)...) + case outcomeFailed: + if r.Transaction != (common.Hash{}) { + attrs = append(attrs, "transaction", r.Transaction) + } + logger.Error("reward check failed", append(attrs, "stage", failureStage(r.Err), "error_kind", observability.ErrorKind(r.Err))...) + case outcomeUnauthorized: + if previous != r.Outcome { + logger.Warn("orchestrator has not authorized this wallet; skipping it", append(attrs, "fix", authorizationHint(wallet))...) + } + default: + if previous != r.Outcome { + logger.Info("reward state changed", attrs...) + } + } +} diff --git a/rewardcaller/app_test.go b/rewardcaller/app_test.go new file mode 100644 index 0000000..9fbde5c --- /dev/null +++ b/rewardcaller/app_test.go @@ -0,0 +1,272 @@ +package rewardcaller + +import ( + "bytes" + "context" + "errors" + "io" + "math/big" + "net" + "net/http" + "net/url" + "sync" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/j0sh/boa/pkg/boa" + "github.com/livepeer/node/eth" + "github.com/livepeer/node/internal/test" + "github.com/livepeer/node/nodeconfig" + "github.com/stretchr/testify/require" +) + +var orchestrator = common.HexToAddress("0x1003") + +type fakeChain struct { + status map[common.Address]eth.RewardStatus + err error + reward error + calls []common.Address +} + +func (f *fakeChain) RewardStatus(_ context.Context, a common.Address) (eth.RewardStatus, error) { + return f.status[a], f.err +} + +func (f *fakeChain) Reward(_ context.Context, a common.Address) (common.Hash, error) { + f.calls = append(f.calls, a) + return common.HexToHash("0xabc"), f.reward +} + +func TestPassOutcomes(t *testing.T) { + wallet := common.HexToAddress("0x0100") + ready := eth.RewardStatus{Round: big.NewInt(9), Initialized: true, Active: true, LastRewardRound: big.NewInt(8), RewardCaller: wallet} + with := func(change func(*eth.RewardStatus)) eth.RewardStatus { + s := ready + change(&s) + return s + } + for _, tc := range []struct { + name string + status eth.RewardStatus + err error + reward error + outcome string + calls int + stage string + }{ + {"rewards once per round", ready, nil, nil, outcomeRewarded, 1, ""}, + {"not authorized or revoked", with(func(s *eth.RewardStatus) { s.RewardCaller = common.HexToAddress("0x0200") }), nil, nil, outcomeUnauthorized, 0, ""}, + {"inactive", with(func(s *eth.RewardStatus) { s.Active = false }), nil, nil, outcomeInactive, 0, ""}, + {"already rewarded", with(func(s *eth.RewardStatus) { s.LastRewardRound = big.NewInt(9) }), nil, nil, outcomeAlreadyRewarded, 0, ""}, + {"round not initialized", with(func(s *eth.RewardStatus) { s.Initialized = false }), nil, nil, outcomeUninitialized, 0, ""}, + {"status unavailable", ready, errors.New("rpc down"), nil, outcomeFailed, 0, "status"}, + {"transaction fails", ready, nil, stageError{"confirm", errors.New("transaction reverted")}, outcomeFailed, 1, "confirm"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeChain{status: map[common.Address]eth.RewardStatus{orchestrator: tc.status}, err: tc.err, reward: tc.reward} + results := pass(t.Context(), f, wallet, []common.Address{orchestrator}) + require.Len(t, results, 1) + require.Equal(t, tc.outcome, results[0].Outcome) + require.Len(t, f.calls, tc.calls) + if tc.stage != "" { + require.Equal(t, tc.stage, failureStage(results[0].Err)) + } else { + require.NoError(t, results[0].Err) + } + if tc.outcome == outcomeRewarded { + require.Equal(t, big.NewInt(9), results[0].LastRewardRound) + } + }) + } +} + +func bindAddress(t *testing.T) boa.HTTPBind { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + address := listener.Addr().String() + require.NoError(t, listener.Close()) + var bind boa.HTTPBind + require.NoError(t, bind.UnmarshalText([]byte(address))) + return bind +} + +func serviceParams(t *testing.T, f *test.RedemptionRPC) Params { + t.Helper() + file, password := test.WriteFixedKeystore(t) + key, err := eth.OpenKeystoreFile(file, password) + require.NoError(t, err) + f.Mu.Lock() + f.Wallet, f.RewardCaller = key.Address(), key.Address() + f.Mu.Unlock() + rpc, err := url.Parse(f.Server.URL) + require.NoError(t, err) + id := uint64(1) + controller := common.HexToAddress("0x1000") + return Params{Settings: nodeconfig.Settings{Network: "test", DataDir: t.TempDir()}, MetricsListen: bindAddress(t), Orchestrators: []string{orchestrator.Hex()}, KeystoreFile: file, KeystorePasswordFile: password, RPCURL: rpc, ChainID: &id, Controller: &controller, PollInterval: time.Second, RewardTxTimeout: time.Second, RewardMaxTxReplacements: 1} +} + +func TestValidateOrchestrators(t *testing.T) { + f := test.NewRedemptionRPC(t) + for _, tc := range []struct { + orchestrators []string + error string + }{ + {nil, "at least one orchestrator"}, + {[]string{"not-an-address"}, "invalid orchestrator address"}, + {[]string{common.Address{}.Hex()}, "invalid orchestrator address"}, + {[]string{orchestrator.Hex(), orchestrator.Hex()}, "duplicate orchestrator"}, + } { + p := serviceParams(t, f) + p.Orchestrators = tc.orchestrators + require.ErrorContains(t, p.Validate(), tc.error) + } + p := serviceParams(t, f) + p.PollInterval = time.Millisecond + require.ErrorContains(t, p.Validate(), "poll interval") + require.NoError(t, serviceParams(t, f).Validate()) +} + +func TestServeRefusesWalletsThatControlStake(t *testing.T) { + for _, tc := range []struct { + name string + setup func(*test.RedemptionRPC, *Params) + error string + }{ + {"registered orchestrator", func(f *test.RedemptionRPC, _ *Params) { f.Registered = true }, "registered or active as an orchestrator"}, + {"active orchestrator", func(f *test.RedemptionRPC, _ *Params) { f.WalletActive = true }, "registered or active as an orchestrator"}, + {"delegator", func(f *test.RedemptionRPC, _ *Params) { f.Bonded = 1 }, "bonded stake"}, + {"configured as an orchestrator", func(f *test.RedemptionRPC, p *Params) { + p.Orchestrators = append(p.Orchestrators, f.Wallet.Hex()) + }, "is a configured orchestrator"}, + {"no orchestrator authorizes it", func(f *test.RedemptionRPC, _ *Params) { f.RewardCaller = common.HexToAddress("0x0200") }, "reward-caller set"}, + {"wrong chain", func(_ *test.RedemptionRPC, p *Params) { *p.ChainID = 2 }, "chain"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := test.NewRedemptionRPC(t) + p := serviceParams(t, f) + f.Mu.Lock() + tc.setup(f, &p) + f.Mu.Unlock() + require.ErrorContains(t, Serve(t.Context(), p, io.Discard), tc.error) + require.Empty(t, f.Transactions(), "refused wallets never sign") + }) + } +} + +func TestServeCallsRewardOncePerRound(t *testing.T) { + f := test.NewRedemptionRPC(t) + p := serviceParams(t, f) + f.Mu.Lock() + f.MineAfter = 1 + f.OnSend = func(*types.Transaction) { f.LastRewardRound = f.Round } // OnSend runs under f.Mu. + f.Mu.Unlock() + ctx, cancel := context.WithCancel(t.Context()) + var logs safeBuffer + done := make(chan error, 1) + go func() { done <- Serve(ctx, p, &logs) }() + ready := func() bool { + response, err := http.Get("http://" + p.MetricsListen.String() + "/readyz") + if err != nil { + return false + } + _ = response.Body.Close() + return response.StatusCode == http.StatusOK + } + require.Eventually(t, ready, 5*time.Second, 20*time.Millisecond, "logs: %s", logs.String()) + sent := f.Transactions() + require.Len(t, sent, 1) + require.True(t, bytes.HasPrefix(sent[0].Data(), rewardForTranscoder), "only delegated reward is sent") + signer := types.LatestSignerForChainID(big.NewInt(1)) + sender, err := types.Sender(signer, sent[0]) + require.NoError(t, err) + require.Equal(t, f.Wallet, sender) + require.Contains(t, logs.String(), "called reward") + + // The next pass sees the round rewarded and sends nothing. + time.Sleep(1500 * time.Millisecond) + require.Len(t, f.Transactions(), 1) + require.Contains(t, logs.String(), "outcome=already_rewarded") + cancel() + require.NoError(t, <-done) +} + +func TestBroadcastPolicy(t *testing.T) { + f := test.NewRedemptionRPC(t) + p := serviceParams(t, f) + key, err := eth.OpenKeystoreFile(p.KeystoreFile, p.KeystorePasswordFile) + require.NoError(t, err) + rpc, err := eth.NewRPC(p.RPCURL, nil) + require.NoError(t, err) + t.Cleanup(rpc.Close) + contracts, err := eth.NewContracts(rpc, *p.Controller) + require.NoError(t, err) + bonding, err := contracts.Resolve(t.Context(), "bondingManager") + require.NoError(t, err) + id := big.NewInt(1) + policy := broadcastPolicy(contracts, id) + sign := func(to common.Address, data []byte, chainID *big.Int) *types.Transaction { + tx, err := key.SignTxForChain(types.NewTx(&types.DynamicFeeTx{ChainID: chainID, To: &to, Data: data, Gas: 21000, GasFeeCap: big.NewInt(1), GasTipCap: big.NewInt(1)}), chainID) + require.NoError(t, err) + return tx + } + reward := append(append([]byte{}, rewardForTranscoder...), make([]byte, 96)...) + require.NoError(t, policy(t.Context(), sign(bonding, reward, id))) + require.ErrorContains(t, policy(t.Context(), sign(common.HexToAddress("0x9999"), reward, id)), "only broadcasts") + require.ErrorContains(t, policy(t.Context(), sign(bonding, []byte{0x22, 0x8c, 0xb7, 0x33}, id)), "only broadcasts") + require.ErrorContains(t, policy(t.Context(), sign(bonding, reward, big.NewInt(2))), "chain mismatch") + f.Mu.Lock() + f.Registered = true + f.Mu.Unlock() + require.ErrorIs(t, policy(t.Context(), sign(bonding, reward, id)), eth.ErrDedicatedWalletIsOrchestrator) +} + +type safeBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *safeBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *safeBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func TestRewardReusesNonceAfterRejectedBroadcast(t *testing.T) { + f := test.NewRedemptionRPC(t) + p := serviceParams(t, f) + key, err := eth.OpenKeystoreFile(p.KeystoreFile, p.KeystorePasswordFile) + require.NoError(t, err) + rpc, err := eth.NewRPC(p.RPCURL, nil) + require.NoError(t, err) + t.Cleanup(rpc.Close) + contracts, err := eth.NewContracts(rpc, *p.Controller) + require.NoError(t, err) + caller := protocol{Contracts: contracts, key: key, chainID: big.NewInt(1), wait: eth.WaitOptions{Timeout: time.Second}} + f.Mu.Lock() + f.RejectNext, f.MineAfter = true, 2 + f.Mu.Unlock() + _, err = caller.Reward(t.Context(), orchestrator) + require.Equal(t, "broadcast", failureStage(err)) + _, err = caller.Reward(t.Context(), orchestrator) + require.NoError(t, err) + sent := f.Transactions() + require.Len(t, sent, 2) + require.Equal(t, sent[0].Nonce(), sent[1].Nonce(), "a rejected transaction must not leave a nonce gap") +} + +func TestReadinessCountsOnlyConfirmedAuthorization(t *testing.T) { + round := big.NewInt(9) + require.Zero(t, authorizedCount([]rewardCheck{{Outcome: outcomeFailed}, {Outcome: outcomeUnauthorized, Round: round}}), + "failed status reads and unauthorized orchestrators confirm nothing") + require.Equal(t, 2, authorizedCount([]rewardCheck{{Outcome: outcomeAlreadyRewarded, Round: round}, {Outcome: outcomeFailed, Round: round}, {Outcome: outcomeFailed}})) +} diff --git a/rewardcaller/caller.go b/rewardcaller/caller.go new file mode 100644 index 0000000..5d5327a --- /dev/null +++ b/rewardcaller/caller.go @@ -0,0 +1,166 @@ +package rewardcaller + +import ( + "bytes" + "context" + "errors" + "math/big" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/livepeer/node/eth" +) + +// Outcomes of one orchestrator check; also the values of the outcome metric label. +const ( + outcomeRewarded = "rewarded" + outcomeAlreadyRewarded = "already_rewarded" + outcomeUninitialized = "round_not_initialized" + outcomeInactive = "inactive" + outcomeUnauthorized = "unauthorized" + outcomeFailed = "failed" +) + +// chain is the protocol access one pass needs. +type chain interface { + RewardStatus(context.Context, common.Address) (eth.RewardStatus, error) + Reward(context.Context, common.Address) (common.Hash, error) +} + +type rewardCheck struct { + Orchestrator common.Address + Outcome string + Round *big.Int + LastRewardRound *big.Int + Transaction common.Hash + Err error +} + +// stageError records where a check failed. Logs carry the stage and error kind, +// never raw error text, which may echo RPC responses. +type stageError struct { + stage string + err error +} + +func (e stageError) Error() string { return e.stage + ": " + e.err.Error() } +func (e stageError) Unwrap() error { return e.err } + +func failureStage(err error) string { + var s stageError + if errors.As(err, &s) { + return s.stage + } + return "unknown" +} + +// pass checks the orchestrators in order, so one wallet's transactions stay sequential. +func pass(ctx context.Context, c chain, wallet common.Address, orchestrators []common.Address) []rewardCheck { + results := make([]rewardCheck, 0, len(orchestrators)) + for _, orchestrator := range orchestrators { + results = append(results, rewardOne(ctx, c, wallet, orchestrator)) + } + return results +} + +func rewardOne(ctx context.Context, c chain, wallet, orchestrator common.Address) rewardCheck { + r := rewardCheck{Orchestrator: orchestrator} + status, err := c.RewardStatus(ctx, orchestrator) + if err != nil { + r.Outcome, r.Err = outcomeFailed, stageError{"status", err} + return r + } + r.Round, r.LastRewardRound = status.Round, status.LastRewardRound + switch { + case status.RewardCaller != wallet: + // Checked every pass: an orchestrator can revoke or replace its caller at any time. + r.Outcome = outcomeUnauthorized + case !status.Active: + r.Outcome = outcomeInactive + case status.Rewarded(): + r.Outcome = outcomeAlreadyRewarded + case !status.Initialized: + r.Outcome = outcomeUninitialized + default: + r.Transaction, r.Err = c.Reward(ctx, orchestrator) + r.Outcome = outcomeRewarded + if r.Err != nil { + r.Outcome = outcomeFailed + } else { + r.LastRewardRound = status.Round + } + } + return r +} + +// authorizedCount counts orchestrators whose status was read and that authorize this +// wallet; a failed read confirms nothing. +func authorizedCount(results []rewardCheck) int { + count := 0 + for _, r := range results { + if r.Round != nil && r.Outcome != outcomeUnauthorized { + count++ + } + } + return count +} + +// protocol submits delegated reward calls from the dedicated wallet. +type protocol struct { + *eth.Contracts + key *eth.Key + chainID *big.Int + wait eth.WaitOptions +} + +// Reward plans rewardForTranscoder, which simulates the call first: an +// unauthorized caller or a round already rewarded fails before signing. +func (p protocol) Reward(ctx context.Context, orchestrator common.Address) (common.Hash, error) { + plan, err := p.RewardForTranscoder(ctx, p.key.Address(), orchestrator) + if err != nil { + return common.Hash{}, stageError{"simulate", err} + } + signed, err := p.Prepare(ctx, plan, p.key, p.chainID) + if err != nil { + return common.Hash{}, stageError{"sign", err} + } + // Rewards are sent one at a time. After any failure the next nonce comes from + // the node's pending count, so a transaction it never received leaves no gap + // that would block every later reward from this wallet. + if err = p.Broadcast(ctx, signed); err != nil { + p.ResetNonceReservation(signed.From) + return signed.Hash, stageError{"broadcast", err} + } + confirmation, err := p.WaitConfirmation(ctx, signed, p.key, p.wait, nil) + if err != nil { + p.ResetNonceReservation(signed.From) + return signed.Hash, stageError{"confirm", err} + } + return confirmation.Hash, nil +} + +var rewardForTranscoder = crypto.Keccak256([]byte("rewardForTranscoderWithHint(address,address,address)"))[:4] + +// broadcastPolicy runs before every broadcast, including fee replacements: the +// sender must still be a dedicated wallet and the call must be a delegated +// reward to BondingManager. The service never sends plain reward(). +func broadcastPolicy(c *eth.Contracts, chainID *big.Int) func(context.Context, *types.Transaction) error { + return func(ctx context.Context, tx *types.Transaction) error { + if tx.ChainId().Cmp(chainID) != 0 { + return errors.New("reward transaction chain mismatch") + } + bonding, err := c.Resolve(ctx, "bondingManager") + if err != nil { + return err + } + if tx.To() == nil || *tx.To() != bonding || !bytes.HasPrefix(tx.Data(), rewardForTranscoder) { + return errors.New("reward caller only broadcasts BondingManager.rewardForTranscoder") + } + sender, err := types.Sender(types.LatestSignerForChainID(chainID), tx) + if err != nil { + return errors.New("invalid reward transaction sender") + } + return c.CheckDedicatedWallet(ctx, sender) + } +}