Repository navigation
fix: remediate internal security audit findings across the node stack - #2183
nullPointerEnjoyer wants to merge 198 commits into
Conversation
block_height_to_postgres_friendly panicked on heights above i64::MAX and the workspace builds with panic=abort, so a single unauthenticated /api/v2/chain/<height> request could abort the whole web-server on postgres deployments. The conversion now returns a typed ApiServerStorageError::BlockHeightTooHigh, propagated from every caller, and chain_at_height rejects out-of-range heights up front with the existing InvalidBlockHeight client error. A CatchPanicLayer is added to the router as defense-in-depth for unwinding builds. Found by internal security audit: WEBSERVER-8-1, WEBSERVER-7-2
check_proof_of_stake only looked at PoSData kernel inputs and never validated the kernel witness vector, which is decoded from the attacker-controlled block header. A block with a valid kernel input and an empty kernel witness vector passed all consensus checks and then hit assert_eq!(inputs.len(), sigs.len()) in the input verifier's CoreContext::new on the block connect path; the workspace builds with panic=abort, so such a block crashed the node. Reject blocks whose kernel witnesses don't match their kernel inputs with a typed consensus error before any state is connected, and replace the assertion with a typed InputCheckError so a future regression in the verifier returns an error instead of panicking. Per-witness authorization of each kernel input remains enforced by the existing full input verification on the connect path. Found by internal security audit: CHAINSTATE-1-1 (H1)
The pending (mempool) transaction rendering built the token decimals
map from the token ids of the outputs alone, while tx_to_json renders
the inputs with the same map and the MintTokens input carries an
amount rendered through it. A consensus-valid relayable transaction
that mints a token it does not also transfer (and whose issuance is
not indexed) left the id missing, so TokenDecimals::get panicked on
expect("must exist") every time the transaction was served from
/api/v2/mempool/transactions or /api/v2/transaction/{id}.
The pending collection now also includes the token ids referenced by
the account command inputs, mirroring the confirmed-path collection
of the scanner; the order-referencing commands are skipped, since
their rendered responses carry no decimal amounts and the referenced
order may itself be pending (unlike the confirmed path, where it is
looked up). The decimals lookup falls back to zero decimals: the
decimals are presentational, the atoms amounts of the responses are
authoritative regardless of them.
Found by internal security audit: WEBSERVER-10-1
Serve header/block requests through a per-peer token bucket; make the whole egress channel chain (frontend commands, per-peer backend events, socket writer queue) bounded; penalize and disconnect peers whose egress queue fills up or whose socket writes time out; remember recent offenses across reconnects so rapid reconnects can't reset ban scores; reject foreign-network peers at the handshake with a small ban score instead of answering with a full HelloAck. Found by internal security audit: H5 (P2P-2-1), L24 (P2P-2-2), L25 (P2P-2-3)
TimestampSearchData::obtain assumed the pool balances map returned by get_stake_pool_balances_at_heights to be contiguous over the requested range and panicked on the first height without an entry; the map is sparse by construction, and a pool decommissioned within the range made the whole node abort (panic=abort). Iterate the map's actual keys and skip the heights where the pool has no (non-zero) balance, carry the height in every search data entry and propagate invariant violations as typed errors instead of expects. Also bound the request: reject a height range longer than MAX_TIMESTAMP_SEARCH_HEIGHT_RANGE heights and a seconds_to_check_for_height above MAX_SECONDS_TO_CHECK_FOR_HEIGHT; both limits surface to RPC callers as errors. Found by internal security audit: BLOCKPROD-10-1, BLOCKPROD-10-2
The reorg rollback deleted the balance, utxo, delegation and similar history of the disconnected blocks, but left their ml.transactions and ml.block_aux_data rows in place, so a transaction of a reorged-out block kept being served as a confirmed one forever, with its confirmations count growing on every new block; the postgres block_aux_data rows were never deleted either, and the in-memory transaction listing could panic on the leftover rows whose aux data was already gone. Add del_transactions_above_height and del_block_aux_data_above_height to the storage trait and both backends, and run them from the reorg disconnect before the main-chain heights are cleared; guard the transaction reads and listings to serve only the transactions whose owning block is on the main chain; bump the storage version so the existing version-mismatch path wipes and rescans the databases that hold the leftover rows. Found by internal security audit: APISTORAGE-6-1, SCANNER-1-1, WEBSERVER-6-1
Round-1 review follow-up of the internal audit fix for the timestamp search (findings H4/M5): - bound the chainstate rewind depth of timestamp search data collection: previously only the requested range length was capped, so a small range far below the chain tip still rewound an unbounded number of blocks under the chainstate lock; the distance from the tip to the range start is now capped as well, and the range validation is consolidated into validate_and_clamp_search_height_range with unit tests - report the caller-supplied max_height in WrongHeightRange instead of the clamped one, so the error reflects what was actually sent - assert in test_decommissioned_pool that find_timestamps_for_staking keys its results by the heights carried by the sparse search data - document the request caps in the wallet controller, wallet RPC interface and CLI command docs - add a changelog entry for the panic fix, the new caps and the TimestampSearchData encoding incompatibility across versions
The pool/delegation reads were made point-in-time for block connect, but order and fungible token issuance reads still served the latest history row: the fill/conclude/freeze order commands read the order and every token account command read the issuance before mutating state, so a row written by a block above the connected height would silently drift the indexed token supply and order balances during replay. Add get_order_at_or_below_height and get_fungible_token_issuance_at_or_below_height to the storage trait with postgres and in-memory implementations mirroring the pool variant, cover both with a shared-suite test alongside the existing pool/delegation point-in-time test, and switch the connect-path reads (transaction state updates, order prefetch for fee checks, order token id collection and the secondary history re-derivation) to the bounded reads. Order::freeze returns a typed error instead of asserting on an already frozen order. Found by internal security audit: APISTORAGE-10-2, SCANNER-10-3, SCANNER-6-6
The node-supplied common ancestor and the scan inputs are now validated with typed errors returned to the caller instead of assertion failures, so a misbehaving remote node (WalletType::Remote) cannot panic the wallet worker. An account already at the node tip is handled as the common block itself. Height arithmetic on the sync and scan paths uses checked conversions with typed errors. Found by internal security audit: WALLET-10-1, WALLET-10-2
The decoded Argon2id memory size, iteration count, parallelism and hash length now have generous upper bounds enforced before they drive allocations or computation, so a crafted wallet file cannot trigger a multi-GiB allocation. Legitimately-created files are still accepted. Found by internal security audit: CRYPTO-10-1
Trezor-produced single-sig witnesses are now verified with the same local check the Ledger and software paths use before the input is marked fully signed. Found by internal security audit: WALLET-3-2
The --history-file command history, which can contain the seed phrase, is now restricted to 0600 on creation and on every start. The insecure warning stays in place. Found by internal security audit: WALLET-5-1
Newly created wallets now use 64 MiB of Argon2id memory instead of 16 MiB. The KDF parameters are stored per wallet file, so existing files keep opening with their stored values. Found by internal security audit: WALLET-5-2
The cookie file is now written to a randomly named temporary file that is created exclusively with owner-only permissions and atomically renamed, instead of a predictable .tmp name opened without truncate. Found by internal security audit: WALLET-5-3
Apply backpressure instead of punish-on-full on the egress path: the peer task now awaits the capacity of the socket writer queue, throttling the message producers to the rate at which the peer reads, so honest peers on slow links are no longer penalized; the backend disconnects a peer whose event queue overflows without a ban score, and the socket write timeout remains the sole slow-reader punishment. The unused EgressQueueFull protocol error is removed. Serve header and block requests by pacing them to the serving refill rate instead of refusing over-budget requests with a ban score, which punished honest fast syncers; only a request whose serving weight exceeds the whole serving budget bucket (a test-only misconfiguration, now clamped) is refused with a ban score. The writer close handling is factored out so a write timeout that closes a full writer queue is still reported. Found by internal security audit: review round 1 findings on B1-p2p-resource-quality (H5, L24, L25 follow-ups)
ml.nft_issuance.owner was derived as a side effect of the address balance and locked-balance writes, which the scan flushes aggregated in BTreeMap (address-string) key order at the same block_height: a same-block NFT transfer persisted the owner of whichever address happened to be flushed last, i.e. NULL about half the time, and a timelock expiry always ended owner NULL because the locked-balance write (amount zero, owner NULL) ran after the available-balance write (owner Some). The web server serves the owner straight from that row. Stop deriving the owner from the flush: drop the update_nft_owner side effect from set_address_balance_at_height and set_address_locked_balance_at_height in both backends, and add an explicit set_nft_token_owner storage write (versioned like the issuance rows) that the scan calls at the output-processing sites in transaction/output order: the recipient on a Transfer or LockThenTransfer output that pays the NFT (and the IssueNft issuance row as before), None when a matching input is consumed, so a burned NFT has no owner while a same-transaction pay-forward restores it. Add end-to-end scan tests: an NFT transferred issuer -> A -> B inside one block must serve B (both transfer addresses sort before the issuer's, the configuration that previously persisted NULL), and an NFT received under a block-count lock must keep its owner through the unlock. Rework the storage suite's set_get NFT section to the new contract: balance writes leave the owner untouched and only set_nft_token_owner moves it, including same-height overwrites and the versioned rollback via del_nft_issuance_above_height. Found by internal security audit: SCANNER-7-1
The experimental trusted-fee path takes per-transaction fees verbatim from the node's block_tx_fees RPC into AccumulatedFee::from_coin_fee and sums them into the total that is credited to the Staked statistic and the pool/delegation reward accounting, with no validation: fees are unsigned amounts (a negative entry cannot deserialize), but an absurdly large entry overflows the reward arithmetic, whose (block_subsidy + total_tx_fees).expect and the combine/map_into_block expects panic mid-batch, rolling the batch back on every retry and wedging the sync loop forever. Bound the values before use: per-transaction and per-block fee caps (just above the whole possible coin supply, which no legitimate fee payable from existing coins can reach, and far below the u128 accumulation range) reject a bad batch with typed TrustedFeeOutOfRange/TrustedBlockFeeOutOfRange errors, loudly logged; the reward-path expects (subsidy plus fees, fee combination and projection, reward distribution, delegation and pool balance updates) return typed FeeArithmeticOverflow/RewardDistributionError errors instead of panicking, so supervise_sync drops the batch and re-fetches it with escalating backoff. The pool-missing lookups keep the LowLevelStorageError convention used by the rest of the connect path. Cover with fee tests: a per-transaction fee above the cap is rejected with the scan staying at the common ancestor and a plain re-fetch succeeding, per-transaction fees below the cap that sum above the per-block cap are rejected before the reward distribution, and a sane trusted fee is indexed exactly as supplied. Found by internal security audit: SCANNER-6-2
Expired ml.locked_utxo rows are never removed, so their retention has to be a deliberate, test-enforced decision rather than an accident: the row is the replay source for the unlock transition. A reorg that disconnects blocks above the expiry height rolls the balance moves and the unlocked UTXO rows back, and reconnecting the expiry block re-drives them from get_locked_utxos_until_now; purging the row when it expires (as the retention cleanup would naturally do) would permanently lose the unlock on such a reorg - the balance would stay locked and the UTXO unservable. Rows are only ever removed by the reorg cleanup above the lock's creation height, which also covers the expired ones once the lock's creation itself is disconnected. Document the semantics on the storage trait reads/writes and at the expiry-processing site, and add a scan test that reorgs across the expiry height and proves the retained row re-drives the unlock: the balance and the spendable UTXO are restored on reconnect, and the expired row is still served by get_locked_utxos_until_now. Found by internal security audit: SCANNER-6-4
Inbound connections get a fresh peer ID each, so the per-peer orphan pool quota (10 entries) could be multiplied by opening more connections from one IP: ten connections times ten junk orphans saturated the aggregate pool cap and locked honest peers out until expiry, while eviction never touched the attacker's protected entries. The per-peer reservation is now keyed by the remote IP address for inbound connections (all of one address's connections share one reservation), while outbound peers keep their per-peer quota; this is the smaller change next to stacking a second per-IP cap, because the orphan pool already keys its accounting by transaction origin: making inbound origins compare by their canonical address (the same key bans use) gives shared counting, reservation and eviction for free. The peer ID is still carried for punishment, event reporting and disconnect cleanup, so peer teardown now removes a connection's orphans by peer ID instead of by origin key. The fail-closed policy is unchanged: a full pool still rejects a newcomer instead of displacing protected entries. Found by internal security audit: M6 (TXLAYER-4-1)
Derive the trusted-fee sanity caps from the chain config instead of the hardcoded 1e20-atom bound: the caps are twice the total supply (the coin amounts minted by the genesis outputs plus the emission schedule's final issuance), so every consensus-valid fee stays inside the cap on each built-in chain. The old hardcoded cap sat far below the Babbage testnet genesis mint (1e20 vs 4e24 atoms), so a consensus-valid testnet fee above 1e9 TML made every batch re-fetch fail TrustedFeeOutOfRange or TrustedBlockFeeOutOfRange and the scanner stalled permanently on a valid block. Chains with a nonzero tail subsidy have no finite total supply; their caps fall back to Amount::MAX, where the typed accumulation-overflow errors remain as the backstop. The caps rationale comment is corrected accordingly: mainnet total supply is ~6.0e19 atoms, not the previously claimed 4.1e17 atoms, and the supply bound is now stated per chain config instead of a single figure.
The address history (transaction_history of /api/v2/address/{address}),
the spendable and all UTXO listings and the delegations listings of an
address and a pool materialized the complete history of the queried
entity on every request, so any unauthenticated client could turn one
request into an arbitrarily large response (all the other listings are
already capped at 100 rows per page by the shared page parser).
The rows of these endpoints are now capped at 1000 per response; when
the cap truncates the result, the response carries a `truncated` flag,
so a partial listing is never silently presented as complete: an
additive field for the object-shaped address response (the same pattern
as the order book listing) and an object wrapping the rows for the
array-shaped ones, which keep their plain array form in the common
non-truncated case.
Found by internal security audit: APISTORAGE-7-2
POST /api/v2/transaction passed the error text of the connected node verbatim to unauthenticated clients, disclosing internal details (the node's state and configuration, the exact mempool rejection reasons). The detail is now kept in the server log and the client receives the generic "Transaction submission failed" client error. Found by internal security audit: WEBSERVER-8-4
The API served CORS responses with allow-origin: * and validated neither the Origin nor the Host header, so any web page the operator visits could read the responses of (and fire requests into) the default localhost-bound API from the operator's browser, and a DNS rebinding attack could reach it under an attacker-chosen host name. Requests carrying an Origin header are now rejected with 403 unless they come from the origin of the server itself or from another loopback address (local tools on the same machine); on loopback-bound deployments the Host header must additionally name a loopback host on the listening port, which defeats rebinding. Non-browser traffic (no Origin header) is unaffected; operators intentionally exposing the API to browser clients from other origins are expected to strip or rewrite the Origin header at their reverse proxy, as documented in the README (new "Browser access and cross-origin requests" section). The subscriber cap of the SSE event stream was also global-only (128 slots): a single client could hold every slot with idle connections and lock all other clients out of the stream. A per-client-IP cap of 16 subscriptions now applies alongside the global one, and the slots are released when the client disconnects. Found by internal security audit: WEBSERVER-8-3, WEBSERVER-8-5
The crawler logged one info line per unsolicited AddrListResponse with no rate limit, so a hostile peer could flood the crawler log with one line per message by sending unsolicited responses in a tight loop. The log line is now rate limited per peer (a small burst, then at most one line per minute); the suppressed lines are demoted to the debug level. Found by internal security audit: WEBSERVER-10-2, INFRA-10-1
The RPC auth layer logged one error line per unauthenticated or malformed request, so a hostile client could flood the log with one line per request while changing no state; the lines are now logged at the debug level. Found by internal security audit: WEBSERVER-10-3
Demote per-message log lines that a peer could trigger at socket rate (unsolicited/duplicate/over-limit transaction announcements and responses, repeated address list requests, block requests during the initial block download) to the debug level. Bound the volume of messages that are only ignored by token buckets that mirror the address announcement rate limiter: unsolicited transaction responses and repeated address list requests that exceed the tolerated rate accrue ban score, so a sustained flood gets the peer discouraged and disconnected. Block requests that arrive while the node is in the initial block download now return an error with a non-zero ban score instead of being ignored. Skip score adjustments for peers that are already being disconnected and log score adjustments at the debug level, so the punishment path itself can't be turned into a per-message log source. Found by internal security audit: M7 (P2P-10-1), M7 (P2P-10-2), M7 (P2P-10-3)
The 1000-row cap of the unpaginated listings was response-only: the backing storage queries still materialized and transferred the complete history of the queried entity before the web layer truncated the result. The five capped listing reads (address transactions, spendable/all UTXOs, delegations from an address, pool delegation shares) now take a max_rows parameter that both backends enforce in the read itself: LIMIT in the Postgres queries, take() in the in-memory backend. The web layer reads cap+1 rows and keeps the existing truncated-flag contract and response shapes. The capped reads pick a deterministic subset (delegation-id order for the delegation listings, outpoint order for the UTXO listings, block-height with transaction-id tiebreak for the history) so repeated truncated responses are stable. Found by internal security audit: APISTORAGE-7-2 (C6 review round 1)
ChainstateConfigFile now derives serde(deny_unknown_fields), and ChainstateLauncherConfigFile deserializes through an unflattened shadow struct, because serde silently drops deny_unknown_fields for a struct read through serde(flatten). A typo'd key in the [chainstate] config section is now a parse error instead of a silently ignored default; parsing tests cover the direct and section paths. Found by internal security audit: INFRA-9-1
The release and static-checks workflows pinned actions by mutable tags or branch refs; every actions/*, docker/*, dtolnay/rust-toolchain and ncipollo/release-action reference is now pinned to the full commit SHA, taken from the action repositories' refs. The release and static-checks workflows that lacked an explicit permissions block are bound to contents: read (release.yml keeps contents: write for creating the release). Found by internal security audit: INFRA-9-2, INFRA-10-5, INFRA-9-5
The GitLab gate installed whatever cargo-deny release was current at install time, so the GitLab and GitHub checks could run different tool versions against different advisory data; it now uses the same pinned cargo-deny 0.21.0 as the GitHub static-checks workflow. Found by internal security audit: INFRA-10-2
|
OpenCodeReview · Complete review: 218 of 218 selected files covered 78 findings.
📄
|
| File | Result |
|---|---|
wallet/wallet-controller/src/synced_controller.rs |
Reviewed |
wallet/src/wallet/mod.rs |
Reviewed |
mempool/src/interface/mempool_interface.rs |
Reviewed |
node-lib/src/config_files/chainstate_launcher.rs |
Reviewed |
common/src/primitives/height.rs |
Reviewed |
wallet/types/src/seed_phrase.rs |
Reviewed |
chainstate/tx-verifier/src/transaction_verifier/input_check/mod.rs |
Reviewed |
api-server/web-server/src/error.rs |
Reviewed |
crypto/src/kdf/argon2.rs |
Reviewed |
chainstate/src/detail/median_time.rs |
Reviewed |
networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs |
Reviewed |
wallet/storage/src/internal/password.rs |
Reviewed |
packaging/rpm/build.sh |
Reviewed |
common/src/chain/block/timestamp.rs |
Reviewed |
wallet/wallet-node-client/src/rpc_client/client_impl.rs |
Reviewed |
common/src/chain/config/builder.rs |
Reviewed |
mempool/src/pool/tx_pool/tx_verifier/chainstate_handle.rs |
Reviewed |
mempool/src/rpc.rs |
Reviewed |
api-server/api-server-common/src/storage/storage_api/mod.rs |
Reviewed |
p2p/src/net/default_backend/backend.rs |
Reviewed |
accounting/src/block_undo.rs |
Reviewed |
wallet/wallet-node-client/src/handles_client/mod.rs |
Reviewed |
wallet/storage/src/internal/store_tx.rs |
Reviewed |
mempool/src/pool/tx_pool/rolling_fee_rate.rs |
Reviewed |
rpc/src/rpc_rate_limit.rs |
Reviewed |
p2p/backend-test-suite/src/ban.rs |
Reviewed |
chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/cached_utxo_block_undo.rs |
Reviewed |
mempool/src/config.rs |
Reviewed |
chainstate/src/detail/error_classification.rs |
Reviewed |
wallet/storage/src/internal/mod.rs |
Reviewed |
p2p/src/message.rs |
Reviewed |
api-server/web-server/src/api/mod.rs |
Reviewed |
api-server/storage-test-suite/src/basic.rs |
Reviewed |
mempool/src/pool/tx_pool/collect_txs.rs |
Reviewed |
common/src/chain/upgrades/netupgrade.rs |
Reviewed |
chainstate/src/lib.rs |
Reviewed |
.github/workflows/code-review.yml |
Reviewed |
storage/core/src/adaptor/locking.rs |
Reviewed |
blockprod/src/detail/mod.rs |
Reviewed |
chainstate/types/src/storage_result.rs |
Reviewed |
chainstate/src/config.rs |
Reviewed |
wallet/wallet-node-client/src/node_traits.rs |
Reviewed |
do_checks.sh |
Reviewed |
api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs |
Reviewed |
common/src/chain/transaction/signature/sighash/hashable.rs |
Reviewed |
api-server/scanner-lib/src/blockchain_state/mod.rs |
Reviewed |
wallet/wallet-controller/src/lib.rs |
Reviewed |
wallet/src/key_chain/mod.rs |
Reviewed |
chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/mod.rs |
Reviewed |
api-server/web-server/src/api/json_helpers.rs |
Reviewed |
api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs |
Reviewed |
api-server/web-server/src/api/rate_limit.rs |
Reviewed |
test/functional/wallet_set_lookahead_size.py |
Reviewed |
node-lib/src/options.rs |
Reviewed |
dns-server/src/main.rs |
Reviewed |
wallet/wallet-rpc-lib/src/rpc/server_impl.rs |
Reviewed |
p2p/src/interface/p2p_interface_impl.rs |
Reviewed |
dns-server/src/crawler_p2p/crawler/address_data.rs |
Reviewed |
chainstate/types/src/error.rs |
Reviewed |
p2p/backend-test-suite/src/block_announcement.rs |
Reviewed |
wallet/storage/src/internal/test.rs |
Reviewed |
build-tools/docker/example-mainnet-dns-server/docker-compose.yml |
Reviewed |
mocks/src/mempool.rs |
Reviewed |
chainstate/src/detail/query.rs |
Reviewed |
wallet/wallet-cli-lib/src/repl/interactive/mod.rs |
Reviewed |
p2p/src/utils/rate_limiter/mod.rs |
Reviewed |
blockprod/src/rpc.rs |
Reviewed |
.github/workflows/code_checks.yml |
Reviewed |
chainstate/src/detail/mod.rs |
Reviewed |
mempool/src/error/mod.rs |
Reviewed |
chainstate/src/rpc/mod.rs |
Reviewed |
wallet/Cargo.toml |
Reviewed |
common/src/chain/partially_signed_transaction/v1.rs |
Reviewed |
packaging/deb/build.sh |
Reviewed |
chainstate/src/detail/ban_score.rs |
Reviewed |
p2p/src/peer_manager/peers_eviction/mod.rs |
Reviewed |
consensus/src/pos/target.rs |
Reviewed |
wallet/wallet-cli-commands/src/command_handler/mod.rs |
Reviewed |
crypto/src/ephemeral_e2e/error.rs |
Reviewed |
chainstate/src/detail/tx_verification_strategy/default_strategy.rs |
Reviewed |
chainstate/tx-verifier/src/transaction_verifier/input_check/signature_only_check.rs |
Reviewed |
p2p/src/lib.rs |
Reviewed |
packaging/common/env/node.env |
Reviewed |
serialization/src/encoded.rs |
Reviewed |
wallet/wallet-controller/src/types/seed_phrase.rs |
Reviewed |
consensus/src/pos/mod.rs |
Reviewed |
p2p/src/sync/peer_common/mod.rs |
Reviewed |
.github/workflows/loom.yml |
Reviewed |
mintscript/src/translate.rs |
Reviewed |
packaging/arch/build.sh |
Reviewed |
p2p/src/net/default_backend/mod.rs |
Reviewed |
api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs |
Reviewed |
storage/src/database/internal.rs |
Reviewed |
.github/workflows/release_windows.yml |
Reviewed |
dns-server/src/crawler_p2p/crawler_manager/mod.rs |
Reviewed |
mempool/src/interface/mempool_interface_impl.rs |
Reviewed |
api-server/web-server/Cargo.toml |
Reviewed |
mempool/src/pool/orphans/test.rs |
Reviewed |
storage/lmdb/src/lib.rs |
Reviewed |
rpc/src/subscription.rs |
Reviewed |
crypto/src/ephemeral_e2e/mod.rs |
Reviewed |
p2p/src/sync/peer/transaction_manager.rs |
Reviewed |
api-server/scanner-lib/src/sync/mod.rs |
Reviewed |
chainstate/src/detail/test.rs |
Reviewed |
dns-server/src/crawler_p2p/crawler/mod.rs |
Reviewed |
blockprod/src/interface/blockprod_interface_impl.rs |
Reviewed |
api-server/scanner-daemon/src/main.rs |
Reviewed |
wallet/wallet-rpc-lib/src/lib.rs |
Reviewed |
wallet/wallet-rpc-lib/src/rpc/interface.rs |
Reviewed |
blockprod/src/lib.rs |
Reviewed |
p2p/src/net/default_backend/types.rs |
Reviewed |
common/src/primitives/amount/decimal.rs |
Reviewed |
storage/failing/src/backend.rs |
Reviewed |
crypto/src/symkey/chacha20poly1305/mod.rs |
Reviewed |
api-server/web-server/src/api/stream.rs |
Reviewed |
p2p/src/net/default_backend/peer/handshake_handler.rs |
Reviewed |
p2p/src/peer_manager/peerdb/storage_impl.rs |
Reviewed |
mempool/src/error/ban_score.rs |
Reviewed |
api-server/web-server/src/main.rs |
Reviewed |
networking/src/transport/message_codec.rs |
Reviewed |
Additional file results omitted to fit this comment.
| timeout-minutes: 40 | ||
| steps: | ||
| - uses: alibaba/open-code-review@494bf1c8d7a19196ab166960a06fef38d69a1d16 # v1.12.0 | ||
| - uses: alibaba/open-code-review@90457245bcd4a0af3ad32856c8a4f03051c43e5f # v1.14.9 |
There was a problem hiding this comment.
This third-party action receives secrets.OCR_LLM_TOKEN and can post comments to the PR (pull-requests: write). Pinning to a SHA is good practice, but the SHA's authenticity (that it corresponds to the official alibaba/open-code-review v1.14.9 release, not a fork) must be independently verified before merging — a comment in this file is not proof. Also note max_tokens_budget: '0' (unlimited) combined with the new token upgrade means a compromised or misbehaving action version could incur unbounded LLM API costs; consider a finite budget.
Suggestion:
| - uses: alibaba/open-code-review@90457245bcd4a0af3ad32856c8a4f03051c43e5f # v1.14.9 | |
| # Verify SHA against https://github.com/alibaba/open-code-review/releases/tag/v1.14.9 | |
| - uses: alibaba/open-code-review@90457245bcd4a0af3ad32856c8a4f03051c43e5f # v1.14.9 |
| create-release: | ||
| needs: [build-macos, build-linux, build-windows, build-docker-amd64] | ||
| runs-on: ubuntu-latest | ||
| if: startsWith(github.ref, 'refs/tags/') |
| runs-on: ubuntu-latest | ||
| steps: | ||
| - name: Checkout the repository |
| fn is_loopback_host(host: &str) -> bool { | ||
| matches!(host, "localhost" | "127.0.0.1" | "::1") | ||
| } |
There was a problem hiding this comment.
is_loopback_host only recognizes the literal strings localhost, 127.0.0.1 and ::1, but BrowserRequestPolicy::strict_host_validation is enabled for any loopback bind address. When the server binds to another loopback address (e.g. 127.5.5.5:3000), a request whose Host header names the server's own bind address (127.5.5.5:3000) — or the derived own-origin used by origin_allowed (which matches it exactly and accepts it) — is rejected by host_allowed, because 127.5.5.5 is not in the hard-coded list. A legitimate browser or tool request that reached the server at its actual loopback address gets a 403, and the CORS preflight/origin check and the Host check disagree. Suggest parsing the host as an IP (or resolving localhost) and using IpAddr::is_loopback(), keeping the textual special-cases only as a fallback.
Suggestion:
| fn is_loopback_host(host: &str) -> bool { | |
| matches!(host, "localhost" | "127.0.0.1" | "::1") | |
| } | |
| fn is_loopback_host(host: &str) -> bool { | |
| if let Ok(ip) = host.parse::<IpAddr>() { | |
| return ip.is_loopback(); | |
| } | |
| matches!(host, "localhost") | |
| } |
| let _query_permit = if token_ids.is_empty() { | ||
| None | ||
| } else { | ||
| Some( | ||
| tokio::time::timeout( | ||
| MEMPOOL_QUERY_WAIT_TIMEOUT, | ||
| MEMPOOL_QUERY_PERMITS.acquire(), | ||
| ) |
There was a problem hiding this comment.
The mempool query permit is now acquired unconditionally for any transaction that references at least one token, before the storage lookup that decides whether the mempool listing is needed at all. Previously the permit was only taken when pending_token_ids was non-empty, i.e. when an actual mempool fetch was required. Now every /transaction lookup of a token-bearing transaction waits on (and holds) the shared MEMPOOL_QUERY_PERMITS budget and is subject to MEMPOOL_QUERY_WAIT_TIMEOUT, even when all referenced tokens resolve from storage and no mempool call follows. Under load this can turn otherwise-cheap lookups into TooManyMempoolRequests (429) rejections, since token-heavy transactions contend for permits they don't need. Consider acquiring the permit lazily: do the storage decimals resolution first, and only take the permit when some referenced token is missing from storage.
Suggestion:
| let _query_permit = if token_ids.is_empty() { | |
| None | |
| } else { | |
| Some( | |
| tokio::time::timeout( | |
| MEMPOOL_QUERY_WAIT_TIMEOUT, | |
| MEMPOOL_QUERY_PERMITS.acquire(), | |
| ) | |
| // Resolve the indexed decimals first; acquire the mempool query permit | |
| // only if some referenced token may be pending (i.e. needs the listing). | |
| let _query_permit = None::<tokio::sync::OwnedSemaphorePermit>; |
| impl Default for RpcRateLimitLayer { | ||
| fn default() -> Self { | ||
| // The same bounds as the HTTP bucket: a stream of single calls keeps the full | ||
| // request rate, while batch elements and WebSocket messages are charged exactly | ||
| // like the requests that carry them. | ||
| Self::new(RATE_LIMIT_BURST, RATE_LIMIT_REFILL_PER_SEC) | ||
| } | ||
| } |
There was a problem hiding this comment.
The HTTP layer and the JSON-RPC layer each construct their own TokenBucket (via the independent Default impls), so a plain HTTP call is charged twice: once at the HTTP middleware and once at the RPC middleware. The effective sustained rate for plain HTTP calls is ~64 rps (half of RATE_LIMIT_REFILL_PER_SEC), while WebSocket messages are charged only once (~128 rps), producing a 2x throughput asymmetry between transports that contradicts the module documentation's claim that batch elements and WebSocket messages are 'charged exactly like the requests that carry them'. Consider sharing one Arc between the two layers, or documenting the intended double charge.
| static LIVE_EVENT_SUBSCRIPTIONS: std::sync::atomic::AtomicUsize = | ||
| std::sync::atomic::AtomicUsize::new(0); |
There was a problem hiding this comment.
LIVE_EVENT_SUBSCRIPTIONS is a process-global counter, so all RPC servers in one node process share the single cap of 8 subscriptions. The node serves both the chainstate and mempool event streams through this connector (see chainstate/src/rpc/mod.rs and mempool/src/rpc.rs), so one component's clients can exhaust the budget of the other, causing legitimate subscriptions to be spuriously rejected. Consider keying the cap per server (e.g. an Arc/permit set owned by the Rpc instance) rather than a static global.
| pub fn from_bytes_unchecked(bytes: E) -> Self { | ||
| let _phantom = Default::default(); | ||
| let this = Self { bytes, _phantom }; | ||
| debug_assert!(T::decode_all(&mut this.bytes()).is_ok()); | ||
| assert!( | ||
| T::decode_all(&mut this.bytes()).is_ok(), | ||
| "from_bytes_unchecked called with an invalid encoding" | ||
| ); | ||
| this | ||
| } |
There was a problem hiding this comment.
from_bytes_unchecked now asserts validity unconditionally, but its production callers in storage/src/database/internal.rs (prefix_iter / greater_equal_iter) feed raw key/value bytes straight from the database. A corrupted DB row will now panic and abort the node in release builds, whereas the surrounding storage layer models this condition as a recoverable Error::Fatal(Fatal::DatabaseCorrupted) (see decode_key two lines below). Since a fallible from_bytes constructor now exists, these iteration paths should use it and map the failure to DatabaseCorrupted instead of panicking.
| leaf_chain.usage_state.increment_up_to_last_issued(U31::from_u32(10).unwrap()); | ||
|
|
||
| let new_idx = U31::from_u32(20).unwrap(); | ||
| leaf_chain.check_issued_lookahead(new_idx, u32::MAX).unwrap(); |
There was a problem hiding this comment.
This test does not actually exercise the saturating_add path it claims to cover. increment_up_to_last_issued only updates last_issued; last_used remains None, so check_issued_lookahead takes the None => new_index_to_issue.into_u32() >= lookahead_size branch, which does no arithmetic at all. With lookahead_size == u32::MAX and index 20, the test passes trivially and would also pass on the original overflow-prone code (last_used.into_u32() + lookahead_size). To cover the fixed code, set last_used to a large value (e.g. KeychainUsageState::new(Some(U31::from_u32(u32::MAX - 2).unwrap()), ...) and issue with a normal lookahead size), so the Some(last_used_index) branch with saturating_add is reached.
Suggestion:
| leaf_chain.usage_state.increment_up_to_last_issued(U31::from_u32(10).unwrap()); | |
| let new_idx = U31::from_u32(20).unwrap(); | |
| leaf_chain.check_issued_lookahead(new_idx, u32::MAX).unwrap(); | |
| leaf_chain.usage_state = KeychainUsageState::new( | |
| // `Some(last_used)` drives the branch that previously used a plain `+`, which | |
| // overflowed near u32::MAX; `saturating_add` must keep the check from panicking. | |
| Some(U31::from_u32(u32::MAX - 2).unwrap()), | |
| Some(U31::from_u32(10).unwrap()), | |
| ); | |
| let new_idx = U31::from_u32(20).unwrap(); | |
| leaf_chain.check_issued_lookahead(new_idx, 20).unwrap(); |
| @@ -60,7 +61,7 @@ pub fn password_to_sym_key(password: &String) -> crate::Result<(SymmetricKey, Kd | |||
| ) | |||
| .expect("must be correct size"); | |||
|
|
|||
| let challenge = kdf_result.into_challenge(); | |||
| let challenge = kdf_result.into_challenge().map_err(|_| crate::Error::WalletInvalidPassword)?; | |||
There was a problem hiding this comment.
into_challenge() only fails with KdfError::InvalidHashSize (it refuses to truncate the hash length into u32). With a fixed key_size(XChacha20Poly1305) this is an internal invariant violation, not a user error, so mapping it to WalletInvalidPassword is misleading: a caller creating a new wallet could be told their password is wrong for a non-password-related internal failure. A non-password error (e.g. WalletDbInconsistentState or a dedicated internal/KDF error) would be more accurate.
Suggestion:
| let challenge = kdf_result.into_challenge().map_err(|_| crate::Error::WalletInvalidPassword)?; | |
| let challenge = kdf_result | |
| .into_challenge() | |
| .map_err(|_| crate::Error::WalletDbInconsistentState)?; |
| TxOutput::Transfer(value, _) | ||
| | TxOutput::LockThenTransfer(value, _, _) | ||
| | TxOutput::Htlc(value, _) | ||
| | TxOutput::Burn(value) => value.coin_amount(), |
There was a problem hiding this comment.
OutputValue::coin_amount() returns None for any token value (see common/src/chain/transaction/output/output_value.rs), so a genesis block containing a token Transfer/LockThenTransfer/Htlc/Burn output makes minted? abort the try_fold and chain_total_supply return None. The caller then silently falls back to Amount::MAX, disabling the new trusted-fee sanity cap for the whole chain. Token outputs should contribute zero coins (like IssueFungibleToken, DataDeposit, etc.), not abort the supply computation; otherwise the safety check is silently defeated on any chain whose genesis mints tokens.
Suggestion:
| TxOutput::Transfer(value, _) | |
| | TxOutput::LockThenTransfer(value, _, _) | |
| | TxOutput::Htlc(value, _) | |
| | TxOutput::Burn(value) => value.coin_amount(), | |
| TxOutput::Transfer(value, _) | |
| | TxOutput::LockThenTransfer(value, _, _) | |
| | TxOutput::Htlc(value, _) | |
| | TxOutput::Burn(value) => Some(value.coin_amount().unwrap_or(Amount::ZERO)), |
| match output_value { | ||
| OutputValue::Coin(amount) => { | ||
| increase_statistic_amount( | ||
| acc, | ||
| CoinOrTokenStatistic::OpenHtlc, | ||
| amount, | ||
| CoinOrTokenId::Coin, | ||
| block_height, | ||
| ) | ||
| .await?; | ||
| } | ||
| OutputValue::TokenV0(_) => {} | ||
| OutputValue::TokenV1(token_id, amount) => { | ||
| increase_statistic_amount( | ||
| acc, | ||
| CoinOrTokenStatistic::OpenHtlc, | ||
| amount, | ||
| CoinOrTokenId::TokenId(*token_id), | ||
| block_height, | ||
| ) | ||
| .await?; | ||
| } | ||
| } |
There was a problem hiding this comment.
NFT owner tracking is asymmetric for HTLC outputs: this creation arm credits OpenHtlc for TokenV1 but never calls set_nft_token_owner, while the matching spend arm in update_tables_from_transaction_inputs (HTLC input) clears the owner with set_nft_token_owner(token_id, ..., None). A TokenV1 value delivered via TxOutput::Htlc therefore serves owner: None for the whole lifetime of the contract even though a recipient exists. Related: the Transfer/LockThenTransfer output arms skip the owner write when amount == Amount::ZERO, so a zero-amount token transfer after the spend-side None write also strands the owner as None. If NFT-in-HTLC is impossible by consensus, guard the spend arm symmetrically (skip the None write there too) or document the invariant; otherwise write the owner here as well.
Suggestion:
| match output_value { | |
| OutputValue::Coin(amount) => { | |
| increase_statistic_amount( | |
| acc, | |
| CoinOrTokenStatistic::OpenHtlc, | |
| amount, | |
| CoinOrTokenId::Coin, | |
| block_height, | |
| ) | |
| .await?; | |
| } | |
| OutputValue::TokenV0(_) => {} | |
| OutputValue::TokenV1(token_id, amount) => { | |
| increase_statistic_amount( | |
| acc, | |
| CoinOrTokenStatistic::OpenHtlc, | |
| amount, | |
| CoinOrTokenId::TokenId(*token_id), | |
| block_height, | |
| ) | |
| .await?; | |
| } | |
| } | |
| OutputValue::TokenV1(token_id, amount) => { | |
| increase_statistic_amount( | |
| acc, | |
| CoinOrTokenStatistic::OpenHtlc, | |
| amount, | |
| CoinOrTokenId::TokenId(*token_id), | |
| block_height, | |
| ) | |
| .await?; | |
| db_tx.set_nft_token_owner(*token_id, block_height, Some(destination)).await?; | |
| } |
| let main_chain_blocks: BTreeSet<Id<Block>> = | ||
| self.main_chain_blocks_table.values().copied().collect(); | ||
| Ok(self | ||
| .ordered_transaction_table | ||
| .range(..tx_global_index) | ||
| .rev() | ||
| .filter(|(_, tx_id)| { | ||
| self.transaction_table | ||
| .get(*tx_id) | ||
| .is_some_and(|(owning_block, _)| main_chain_blocks.contains(owning_block)) | ||
| }) |
There was a problem hiding this comment.
get_transactions_with_block_before_tx_global_index deep-copies every main-chain block id into a fresh BTreeSet on every call (O(main-chain length) per API listing request), only to filter candidates whose owning blocks are, by construction, already on the main chain: del_transactions_above_height removes the transactions of disconnected blocks from transaction_table (and cascades into ordered_transaction_table) whenever the main chain changes, so any surviving row necessarily belongs to a main-chain block. Consider dropping the set entirely, or at least reusing a cached reverse index, so the per-call cost doesn't scale with chain length.
Suggestion:
| let main_chain_blocks: BTreeSet<Id<Block>> = | |
| self.main_chain_blocks_table.values().copied().collect(); | |
| Ok(self | |
| .ordered_transaction_table | |
| .range(..tx_global_index) | |
| .rev() | |
| .filter(|(_, tx_id)| { | |
| self.transaction_table | |
| .get(*tx_id) | |
| .is_some_and(|(owning_block, _)| main_chain_blocks.contains(owning_block)) | |
| }) | |
| Ok(self | |
| .ordered_transaction_table | |
| .range(..tx_global_index) | |
| .rev() | |
| .filter(|(_, tx_id)| self.transaction_table.contains_key(tx_id)) |
| fn is_main_chain_block(&self, block_id: &Id<Block>) -> bool { | ||
| self.main_chain_blocks_table.values().any(|id| id == block_id) | ||
| } |
There was a problem hiding this comment.
is_main_chain_block performs a linear scan over main_chain_blocks_table (O(main-chain length)) on every call, and it is invoked per transaction in get_transaction_with_block and get_transaction. On a long chain this turns each per-transaction API read into an O(n) scan. A reverse index (e.g. a HashSet<Id<Block>> of main-chain block ids, or storing the height next to the transaction so the map can be probed by height) would make this O(1). Similarly, get_all_orders rebuilds the full BTreeSet of main-chain block ids on every call; the same reverse set could be reused.
Suggestion:
| fn is_main_chain_block(&self, block_id: &Id<Block>) -> bool { | |
| self.main_chain_blocks_table.values().any(|id| id == block_id) | |
| } | |
| fn is_main_chain_block(&self, block_id: &Id<Block>) -> bool { | |
| self.main_chain_block_ids.contains(block_id) | |
| } |
| "SELECT delegation_id, balance, spend_destination, next_nonce, | ||
| creation_block_height | ||
| FROM ml.latest_delegations_cache | ||
| WHERE pool_id = $1 | ||
| ORDER BY delegation_id | ||
| LIMIT $2;", |
There was a problem hiding this comment.
Cross-backend subset divergence: the trait contract for max_rows (see storage_api/mod.rs) promises the subset with the smallest delegation ids, which is what the in-memory backend returns (BTreeMap order over raw DelegationIds). Here the subset is chosen by ORDER BY on the encoded address string (prefix + checksum included), which does not preserve DelegationId ordering. For any pool with more than max_rows delegations, the two backends return different delegations for the same query, so explorer responses depend on which backend serves the request. Consider ordering by the raw id bytes (e.g. a stored raw-id bytea column, or ORDER BY the token that the bech32 encoding is derived from) so both backends agree.
Suggestion:
| "SELECT delegation_id, balance, spend_destination, next_nonce, | |
| creation_block_height | |
| FROM ml.latest_delegations_cache | |
| WHERE pool_id = $1 | |
| ORDER BY delegation_id | |
| LIMIT $2;", | |
| ORDER BY delegation_id -- TODO: order by raw id bytes to match the in-memory backend | |
| LIMIT $2; |
| fn host_allowed(&self, authority: &str) -> bool { | ||
| match parse_authority(authority) { | ||
| Some((host, port)) => { | ||
| is_loopback_host(&host) && port.is_none_or(|port| port == self.listen_port) | ||
| } | ||
| None => false, | ||
| } | ||
| } |
There was a problem hiding this comment.
A loopback bind to any address other than 127.0.0.1/::1 (e.g. 127.0.0.2, or 127.x.x.x generally) enables strict host validation, but host_allowed only accepts the hosts localhost, 127.0.0.1 and ::1. A legitimate non-browser client (curl, a local tool) reaching the server at its actual bind address sends Host: 127.0.0.2:3000, which host_allowed rejects — every request to such a deployment is answered with 403. BrowserRequestPolicy::new already computes the bind address in own_origins; the Host check should accept the bind address itself (and arguably the whole 127.0.0.0/8 loopback range), not just the three well-known names. The existing tests only exercise 127.0.0.1, so this is untested.
Suggestion:
| fn host_allowed(&self, authority: &str) -> bool { | |
| match parse_authority(authority) { | |
| Some((host, port)) => { | |
| is_loopback_host(&host) && port.is_none_or(|port| port == self.listen_port) | |
| } | |
| None => false, | |
| } | |
| } | |
| fn host_allowed(&self, authority: &str) -> bool { | |
| match parse_authority(authority) { | |
| Some((host, port)) => { | |
| (is_loopback_host(&host) || Some(&host) == self.bind_host.as_ref()) | |
| && port.is_none_or(|port| port == self.listen_port) | |
| } | |
| None => false, | |
| } | |
| } |
| pub fn try_subscribe(&self, client_ip: IpAddr) -> Option<StreamEventsSubscription> { | ||
| let _ip_slot = self.try_acquire_ip_slot(client_ip)?; |
There was a problem hiding this comment.
The per-IP subscriber cap is keyed on ConnectInfo's socket address, but this deployment expects a reverse proxy (see the x-accel-buffering header set in api/stream.rs). Behind nginx (or any TCP proxy, or large-scale NAT), ConnectInfo reports the proxy's/NAT's address, so all external clients share one IP and collectively exhaust MAX_STREAM_SUBSCRIBERS_PER_IP = 16 slots — legitimate users will get locked out with TooManyStreamConnections. Consider deriving the key from a trusted forwarded-for header (validated against a configured trusted-proxy allowlist), making the per-IP cap configurable, or documenting that the limit assumes direct client connections.
| if canonical.is_loopback() || canonical.is_unspecified() { | ||
| return None; | ||
| } |
There was a problem hiding this comment.
The loopback and unspecified exemption means any address canonicalizing to loopback (including v4-mapped forms like ::ffff:127.0.0.1) bypasses the per-IP handshake limit entirely. Since only the global MAX_CONCURRENT_HANDSHAKES cap remains, a compromised or busy local process can occupy all 100 handshake slots and starve legitimate remote peers. Consider either applying the per-IP cap to loopback addresses as well (with a dedicated key) or documenting why local traffic is intentionally unbounded.
| if self.recently_served_transactions.contains(&tx_id) | ||
| || self.pending_tx_responses.iter().any(|pending| pending.tx_id == tx_id) | ||
| { | ||
| return Err(P2pError::ProtocolError( | ||
| ProtocolError::DuplicatedTransactionRequest(tx_id), | ||
| )); | ||
| } |
There was a problem hiding this comment.
The duplicate-request ban also fires while the first response is still sitting in pending_tx_responses awaiting serving budget, i.e. before the peer has actually received anything. Under tx serving pacing (bucket exhaustion, MAX_PENDING_TX_RESPONSES backlog) the queued response can be delayed indefinitely, so a peer that times out and re-requests the same id gets a ban score via DuplicatedTransactionRequest even though its first request was never answered. This contradicts the documented invariant in the RecentlyServedTransactions docs ("a peer that never receives it ... isn't punished for re-requesting it"), which only holds after the response has been dequeued and sent. Consider distinguishing "already answered" (track ids of dequeued responses only, as done) from "answer still queued" (a re-request for a still-pending id should be ignored or tolerated rather than punished).
Suggestion:
| if self.recently_served_transactions.contains(&tx_id) | |
| || self.pending_tx_responses.iter().any(|pending| pending.tx_id == tx_id) | |
| { | |
| return Err(P2pError::ProtocolError( | |
| ProtocolError::DuplicatedTransactionRequest(tx_id), | |
| )); | |
| } | |
| if self.recently_served_transactions.contains(&tx_id) { | |
| return Err(P2pError::ProtocolError( | |
| ProtocolError::DuplicatedTransactionRequest(tx_id), | |
| )); | |
| } | |
| // A response still awaiting serving budget hasn't reached the peer yet; | |
| // silently drop the duplicate request instead of punishing the peer. | |
| if self.pending_tx_responses.iter().any(|pending| pending.tx_id == tx_id) { | |
| return Ok(()); | |
| } |
| Err(err) => { | ||
| db_tx.abort(); | ||
| Self::reload_accounts_from_db(&self.db, &mut self.accounts, unused)?; | ||
| Err(err) | ||
| } |
There was a problem hiding this comment.
On all rollback paths here (and in for_account_rw, for_account_rw_unlocked, for_account_key_chain_rw_unlocked, scan_new_blocks), the reload-from-DB call uses ?. If the reload itself fails, the original error (the actual cause, e.g. the commit failure or the callback error) is replaced by the reload error, and the wallet is left with inconsistent in-memory state while the caller sees an unrelated error. Consider logging the original error before attempting the reload, or returning the original error (optionally annotated) so the root cause is never lost.
Suggestion:
| Err(err) => { | |
| db_tx.abort(); | |
| Self::reload_accounts_from_db(&self.db, &mut self.accounts, unused)?; | |
| Err(err) | |
| } | |
| Err(err) => { | |
| db_tx.abort(); | |
| if let Err(reload_err) = | |
| Self::reload_accounts_from_db(&self.db, &mut self.accounts, unused) | |
| { | |
| log::error!("failed to reload accounts after transaction failure: {reload_err}"); | |
| } | |
| Err(err) | |
| } |
| rpc_client: &N, | ||
| ptx: &PartiallySignedTransaction, | ||
| ) -> Result<(), ControllerError<N>> { | ||
| for (input, input_utxo) in ptx.tx().inputs().iter().zip(ptx.input_utxos()) { |
There was a problem hiding this comment.
zip silently truncates to the shorter iterator. A PartiallySignedTransaction reaching this path can have input_utxos shorter than tx.inputs() — the RPC entry point decodes it from raw bytes via the derived Decode impl (sign_raw_transaction in wallet-rpc-lib/src/rpc/mod.rs), which never runs ensure_consistency, so the inputs.len() == input_utxos.len() invariant enforced only in PartiallySignedTransactionV1::new is not guaranteed here. A crafted PTX can omit the trailing UTXO payloads, and those inputs will be signed without the node cross-check this function exists to enforce. Check the lengths up front and fail closed on a mismatch instead of letting zip skip the tail.
Suggestion:
| for (input, input_utxo) in ptx.tx().inputs().iter().zip(ptx.input_utxos()) { | |
| utils::ensure!( | |
| ptx.tx().inputs().len() == ptx.input_utxos().len(), | |
| ControllerError::WalletError(WalletError::PartiallySignedTransactionUtxoCountMismatch) | |
| ); | |
| for (input, input_utxo) in ptx.tx().inputs().iter().zip(ptx.input_utxos()) { |
| @@ -89,16 +89,77 @@ where | |||
| } | |||
|
|
|||
| async fn event_loop(mut self) { | |||
| // Commands that arrive while a unit of background work owns the wallet are | |||
| // buffered here and executed at the next work boundary. | |||
| let mut deferred_commands = VecDeque::<WalletCommand<N>>::new(); | |||
There was a problem hiding this comment.
deferred_commands is unbounded and the command channel (CommandSender<N>) is an unbounded mpsc, so while a unit of background work owns the wallet (which per the SHUTDOWN_TIMEOUT comment can take up to ~120s with a hardware wallet), incoming RPC commands accumulate with no cap. A flooding client can grow memory without bound, and no backpressure or rejection is applied to senders. Consider bounding the queue (or the channel) and rejecting/deferring with an error response once the cap is exceeded.
Suggestion:
| let mut deferred_commands = VecDeque::<WalletCommand<N>>::new(); | |
| // Bound the buffer so a client cannot accumulate unbounded commands while a | |
| // long hardware-wallet unit of work owns the wallet; excess commands should | |
| // be rejected with an error instead of queued indefinitely. |
| env: | ||
| # The value originates in the PR's Cargo.toml; pass it as an environment | ||
| # variable instead of ${{ }} interpolation so it cannot inject shell. | ||
| RUST_VERSION: ${{ steps.extract_cargo_info.outputs.RUST_VERSION }} |
There was a problem hiding this comment.
While RUST_VERSION is now safely passed via env (no shell injection), the sibling outputs TREZOR_REPO_REV and LEDGER_REPO_REV — also derived from PR-controlled Cargo.toml — are passed directly as ref: to actions/checkout of external repositories (mintlayer/mintlayer-trezor-firmware, mintlayer/mintlayer-ledger-app) with no validation. A malicious PR can point these at an attacker-controlled commit/repo, causing attacker-authored firmware/tooling to be built and executed in CI. Consider validating these outputs against an allow-list (e.g. commit-SHA regex or known-rev pinning) in the extract step, mirroring the hardening done here for RUST_VERSION.
Suggestion:
| env: | |
| # The value originates in the PR's Cargo.toml; pass it as an environment | |
| # variable instead of ${{ }} interpolation so it cannot inject shell. | |
| RUST_VERSION: ${{ steps.extract_cargo_info.outputs.RUST_VERSION }} | |
| env: | |
| # The value originates in the PR's Cargo.toml; pass it as an environment | |
| # variable instead of ${{ }} interpolation so it cannot inject shell. | |
| RUST_VERSION: ${{ steps.extract_cargo_info.outputs.RUST_VERSION }} | |
| # Additionally validate RUST_VERSION / TREZOR_REPO_REV / LEDGER_REPO_REV | |
| # against an allow-list (e.g. ^[0-9a-f]{40}$ or a known-tag set) since a | |
| # malicious PR controls their values. |
| // unauthenticated explorer endpoints feed it directly, so one pathological query must | ||
| // not pin a connection indefinitely. The timeout is per statement; the scanner's | ||
| // multi-statement batches are unaffected as long as each statement stays bounded. | ||
| config.options("--statement_timeout=60000"); |
There was a problem hiding this comment.
The statement timeout is hardcoded as a connection-option string on the shared connection_config, so it silently applies to every session built from it — pooled explorer connections, but also any other dedicated connection derived from this config (e.g. acquire_single_writer_lock connects with the same config). Under load a legitimately slow scanner statement now fails with a generic timeout error rather than a diagnosable one, and the 60s value is not configurable per deployment. Consider making it a config knob (or at least a named constant with context in the error surfaced when a statement times out). Also note config.options(...) replaces any pre-existing options string rather than appending to it.
Suggestion:
| config.options("--statement_timeout=60000"); | |
| // Make the timeout configurable, e.g. via PostgresConfig, and append | |
| // instead of overwriting any user-supplied options. | |
| config.options(&format!("--statement_timeout={POSTGRES_STATEMENT_TIMEOUT_MS}")); |
| logging::log::info!("Scanner single-writer advisory lock acquired"); | ||
| Ok(SingleWriterGuard { | ||
| _client: client, | ||
| _driver: driver, | ||
| }) |
There was a problem hiding this comment.
The single-writer lock can be silently lost while the daemon keeps writing. If the dedicated lock connection dies (network blip, server restart, idle-session termination), Postgres releases the session-level advisory lock server-side, but this process keeps running and its guard still looks valid: the scanner's subsequent batches run on the pool connections and will succeed without any lock protection, so a second daemon that starts afterwards acquires the lock and the two writers interleave batches — exactly the corruption scenario the lock is meant to prevent. The doc comment defers to a 'batch-level retry with a loud log' safety net, but nothing here or in the caller (scanner-daemon/src/main.rs just holds the guard) observes the driver task or the client's liveness. Suggest monitoring the driver JoinHandle / connection state while the daemon runs and failing loudly or re-acquiring the lock when the lock connection is lost.
Suggestion:
| logging::log::info!("Scanner single-writer advisory lock acquired"); | |
| Ok(SingleWriterGuard { | |
| _client: client, | |
| _driver: driver, | |
| }) | |
| logging::log::info!("Scanner single-writer advisory lock acquired"); | |
| Ok(SingleWriterGuard { | |
| _client: client, | |
| _driver: driver, | |
| }) | |
| // Caller-side: supervise the driver task / connection liveness for the | |
| // daemon's lifetime; a dead lock connection means the lock was released | |
| // server-side and the daemon must stop or re-acquire before writing. |
| TxOutput::ProduceBlockFromStake(_, _) | ||
| | TxOutput::CreateDelegationId(_, _) | ||
| | TxOutput::IssueFungibleToken(_) | ||
| | TxOutput::IssueNft(_, _, _) | ||
| | TxOutput::DataDeposit(_) | ||
| | TxOutput::CreateOrder(_) => Some(Amount::ZERO), |
There was a problem hiding this comment.
This arm undercounts the chain supply the same way as the confirmed CreateOrder case: a genesis DataDeposit output locks a real coin amount that is spendable when the deposit is spent, and a genesis ProduceBlockFromStake output locks the staked coin until the referenced block is produced. Mapping both to Amount::ZERO makes chain_total_supply return a total that is short by exactly those amounts, so trusted_fee_caps derives a cap below twice the true supply. A custom chain with large data deposits (or stake-kernel outputs) in its genesis could then have consensus-valid fees/blocks rejected with TrustedFeeOutOfRange/TrustedBlockFeeOutOfRange, wedging the indexer on a legitimately valid batch.
Suggestion:
| TxOutput::ProduceBlockFromStake(_, _) | |
| | TxOutput::CreateDelegationId(_, _) | |
| | TxOutput::IssueFungibleToken(_) | |
| | TxOutput::IssueNft(_, _, _) | |
| | TxOutput::DataDeposit(_) | |
| | TxOutput::CreateOrder(_) => Some(Amount::ZERO), | |
| TxOutput::DataDeposit(value) => Some(value.coin_amount().unwrap_or(Amount::ZERO)), | |
| TxOutput::ProduceBlockFromStake(value, _) => { | |
| Some(value.coin_amount().unwrap_or(Amount::ZERO)) | |
| } | |
| TxOutput::CreateDelegationId(_, _) | |
| | TxOutput::IssueFungibleToken(_) | |
| | TxOutput::IssueNft(_, _, _) | |
| | TxOutput::CreateOrder(_) => Some(Amount::ZERO), |
| // A missing input UTXO is node-supplied data the index cannot | ||
| // explain (e.g. a spend of an exotic, unindexed genesis output); | ||
| // report it as a batch error instead of panicking, so the sync | ||
| // loop skips and re-fetches the batch with a loud log rather | ||
| // than crash-looping on it. |
There was a problem hiding this comment.
This error path permanently wedges the indexer instead of just skipping a batch. A missing input UTXO is a deterministic failure: the same batch will be re-fetched and fail identically on every attempt. supervise_sync (scanner-daemon/src/lib.rs) retries sync errors forever with only a capped backoff and no attempt bound or permanent/transient distinction, so a single unindexed exotic genesis output (or any other deterministic per-batch rejection like TrustedFeeOutOfRange from a misbehaving node) stops indexing progress indefinitely, with only log lines to notice. The comment's "the sync loop skips and re-fetches the batch" overstates the recovery: skipping cannot make progress here. Consider bounding retries per batch height, or classifying these InvalidBlock/LowLevelStorageError rejections as operator-visible fatal/poison conditions that skip the offending height explicitly.
Suggestion:
| // A missing input UTXO is node-supplied data the index cannot | |
| // explain (e.g. a spend of an exotic, unindexed genesis output); | |
| // report it as a batch error instead of panicking, so the sync | |
| // loop skips and re-fetches the batch with a loud log rather | |
| // than crash-looping on it. | |
| // A missing input UTXO is node-supplied data the index cannot | |
| // explain (e.g. a spend of an exotic, unindexed genesis output); | |
| // report it as a batch error instead of panicking. Note: the | |
| // failure is deterministic, so the supervisor will retry the same | |
| // batch forever unless this error class is treated as fatal or | |
| // the offending height is skipped explicitly. |
| if !self.known_transactions.contains(&tx_id) { | ||
| return Err(P2pError::ProtocolError( | ||
| ProtocolError::UnknownTransactionRequested(tx_id), | ||
| )); | ||
| } |
There was a problem hiding this comment.
The new UnknownTransactionRequested ban is gated on known_transactions.contains(&tx_id), but KnownTransactions is a rolling bloom filter (capacity 50 000, see peer_common/known_transactions.rs) that forgets the oldest ids once capacity is exceeded — the code elsewhere in this very file acknowledges the filter "can have false negatives". A peer that legitimately relays enough transactions to push an announced id out of the filter before it issues the corresponding TransactionRequest will now be disconnected/discouraged for the request that bitcoin-core, as the comment itself notes, merely ignores. Since a punishment must not be evadable but also must not punish honest peers, consider tracking announced-requestable ids exactly (e.g. in RecentlyServedTransactions-like bounded structures, or only serving without punishing), or lowering this from a ban-scored error to an ignored request.
Suggestion:
| if !self.known_transactions.contains(&tx_id) { | |
| return Err(P2pError::ProtocolError( | |
| ProtocolError::UnknownTransactionRequested(tx_id), | |
| )); | |
| } | |
| // Serve nothing but don't punish: `known_transactions` is a rolling bloom | |
| // filter, so a false negative here would disconnect an honest peer. | |
| if !self.known_transactions.contains(&tx_id) { | |
| log::debug!("Ignoring transaction request for unannounced tx {tx_id:x}"); | |
| return Ok(()); | |
| } |
| pub fn from_bytes(bytes: E) -> Result<Self, Error> { | ||
| let _phantom = Default::default(); | ||
| let this = Self { bytes, _phantom }; | ||
| T::decode_all(&mut this.bytes())?; | ||
| Ok(this) | ||
| } |
There was a problem hiding this comment.
Encoded::from_bytes runs a full decode_all at construction, and decode() later runs decode_all again, so every value fetched through the new storage::database::internal::get path decodes twice. For hot read paths this roughly doubles decode work. If this is intentional (validation only at the storage boundary) consider documenting it, or add a checked-construction internal path that carries the Result forward so the later decode() need not re-validate.
| assert!( | ||
| T::decode_all(&mut this.bytes()).is_ok(), | ||
| "from_bytes_unchecked called with an invalid encoding" | ||
| ); |
There was a problem hiding this comment.
The new unconditional assert! in from_bytes_unchecked panics in release builds, but the storage layer's migration is incomplete: storage/src/database/internal.rs still calls from_bytes_unchecked on raw database keys/values in prefix_iter, prefix_iter_keys, greater_equal_iter, and greater_equal_iter_keys (only get and the try_* iterators were migrated to Encoded::from_bytes with Error::Fatal(Fatal::DatabaseCorrupted)). A single corrupted row surfaced by one of those iterators will now abort the whole process, exactly the failure mode this change intends to turn into a recoverable error. Either migrate those call sites to the fallible constructor, or keep the panic behavior scoped and documented.
Suggestion:
| assert!( | |
| T::decode_all(&mut this.bytes()).is_ok(), | |
| "from_bytes_unchecked called with an invalid encoding" | |
| ); | |
| assert!( | |
| T::decode_all(&mut this.bytes()).is_ok(), | |
| "from_bytes_unchecked called with an invalid encoding" | |
| ); | |
| // Note: callers reading persisted data (e.g. storage/src/database/internal.rs | |
| // prefix_iter/greater_equal_iter) must migrate to `from_bytes` first, otherwise | |
| // a corrupted DB row aborts the process here in release builds. |
| /// The longest wait for a device operation before it is abandoned with an error. | ||
| /// Deliberately generous: an operation that requires user interaction with the | ||
| /// device is slow even when everything works. | ||
| const DEVICE_OPERATION_TIMEOUT: Duration = Duration::from_secs(120); |
There was a problem hiding this comment.
DEVICE_OPERATION_TIMEOUT (120s) bounds the entire blocking operation, including time the device spends waiting for the user to review and confirm a transaction or message on its screen. A user who takes longer than two minutes to confirm will get TrezorError::DeviceOperationTimeout, and because the abandoned blocking closure keeps holding the client mutex, every subsequent device operation will report TrezorError::DeviceBusy until the process is restarted. Consider differentiating between transport inactivity (where a timeout is safe) and user-confirmation phases (where an operation can legitimately wait indefinitely), or at least recovering from DeviceBusy by dropping and re-creating the client instead of requiring a restart.
Suggestion:
| const DEVICE_OPERATION_TIMEOUT: Duration = Duration::from_secs(120); | |
| const DEVICE_OPERATION_TIMEOUT: Duration = Duration::from_secs(120); | |
| // TODO: a user taking >120s to confirm on the device leaves the abandoned closure | |
| // holding the client mutex; subsequent operations then fail with DeviceBusy until | |
| // restart. Consider re-creating the client on DeviceBusy instead. |
| restrict_history_file_permissions(&file_name) | ||
| .map_err(|e| WalletCliError::FileError(file_name, e.to_string()))?; |
There was a problem hiding this comment.
The history file is created by FileBackedHistory::with_file with the process default umask permissions, and only afterwards is chmod 0o600 applied. Between creation and this call there is a window (and, if the process were to fail in between, permanently) during which a file containing possibly sensitive command lines (seed phrases, passphrases) is group/world-readable. Close the race by creating the file with 0o600 before handing it to reedline, e.g. via OpenOptions::new().mode(0o600).create(true).write(true).open(...) on unix before constructing the history, or check/repair the mode on every startup rather than only after creation.
Suggestion:
| restrict_history_file_permissions(&file_name) | |
| .map_err(|e| WalletCliError::FileError(file_name, e.to_string()))?; | |
| // Create the file with owner-only permissions before reedline opens it, | |
| // so the contents are never readable by others, even transiently. | |
| #[cfg(unix)] | |
| { | |
| use std::io::Write; | |
| use std::os::unix::fs::OpenOptionsExt; | |
| std::fs::OpenOptions::new() | |
| .mode(0o600) | |
| .create(true) | |
| .append(true) | |
| .open(&file_name) | |
| .and_then(|mut f| f.flush()) | |
| .map_err(|e| WalletCliError::FileError(file_name.clone(), e.to_string()))?; | |
| } | |
| restrict_history_file_permissions(&file_name) | |
| .map_err(|e| WalletCliError::FileError(file_name, e.to_string()))?; |
| for arg_id in COMMAND_LINE_REJECTED_ARG_IDS { | ||
| if matches.value_source(arg_id) == Some(clap::parser::ValueSource::CommandLine) { |
There was a problem hiding this comment.
parse_args_or_exit is generic over any clap::Parser, but reject_command_line_secrets unconditionally calls matches.value_source("postgres_password"). In clap, ArgMatches::value_source panics when the id does not exist in the matches. Both current callers (scanner-daemon, web-server) flatten PostgresConfig, so today the id always exists — but any future binary that reuses this helper without PostgresConfig (or if the option is ever renamed) will panic at startup instead of producing a clear error. Look up the argument on command first and skip when absent.
Suggestion:
| for arg_id in COMMAND_LINE_REJECTED_ARG_IDS { | |
| if matches.value_source(arg_id) == Some(clap::parser::ValueSource::CommandLine) { | |
| for arg_id in COMMAND_LINE_REJECTED_ARG_IDS { | |
| let arg_exists = command.get_arguments().any(|arg| arg.get_id() == *arg_id); | |
| if arg_exists | |
| && matches.value_source(arg_id) == Some(clap::parser::ValueSource::CommandLine) | |
| { |
| for transaction_id in transaction_ids { | ||
| if let Err(position) = rows.binary_search(&transaction_id) { | ||
| rows.insert(position, transaction_id); | ||
| } | ||
| } |
There was a problem hiding this comment.
Backend-consistency issue with the new max_rows truncation: the in-memory rows are ordered by Id<Transaction>'s derived Ord, while the Postgres query orders by transaction_id DESC on the stored bytea encoding. Derived Ord on Id compares the struct fields (e.g. hash type tag first), not the raw big-endian encoding, so when an address has more than max_rows transactions the two backends can return a different subset of rows for the same request. This is the same truncation-order divergence already noted for outpoints, applied to the address-transactions listing.
Suggestion:
| for transaction_id in transaction_ids { | |
| if let Err(position) = rows.binary_search(&transaction_id) { | |
| rows.insert(position, transaction_id); | |
| } | |
| } | |
| // Order/truncate by the same key as the postgres backend (the raw byte | |
| // encoding of the transaction id), so both backends return the same | |
| // subset when the result must be truncated to `max_rows`. | |
| for transaction_id in transaction_ids { | |
| if let Err(position) = rows.binary_search(&transaction_id) { | |
| rows.insert(position, transaction_id); | |
| } | |
| } |
| if buckets.len() >= inner.max_tracked_addresses { | ||
| let stale_after = inner.stale_after; | ||
| buckets.retain(|_, bucket| now.duration_since(bucket.last_seen) <= stale_after); | ||
| if buckets.len() >= inner.max_tracked_addresses { | ||
| return false; | ||
| } | ||
| } |
There was a problem hiding this comment.
Once the tracked-address bound is exhausted and no entries are stale, every request from a new address pays a full buckets.retain scan (up to 65,536 entries) while holding the mutex that guards all rate-limit accounting, including the fast path of tracked addresses. An attacker with MAX_TRACKED_ADDRESSES distinct active addresses turns every subsequent request into a bounded-but-lock-held O(n) scan, serializing and slowing all clients on the CPU work. Consider evicting incrementally (e.g. maintain a staleness-ordered structure and only evict as many entries as needed to admit the new address) or failing fast with a cheap last-full-sweep timestamp instead of scanning the whole map on each new-address request.
Suggestion:
| if buckets.len() >= inner.max_tracked_addresses { | |
| let stale_after = inner.stale_after; | |
| buckets.retain(|_, bucket| now.duration_since(bucket.last_seen) <= stale_after); | |
| if buckets.len() >= inner.max_tracked_addresses { | |
| return false; | |
| } | |
| } | |
| if buckets.len() >= inner.max_tracked_addresses { | |
| let stale_after = inner.stale_after; | |
| buckets.retain(|_, bucket| now.duration_since(bucket.last_seen) <= stale_after); | |
| if buckets.len() >= inner.max_tracked_addresses { | |
| return false; | |
| } | |
| } | |
| // Alternative: track `last_full_sweep: Instant` and skip the retain when the | |
| // previous sweep is younger than `stale_after` — no entry can have gone stale | |
| // within that window, so the O(n) scan is unnecessary and the lock is held only | |
| // for the constant-time bucket update. |
| other.tx_undos.into_iter().try_for_each(|(id, op)| { | ||
| let result = combine(self.tx_undos.get(&id).cloned(), Some(op)) | ||
| .map_err(|err| UtxosBlockUndoError::CacheInvariantViolation(err.to_string()))?; | ||
| if let Some(result) = result { | ||
| self.tx_undos.insert(id, result); | ||
| } | ||
| }); | ||
| Ok(()) | ||
| })?; |
There was a problem hiding this comment.
On a CacheOperationError the merge bails out mid-iteration, but entries combined before the failure have already been inserted into self (and other has been drained via into_iter). This leaves the cache partially merged and inconsistent, yet the containing TransactionVerifier keeps running and may silently reuse this corrupted state for subsequent verification instead of surfacing a clear "cache poisoned" condition. Since these errors signal an internal invariant break, consider either (a) computing all combined results first and only inserting after every entry merges successfully, or (b) documenting/marking the cache as poisoned so later operations fail fast.
Suggestion:
| other.tx_undos.into_iter().try_for_each(|(id, op)| { | |
| let result = combine(self.tx_undos.get(&id).cloned(), Some(op)) | |
| .map_err(|err| UtxosBlockUndoError::CacheInvariantViolation(err.to_string()))?; | |
| if let Some(result) = result { | |
| self.tx_undos.insert(id, result); | |
| } | |
| }); | |
| Ok(()) | |
| })?; | |
| // Combine all entries first; only mutate `self` if every merge succeeds, | |
| // so a failed combine cannot leave the cache partially merged. | |
| let mut combined = Vec::new(); | |
| for (id, op) in other.tx_undos { | |
| let result = combine(self.tx_undos.get(&id).cloned(), Some(op)) | |
| .map_err(|err| UtxosBlockUndoError::CacheInvariantViolation(err.to_string()))?; | |
| combined.push((id, result)); | |
| } | |
| for (id, result) in combined { | |
| if let Some(result) = result { | |
| self.tx_undos.insert(id, result); | |
| } | |
| } |
| let time_diff = current_time | ||
| .saturating_sub(self.last_rolling_fee_update) | ||
| .min(config::ROLLING_FEE_MAX_DECAY_WINDOW); |
There was a problem hiding this comment.
The forward-jump clamp uses ROLLING_FEE_MAX_DECAY_WINDOW (= ROLLING_FEE_BASE_HALFLIFE), but the half-life passed to decay_fee can be as small as one quarter of the base half-life (rolling_fee_halflife() returns BASE_HALFLIFE / 4 when pool memory usage is below max_size/4). In that regime a single clock jump clamped to one base half-life applies up to four halvings (a 16x reduction) in one event, contradicting the stated intent that "one event cannot collapse the rolling minimum fee rate". Clamp the decay window to one caller-provided half-life instead, e.g. .min(halflife), so a single decay event never reduces the rate by more than one half regardless of the configured half-life.
Suggestion:
| let time_diff = current_time | |
| .saturating_sub(self.last_rolling_fee_update) | |
| .min(config::ROLLING_FEE_MAX_DECAY_WINDOW); | |
| let time_diff = current_time | |
| .saturating_sub(self.last_rolling_fee_update) | |
| .min(halflife); |
| /// Create `Encoded` from raw encoding. It is responsibility of the caller to ensure the byte | ||
| /// sequence constitutes a valid encoding of an object of type `T`. | ||
| /// | ||
| /// The bytes are validated unconditionally (debug and release builds alike), so misuse | ||
| /// aborts here with a clear message instead of inside [Self::decode] later. | ||
| pub fn from_bytes_unchecked(bytes: E) -> Self { |
There was a problem hiding this comment.
from_bytes_unchecked now panics unconditionally (including release builds). Cross-checking the codebase, storage/src/database/internal.rs::prefix_iter/prefix_iter_keys/greater_equal_iter/greater_equal_iter_keys still feed raw database bytes (keys and values) to from_bytes_unchecked. The same update added fallible paths (Encoded::from_bytes -> DatabaseCorrupted) for get and decode_entry precisely to surface corrupted rows as typed errors, but these iterator paths were left unchecked: a single undecodable/corrupted DB row encountered during iteration will now abort the whole node process in production instead of returning a DatabaseCorrupted error. Consider migrating these iterator call sites to the new fallible constructor (their signatures already return crate::Result), or at least keeping the debug-only assertion for the pre-existing DB-backed callers.
| Err(err) => { | ||
| db_tx.abort(); | ||
| let ro_tx = self.db.transaction_ro()?; | ||
| self.next_unused_account.1.reload_from_database(&ro_tx)?; | ||
| return Err(err); | ||
| } |
There was a problem hiding this comment.
In this error path (and the commit-failure path), reload_from_database is called with ?; if the reload itself fails, its error replaces the original scan error, so the caller loses the root cause. The same masking pattern appears in for_accounts_rw and for_account_rw_unlocked. Additionally, scan_new_blocks may have already delivered wallet_events for transactions before the rollback, so consumers can receive events for data that was never committed — consider deferring event emission until after a successful commit, and logging the original error before propagating the reload failure.
Suggestion:
| Err(err) => { | |
| db_tx.abort(); | |
| let ro_tx = self.db.transaction_ro()?; | |
| self.next_unused_account.1.reload_from_database(&ro_tx)?; | |
| return Err(err); | |
| } | |
| Err(err) => { | |
| db_tx.abort(); | |
| let ro_tx = self.db.transaction_ro()?; | |
| if let Err(reload_err) = self.next_unused_account.1.reload_from_database(&ro_tx) { | |
| log::error!("Failed to reload account after scan error {:?}: {:?}", err, reload_err); | |
| } | |
| return Err(err); | |
| } |
| let ask_atoms = info.initially_asked.amount().amount().into_atoms(); | ||
| if ask_atoms == 0 { | ||
| log::warn!("Order {} has zero ask amount, skipping price", info.order_id); | ||
| return None; | ||
| } |
There was a problem hiding this comment.
The log message says the price is being skipped, but returning None here drops the entire order from the displayed list, not just its price. A zero-ask order is still an active order the user owns; silently hiding it while the message implies only the price column is affected is misleading. Consider keeping the order (e.g. render the price as N/A) or fixing the message to say the order is skipped.
Suggestion:
| let ask_atoms = info.initially_asked.amount().amount().into_atoms(); | |
| if ask_atoms == 0 { | |
| log::warn!("Order {} has zero ask amount, skipping price", info.order_id); | |
| return None; | |
| } | |
| let ask_atoms = info.initially_asked.amount().amount().into_atoms(); | |
| if ask_atoms == 0 { | |
| log::warn!("Order {} has zero ask amount, skipping the order", info.order_id); | |
| return None; | |
| } |
| let Some(token1_id) = token_ids_map.get(token1_id_as_addr) else { | ||
| return token1_id_as_addr.cmp(token2_id_as_addr); | ||
| }; | ||
| let Some(token2_id) = token_ids_map.get(token2_id_as_addr) else { | ||
| return token1_id_as_addr.cmp(token2_id_as_addr); | ||
| }; |
There was a problem hiding this comment.
The comparator mixes two ordering schemes: ticker-based ordering for tokens present in token_ids_map and raw address comparison when an id is missing. If the fallback path triggers for some but not all tokens, the combined relation is not guaranteed to be a total order (ticker order can contradict address order across a missing token), and Rust's sort implementations panic with "user-provided comparison function does not correctly implement a total order" on intransitive comparators. Since this fallback exists specifically for the case where the comment's assumption fails, consider falling back consistently (e.g. always compare ids by address as the tiebreaker when either ticker lookup misses), or comparing (Option, address) uniformly for both sides.
| // Give priority to user request processing | ||
| command = self.command_rx.recv(), if !command_channel_closed => { | ||
| match command { | ||
| // While background work owns the wallet, commands are buffered | ||
| // and executed at the next work boundary. | ||
| Some(command) => deferred_commands.push_back(command), | ||
| None => command_channel_closed = true, | ||
| } | ||
| } |
There was a problem hiding this comment.
While a background unit owns the wallet, all incoming user commands (including Stop) are deferred until the unit completes. A single unit is do_periodic_work, whose first step sync_once can take an unbounded amount of time (e.g. a full initial blockchain scan, or device operations of up to DEVICE_OPERATION_TIMEOUT each), so the RPC surface can be unresponsive for minutes with no bound or progress feedback. Previously Controller::run ran in the same select loop so commands interleaved at await points. Consider bounding the deferral window (e.g. splitting the unit into smaller awaits, or surfacing a 'wallet busy' error/status after a cap) so interactive calls are not starved behind a long sync.
Suggestion:
| // Give priority to user request processing | |
| command = self.command_rx.recv(), if !command_channel_closed => { | |
| match command { | |
| // While background work owns the wallet, commands are buffered | |
| // and executed at the next work boundary. | |
| Some(command) => deferred_commands.push_back(command), | |
| None => command_channel_closed = true, | |
| } | |
| } | |
| // Give priority to user request processing | |
| command = self.command_rx.recv(), if !command_channel_closed => { | |
| match command { | |
| // While background work owns the wallet, commands are buffered | |
| // and executed at the next work boundary. | |
| Some(command) => deferred_commands.push_back(command), | |
| None => command_channel_closed = true, | |
| } | |
| } | |
| // TODO: consider bounding how long a unit of background work may defer | |
| // user commands (e.g. a full blockchain scan in sync_once), since RPC | |
| // calls now block until the in-flight unit completes. |
| .rev() | ||
| .flat_map(|txs| txs.iter().rev()) | ||
| .cloned() | ||
| .take(max_rows as usize) |
There was a problem hiding this comment.
Same backend-consistency issue as the delegations above, now that max_rows truncation is applied: the in-memory backend truncates over BTreeSet<UtxoOutPoint> (derived struct Ord, i.e. txid/index field order), while the postgres queries order by the serialized bytea outpoint encoding (ORDER BY ua.outpoint / ORDER BY outpoint), whose lexicographic order differs from the struct Ord. For addresses holding more than max_rows UTXOs, the two backends can return different subsets. Note also that in the postgres get_address_all_utxos UNION query the unqualified ORDER BY outpoint sorts across both branches, so the limit can evict spendable rows in favor of locked ones depending on byte order.
| (last.spend_destination() == address) | ||
| .then_some((delegation_id.to_owned(), last.clone())) | ||
| }) | ||
| .take(max_rows as usize) | ||
| .collect()) |
There was a problem hiding this comment.
The new max_rows truncation makes the returned subset order-dependent, but the in-memory backend takes rows in DelegationId's derived Ord order (BTreeMap iteration), while the postgres backend orders by the bech32 text of the delegation id (ORDER BY delegation_id on ml.latest_delegations_cache). Those orderings do not agree in general, so with more delegations than max_rows the two backends can return different subsets for the same query. This is exactly the consistency property the get_pool_delegations implementation above deliberately establishes (ranking by Address::into_string() before truncating). Sort the candidates by the bech32 address string here too (or rank lazily) before take.
Suggestion:
| (last.spend_destination() == address) | |
| .then_some((delegation_id.to_owned(), last.clone())) | |
| }) | |
| .take(max_rows as usize) | |
| .collect()) | |
| (last.spend_destination() == address) | |
| .then_some((delegation_id.to_owned(), last.clone())) | |
| }) | |
| .collect::<Vec<_>>(); | |
| result.sort_by_key(|(delegation_id, _)| { | |
| Address::new(&self.chain_config, *delegation_id) | |
| .map(|a| a.into_string()) | |
| .unwrap_or_default() | |
| }); | |
| result.truncate(max_rows as usize); | |
| Ok(result) |
| fn restore_initial_data(&mut self) { | ||
| if let Some(initial_data_before_tx) = self.initial_data_before_tx.as_mut() { | ||
| std::mem::swap(&mut *self.transaction, initial_data_before_tx); | ||
| } | ||
| } |
There was a problem hiding this comment.
Starting every read-write transaction now clones the entire ApiServerInMemoryStorage (all BTreeMaps: transactions, UTXOs, addresses, token data, statistics) and keeps the snapshot alive for the transaction's lifetime. This makes each write transaction O(total state) in time and roughly doubles memory while held. With a fully-synced chain state this can dominate the cost of small writes. If the in-memory backend is only used for tests/wasm with modest state, at least document the scale at which this is acceptable; otherwise consider an undo-log (record the pre-image of mutated keys per transaction) instead of a whole-state snapshot.
| // In HTTP/2 the authority is carried by the URI instead of a Host header. | ||
| // If neither a Host header nor a URI authority is present the request | ||
| // passes; that path is only reachable for legacy HTTP/1.0 traffic, | ||
| // which relies on hyper requiring Host for HTTP/1.1. | ||
| if !host_seen && let Some(uri_host) = uri_host { |
There was a problem hiding this comment.
In the strict (loopback-bound) mode, the HTTP/2 authority check runs only when no Host header was seen (!host_seen && uri_host.is_some()). A request that carries a valid loopback Host header AND a conflicting URI authority — reachable in h2c-proxy scenarios where a fronting proxy injects Host while the h2 :authority names an attacker-controlled domain — is validated on the Host header alone and the authority is never checked, since h2 clients do not send a Host header and a present one here is by definition non-standard. Validating whichever of the two is present and failing closed when both exist and disagree would close this gap.
| } else { | ||
| match authority.rsplit_once(':') { | ||
| Some((host, port)) => (host, Some(port.parse::<u16>().ok()?)), | ||
| None => (authority, None), | ||
| } | ||
| }; |
There was a problem hiding this comment.
parse_authority mishandles an unbracketed IPv6 authority without a port: Host: ::1 is split at the last : into host :: and port 1, so a legitimate (if unusual) IPv6 literal Host header is turned into a wrong host/port pair rather than failing closed or parsing correctly. In the strict mode this results in a spurious rejection of a valid local request; in host_not_loopback it can wrongly pass, since host :: is not recognized by is_loopback_host the way ::1 is (it still passes only because :: parses as the unspecified address, not a loopback one). Prefer detecting an unbracketed multi-colon authority explicitly and rejecting it, mirroring how browsers always bracket IPv6 origins.
| let new_peer_bytes = peer_bytes.checked_sub(bytes).unwrap_or_else(|| { | ||
| debug_panic_or_log!("Egress byte accounting underflow for peer {peer_id}"); | ||
| 0 | ||
| }); | ||
| *peer_bytes = new_peer_bytes; | ||
| new_peer_bytes | ||
| } | ||
| None => return, | ||
| }; | ||
|
|
||
| state.total_bytes = state.total_bytes.saturating_sub(bytes); |
There was a problem hiding this comment.
When the per-peer account underflows (a double release, e.g. a socket writer release racing with release_all_for_peer after the connection teardown), the code detects the underflow but still subtracts the full bytes from the shared total_bytes via saturating_sub. Since those bytes were no longer (or never) accounted for this peer, the node-wide total is silently under-counted, permanently inflating the remaining budget and letting peers collectively exceed max_total_bytes. The corrupted-account branch should return without adjusting the total, or subtract only the amount actually removed from the per-peer account.
Suggestion:
| let new_peer_bytes = peer_bytes.checked_sub(bytes).unwrap_or_else(|| { | |
| debug_panic_or_log!("Egress byte accounting underflow for peer {peer_id}"); | |
| 0 | |
| }); | |
| *peer_bytes = new_peer_bytes; | |
| new_peer_bytes | |
| } | |
| None => return, | |
| }; | |
| state.total_bytes = state.total_bytes.saturating_sub(bytes); | |
| let released = match state.per_peer_bytes.get_mut(&peer_id) { | |
| Some(peer_bytes) => { | |
| let released = (*peer_bytes).min(bytes); | |
| if bytes > *peer_bytes { | |
| debug_panic_or_log!("Egress byte accounting underflow for peer {peer_id}"); | |
| } | |
| *peer_bytes -= released; | |
| released | |
| } | |
| None => return, | |
| }; | |
| state.total_bytes -= released; |
| fn send_command(&mut self, command: types::Command) -> crate::Result<()> { | ||
| self.cmd_sender.try_send(command).map_err(|err| { | ||
| log::error!("Failed to send a command to the backend: {err}"); | ||
| P2pError::ChannelClosed | ||
| }) | ||
| } |
There was a problem hiding this comment.
try_send on the bounded command channel can fail with TrySendError::Full (queue saturation) as well as TrySendError::Closed (backend gone), but both are mapped to P2pError::ChannelClosed. On a full queue, legitimate commands such as Disconnect, Accept, or sync messages are dropped and callers see a misleading "channel closed" error that normally signals backend shutdown (e.g. p2p/src/lib.rs matches Err(P2pError::ChannelClosed) if shutdown_.load()), so a congestion failure is indistinguishable from a shutdown-induced one and no backpressure is applied. Consider distinguishing the cases via err.is_full() / err.is_closed(), or awaiting send(...) here so the caller is throttled instead of losing the command.
Suggestion:
| fn send_command(&mut self, command: types::Command) -> crate::Result<()> { | |
| self.cmd_sender.try_send(command).map_err(|err| { | |
| log::error!("Failed to send a command to the backend: {err}"); | |
| P2pError::ChannelClosed | |
| }) | |
| } | |
| fn send_command(&mut self, command: types::Command) -> crate::Result<()> { | |
| match self.cmd_sender.try_send(command) { | |
| Ok(()) => Ok(()), | |
| Err(err) if err.is_closed() => { | |
| log::error!("Failed to send a command to the backend: {err}"); | |
| Err(P2pError::ChannelClosed) | |
| } | |
| Err(err) => { | |
| log::error!("Backend command queue is full: {err}"); | |
| Err(P2pError::Other("Backend command queue is full".into())) | |
| } | |
| } | |
| } |
| let address = peer_address.as_bannable(); | ||
| let accumulated = self.peerdb.record_recent_offense(address, score); |
There was a problem hiding this comment.
Sub-threshold offenses of a connected peer are recorded into the address-keyed recent-offense memory here, and then the same scores are recorded again when the peer disconnects (connection_closed calls record_recent_offense(address, peer.score) with the peer's full accumulated score). Each in-connection sub-threshold offense is thus counted twice against the address, inflating the accumulated score and potentially discouraging an address faster than the ban-score design intends. Either skip address recording for connected peers (letting connection_closed capture the final score), or on disconnect record only the offenses not already remembered.
Suggestion:
| let address = peer_address.as_bannable(); | |
| let accumulated = self.peerdb.record_recent_offense(address, score); | |
| let address = peer_address.as_bannable(); | |
| // Note: only for peers not tracked in `self.peers`; a connected peer's | |
| // score is remembered once, when its connection closes. | |
| let accumulated = self.peerdb.record_recent_offense(address, score); |
| if msg.oversized_reason() { | ||
| self.adjust_peer_score( | ||
| peer_id, | ||
| WILL_DISCONNECT_OVERSIZED_REASON_BAN_SCORE, | ||
| "Oversized WillDisconnect reason", | ||
| ); | ||
| } |
There was a problem hiding this comment.
The oversized-reason ban score is intentionally applied "while the peer is still connected" so it survives the disconnection, but adjust_peer_score now early-returns for any peer already in pending_disconnects. If the peer was already being disconnected (e.g. penalized or ping-timed-out moments earlier) and then sends a WillDisconnect with an oversized reason, the score adjustment is silently dropped and never reaches record_recent_offense in connection_closed (which only re-records peer.score). The comment's stated goal is defeated in exactly the ordering the comment warns about; consider recording address-keyed recent offenses even when the peer is already pending disconnect.
| match operation { | ||
| // The inner result is the operation outcome: a device error or a busy lock. | ||
| Ok(Ok(result)) => result.map_err(Into::into), | ||
| Ok(Err(join_error)) => Err(TrezorError::DeviceError(join_error.to_string()).into()), |
There was a problem hiding this comment.
A panicking device operation surfaces as a JoinError and is reported as TrezorError::DeviceError(join_error.to_string()), which converts an internal bug into a plausible-looking device failure and discards the panic payload/backtrace. Consider distinguishing the join error (e.g. a dedicated variant or preserving the panic message via join_error.into_panic()) so a genuine panic is diagnosable rather than masked as flaky hardware.
Suggestion:
| Ok(Err(join_error)) => Err(TrezorError::DeviceError(join_error.to_string()).into()), | |
| Ok(Err(join_error)) => Err(TrezorError::DeviceError(format!( | |
| "device operation task failed: {join_error}" | |
| ) | |
| .into())), |
| OutputValue::TokenV0(_) => { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Behavior change worth confirming: previously a block-reward Burn output fell into the shared arm that called set_utxo, so burn outputs of block rewards were indexed as spendable UTXOs. This new arm continues before set_utxo, so such outputs are no longer indexed at all. Any chain (including already-indexed history) that contains a block-reward burn output which is later spent will now hit the "referenced input ... is missing from the storage; rejecting the batch" error in fetch_utxo/update_tables_from_transaction_inputs, wedging the scan on a consensus-valid chain. If the skip is intentional, the transition plan for existing indexes (full re-index?) should be documented, and the comment's claim that the value "was never credited to any address balance" should also cover the previously-UTXO-indexed rows that reads like get_address_all_utxos used to serve.
Suggestion:
| OutputValue::TokenV0(_) => { | |
| continue; | |
| } | |
| OutputValue::TokenV0(_) => { | |
| continue; | |
| } | |
| // NOTE: unlike the previous shared arm, this skips set_utxo | |
| // for burn outputs entirely; spending such an output later | |
| // now rejects the batch as a missing input. |
Summary
Remediates the findings of an internal end-to-end security audit of the node stack (consensus and chainstate, p2p networking, transaction handling, wallet, indexer, storage, web server/RPC, deployment), plus the residual items surfaced by two hint-free re-audits of the remediated tree.
High-severity fixes
assert_eq!on the connect path (workspace builds withpanic = "abort", so the old behavior was a network-wide node kill from a single produced block). Rejection happens incheck_proof_of_stakebefore any storage access; the connect-path assert becomes a typed error as defense in depth.GET /api/v2/chain/:heightfor heights above the postgresi64range: heights are bounded at the handler, the storage conversion returns a typed error instead of panicking, and aCatchPanicLayeris installed as defense in depth.0.ml.transactionsandml.block_aux_dataare deleted on disconnect (both storage backends, in one transaction), every transaction read verifies main-chain membership, and the storage version bump forces a rescan so stale rows cannot survive.Other fixes (selection)
NULLowner), trusted fees are bounded and no longer wedge the scanner, genesis Burn is counted, exotic genesis spends produce typed batch errors instead of crashes, the daemon takes a single-writer advisory lock, andml.locked_utxoexpiry lookup is indexed.circulating_supplyreconciles with the sum of served balances; a spent data-deposit counter correction and afungible_token.authoritysame-height rewrite fix close the remaining drift paths.Hostvalidation (DNS rebinding), node error text no longer echoed to clients, capped unpaginated listings with atruncatedflag, and exact pagination-cursor key-count enforcement.SharedSecret/SymmetricKeydebug output redacted, KDF parameters bounded at decode, derivation-path and KDF-length truncations made self-defending, hardware-wallet signatures verified locally, seed-phrase purgeVACUUMs the database, CLI history files get0600, node-supplied sync data is validated instead of asserted.--lockedand default to a versioned tag, unknown[chainstate]config keys are rejected, packaged env files installed0600, andsnowupdated to 0.9.7 (RUSTSEC-2026-0626).Storage version
Bumped
CURRENT_STORAGE_VERSIONto 31 (this branch supersedes the version 29 bump from #2181, which is included here): scanners reinitialize and rescan on the next start, rebuilding address balances, holders, statistics (including the new open-HTLC and open-order buckets) and the token authority column.Tests
Based on #2181 (included via master); the block-reward debit and the new statistics buckets are verified together by the reconciliation tests.