Skip to content

fix: remediate internal security audit findings across the node stack - #2183

Open
nullPointerEnjoyer wants to merge 198 commits into
masterfrom
fix/internal-audit-2026-11
Open

nullPointerEnjoyer wants to merge 198 commits into
masterfrom
fix/internal-audit-2026-11

Conversation

@nullPointerEnjoyer

Copy link
Copy Markdown
Collaborator

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

  • PoS blocks with mismatched kernel witness counts are rejected instead of reaching an assert_eq! on the connect path (workspace builds with panic = "abort", so the old behavior was a network-wide node kill from a single produced block). Rejection happens in check_proof_of_stake before any storage access; the connect-path assert becomes a typed error as defense in depth.
  • Unauthenticated process abort on GET /api/v2/chain/:height for heights above the postgres i64 range: heights are bounded at the handler, the storage conversion returns a typed error instead of panicking, and a CatchPanicLayer is installed as defense in depth.
  • Pending-transaction rendering no longer aborts when a mempool transaction mints a token it does not also transfer: the token-decimals map is built from inputs as well, and the decimals lookup degrades to 0.
  • Timestamps-for-staking scan is safe for decommissioned pools (sparse balance history is iterated instead of index-panicked) and its request parameters are bounded (range length, per-height seconds, tip distance, and total search cost).
  • P2P bandwidth amplification is bounded end to end: per-peer serving token buckets for headers, blocks and transaction responses, a node-wide egress byte budget with hoarder identification, ban scores for non-reading peers and duplicate/unknown requests, reconnect-persistent offense memory, and inbound-eviction netgroup caps.
  • Reorged-out transactions are no longer served as confirmed: ml.transactions and ml.block_aux_data are 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)

  • Mempool: orphan-pool reservations are keyed by remote address (multi-connection monopolization), parked orphans are promoted when their parents are mined, the dead RBF rule-2 check is replaced by a typed rejection, and the rolling-fee decay no longer panics on wall-clock steps.
  • Indexer: point-in-time reads extended to orders and fungible-token data, NFT ownership is written at the output site (same-block transfers previously served a NULL owner), 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, and ml.locked_utxo expiry lookup is indexed.
  • Statistics: open HTLC and open order value each get their own served bucket so circulating_supply reconciles with the sum of served balances; a spent data-deposit counter correction and a fungible_token.authority same-height rewrite fix close the remaining drift paths.
  • Web/RPC: RPC request rate limiting with costlier auth hashing, per-IP request budget, per-client subscriber caps with bounded queues, browser-origin and Host validation (DNS rebinding), node error text no longer echoed to clients, capped unpaginated listings with a truncated flag, and exact pagination-cursor key-count enforcement.
  • Wallet/crypto: SharedSecret/SymmetricKey debug output redacted, KDF parameters bounded at decode, derivation-path and KDF-length truncations made self-defending, hardware-wallet signatures verified locally, seed-phrase purge VACUUMs the database, CLI history files get 0600, node-supplied sync data is validated instead of asserted.
  • Ops/supply-chain: CI workflows pinned by SHA with least-privilege permissions, docker images build --locked and default to a versioned tag, unknown [chainstate] config keys are rejected, packaged env files installed 0600, and snow updated to 0.9.7 (RUSTSEC-2026-0626).

Storage version

Bumped CURRENT_STORAGE_VERSION to 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

  • Consensus: kernel-witness rejection, PoS target guard, retarget bounds, timestamp-scan safety, decommissioned-pool scan.
  • p2p: serving-budget pacing and refusal, duplicate/unknown request punishment, slow-reader penalization with backpressure exception, netgroup eviction caps, WillDisconnect truncation.
  • Scanner/storage (both backends, containerized postgres in CI): reorged-out transactions disappear from reads and listings, live-vs-backfill equivalence per arm, point-in-time order/token reads, same-height authority rewrite, HTLC and order statistics reconciliation under fills/conclusions/reorgs, row caps, backend parity for history merge and transaction rollback.
  • Web: offset and cursor bounds, rate limiter, origin/Host policy, graceful degradation paths.
  • Wallet/crypto: debug-redaction regression tests, KDF bound rejection, hardware-signature verification, purge vacuum.

Based on #2181 (included via master); the block-reward debit and the new statistics buckets are verified together by the reconciliation tests.

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
@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

OpenCodeReview · Complete review: 218 of 218 selected files covered

78 findings.

  • Successfully posted inline: 15 comment(s)
  • 📝 In summary (no line info): 1 comment(s)
  • 📋 Routed to summary by policy: 50 comment(s)
  • ⏭️ Skipped (overlap with history): 10 comment(s)
  • ❌ Failed to post inline: 2 comment(s)

maintainability · low

📄 .github/workflows/code_checks.yml

⚠️ GitHub could not post this as an inline comment: No line information provided

This job (and the other jobs in this file) lacks timeout-minutes; only code-review.yml, wasm.yml and create-release got timeouts in this change. A hung build can consume runner time indefinitely. Consider adding a job-level timeout.


other · low

📄 packaging/deb/build.sh (L95-L98)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category other)

Note: these files are dpkg conffiles, so dpkg preserves the permissions of any already-installed copy on upgrade — the 0600 mode only takes effect on fresh installs. Existing deployments will keep the previous world-readable mode unless an admin fixes it manually. Consider documenting this in the release notes or adding a postinst permission fixup if tightening existing installs matters.


security · low

📄 .github/workflows/release.yml (L8-L11)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category security)

The workflow-level permissions: contents: write applies to all jobs, including the reusable-workflow build jobs (build-macos/linux/windows/docker) which only need read access. Only docker-release-status narrows to {}. Consider adding job-level minimal permissions (e.g. permissions: contents: read) to the build jobs so only create-release retains contents: write for the release action.

💡 Suggested Change

Before:

permissions:
  contents: write

jobs:

After:

permissions:
  contents: write

jobs:
  build-macos:
    permissions:
      contents: read
    uses: ./.github/workflows/release_macos.yml

maintainability · low

📄 .github/workflows/build.yml (L23-L23)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

Unlike the other release workflows (release_linux 180m, release_windows 120m, release_docker 60-240m) and code-review/wasm/create-release, the jobs in this workflow have no timeout-minutes, so a hung build/test (e.g. device-emulator tests waiting on hardware) can consume runner time indefinitely. Add a job-level timeout, e.g. timeout-minutes: 120.


maintainability · low

📄 .github/workflows/build.yml (L32-L37)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

release_macos.yml sets persist-credentials: false on checkout for token hygiene, but the checkout steps in build.yml, code_checks.yml, loom.yml, release_linux.yml and release_windows.yml do not. Since all these jobs are read-only after this change, applying persist-credentials: false consistently would reduce residual GITHUB_TOKEN exposure in the runner workspace.


maintainability · low

📄 do_checks.sh (L15-L15)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

This guard only inspects RUSTFLAGS / CARGO_ENCODED_RUSTFLAGS environment variables. Target-specific codegen flags can also be supplied via .cargo/config.toml (build.rustflags / target.<triple>.rustflags) or build.rustflags in config, which cargo applies without either variable being set — such a configuration would silently bypass this RUSTSEC-2026-0620 guard. The repo's current .cargo/config.toml is safe (no target-cpu/avx512 flags), but consider either also scanning the config files or documenting this limitation so future config additions don't quietly defeat the check.

💡 Suggested Change

Before:

if printf '%s %s' "${RUSTFLAGS:-}" "${CARGO_ENCODED_RUSTFLAGS:-}" | grep -Eq 'target-cpu=native|target-feature=[^ ]*avx512'; then

After:

# Also guard against flags set via .cargo/config.toml, which bypass RUSTFLAGS:
# if grep -Eq 'target-cpu=native|target-feature=.*avx512' .cargo/config.toml; then ... fi
if printf '%s %s' "${RUSTFLAGS:-}" "${CARGO_ENCODED_RUSTFLAGS:-}" | grep -Eq 'target-cpu=native|target-feature=[^ ]*avx512'; then

bug · low

📄 .github/workflows/release_macos.yml (L11-L14)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

The build job in this reusable macOS release workflow has no timeout-minutes, unlike its Linux (180m) and Windows (120m) counterparts and the workflows that received timeouts in this change (code-review, wasm, create-release). A hung codesign/build step would consume runner time up to the 360-minute GitHub default. Add an explicit job-level timeout for consistency and cost containment.

💡 Suggested Change

Before:

  build:
    runs-on: macos-latest
    permissions:
      contents: read

After:

  build:
    runs-on: macos-latest
    permissions:
      contents: read
    timeout-minutes: 120

performance · low

📄 api-server/api-server-common/src/storage/impls/in_memory/mod.rs (L606-L613)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category performance)

Every call to get_pool_delegations re-derives the full delegation set via get_pool_delegations_at_or_below_height and then allocates a bech32 Address string per delegation just to rank and truncate. This is O(n log n) with n string allocations per read, and the ranking is stable, so it cannot be cached trivially either. Consider ranking by the raw DelegationId encoding (which the bech32 encoding preserves one-to-one) or caching the address strings, so truncation does not re-encode every delegation on each call.


maintainability · low

📄 api-server/scanner-lib/src/blockchain_state/mod.rs (L2030-L2034)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

The zero-decimals fallback for an unissued token reference is silent: it is snapshotted into indexed rows and never refreshed (as the comment notes), yet nothing in the logs marks that this happened. A single warn-level log (deduplicated per token id) would make downstream 'wrong digit grouping' reports diagnosable without a re-index investigation.

💡 Suggested Change

Before:

    let decimals = if let Some(decimals) = new_tokens.get(&token_id) {
        *decimals
    } else {
        db_tx.get_token_num_decimals(token_id).await?.unwrap_or(0)
    };

After:

    let decimals = if let Some(decimals) = new_tokens.get(&token_id) {
        *decimals
    } else {
        let decimals = db_tx.get_token_num_decimals(token_id).await?.unwrap_or(0);
        if decimals == 0 {
            logging::log::warn!(
                "Token {token_id} has no issuance record; indexing with 0 decimals (display-only)"
            );
        }
        decimals
    };

style · low

📄 api-server/scanner-daemon/src/main.rs (L99-L102)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category style)

The lock-acquisition failure is an initialization-level error (lock refused or connection failed), but it is remapped into the PostgresConnectionError variant, which misreports a 'another daemon holds the single-writer lock' refusal as a connection problem. Consider a dedicated variant or an InitializationError passthrough so operators see the actual cause at the top level.

💡 Suggested Change

Before:

    let _single_writer_lock = storage
        .acquire_single_writer_lock()
        .await
        .map_err(ApiServerScannerError::PostgresConnectionError)?;

After:

    let _single_writer_lock = storage
        .acquire_single_writer_lock()
        .await
        .map_err(|err| ApiServerScannerError::InitializationError(err.to_string()))?;

maintainability · low

📄 api-server/web-server/src/api/mod.rs (L187-L195)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

Note: parse_authority is shared between the Origin and Host checks; if it ever grows Origin-specific behavior (e.g. scheme handling), the two consumers diverge silently. Keeping a small test pinning each consumer's expectations (the Host path is exercised above; consider an explicit test that parse_authority ignores the scheme) would make that contract durable.


test · low

📄 api-server/web-server/src/api/rate_limit.rs (L279-L280)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category test)

The test-only refill_restores_the_budget_up_to_the_capacity case sleeps 20 ms and depends on wall-clock progress; on a heavily loaded CI runner the sleep can be preempted past the assertions' intent, but the reverse (too little elapsed time) makes the assertion flaky in the other direction: after 20 ms at 1000/s the refill is 20 tokens, capped at capacity 2 — that direction is safe, but if the thread loses its slot before the first two acquisitions the pre-sleep asserts can fail. Consider injecting a deterministic clock or loosening the pre-sleep acquire assertions to reduce CI flakiness.


maintainability · low

📄 api-server/web-server/src/streaming.rs (L111-L113)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

The per-IP reservation happens before acquiring the global semaphore permit, so when the global cap is exhausted the per-IP slot is reserved and immediately released. Behavior is correct, but acquiring the scarcer global permit first would avoid transient map churn and point-increment/decrement cycles on every rejected request under load. Minor: consider swapping the order.

💡 Suggested Change

Before:

    pub fn try_subscribe(&self, client_ip: IpAddr) -> Option<StreamEventsSubscription> {
        let _ip_slot = self.try_acquire_ip_slot(client_ip)?;
        let permit = Arc::clone(&self.subscriber_slots).try_acquire_owned().ok()?;

After:

    pub fn try_subscribe(&self, client_ip: IpAddr) -> Option<StreamEventsSubscription> {
        let permit = Arc::clone(&self.subscriber_slots).try_acquire_owned().ok()?;
        let _ip_slot = self.try_acquire_ip_slot(client_ip)?;

maintainability · low

📄 api-server/web-server/src/api/v2.rs (L1844-L1850)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

The pool block stats time-range clamp silently truncates the requested range: a caller asking for 200k blocks gets stats for only the first 100k, with no indication the response is partial. Every other newly capped listing in this change reports truncation to the client (the truncated flag via cap_listing_rows/capped_listing_response, or a client error via OffsetTooLarge). Consider at least documenting the clamp in the response (e.g. echoing the effective height range) or rejecting over-range spans as a client error, so a client can distinguish a short pool history from a silently clipped one.

💡 Suggested Change

Before:

fn clamp_pool_block_stats_range(
    (from_height, to_height): (BlockHeight, BlockHeight),
) -> (BlockHeight, BlockHeight) {
    let clamped_to =
        u64::from(to_height).min(u64::from(from_height).saturating_add(POOL_BLOCK_STATS_MAX_RANGE));
    (from_height, BlockHeight::new(clamped_to))
}

After:

// Either reject the over-range span as a client error, or surface the effective
// range in the response body alongside the stats rows.

other · low

📄 api-server/web-server/src/streaming.rs (L62-L62)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category other)

The per-IP cap of 16 is enforced against the raw peer address (ConnectInfo). Behind a NAT gateway or a reverse proxy (note the code already sets the x-accel-buffering header, suggesting nginx-style proxies are in play), all clients share one IP, so 16 concurrent streams per IP may legitimately lock out unrelated users. Consider making this limit configurable (like StreamingConfig::max_subscribers) or honoring X-Forwarded-For when behind a trusted proxy.

💡 Suggested Change

Before:

const MAX_STREAM_SUBSCRIBERS_PER_IP: usize = 16;

After:

/// Configurable per-IP subscriber cap (default 16), see `StreamingConfig`.
const MAX_STREAM_SUBSCRIBERS_PER_IP: usize = 16;

maintainability · low

📄 chainstate/src/config.rs (L155-L158)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

This per-chain-type default for pos_seal_activation_gate duplicates the logic in ChainstateConfig::pos_seal_activation_gate_enabled (lines 111-114). If one copy is updated without the other, the warning will silently stop matching the actual effective default, defeating this guardrail. Consider extracting a shared helper (e.g. ChainstateConfig::pos_seal_activation_gate_default(chain_type)) and calling it from both places, or comparing the effective value against pos_seal_activation_gate_enabled directly.

💡 Suggested Change

Before:

    let gate_default = match chain_type {
        ChainType::Testnet => true,
        ChainType::Mainnet | ChainType::Signet | ChainType::Regtest => false,
    };

After:

    let gate_default = chainstate_config.pos_seal_activation_gate_default(chain_type);

maintainability · low

📄 chainstate/src/detail/orphan_blocks/pool.rs (L100-L103)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

When max_orphans is 0, add_block silently discards the block and returns Ok(()), so callers cannot distinguish "accepted as orphan" from "dropped". If downstream logic (e.g., orphans_proxy announcement handling) assumes an Ok result means the block was retained, it may wait for an orphan resolution that never comes. Consider returning a typed outcome or logging at warn level.

💡 Suggested Change

Before:

        if self.max_orphans == 0 {
            logging::log::debug!("Discarding orphan block {block_id}: orphan pool capacity is 0");
            return Ok(());
        }

After:

        if self.max_orphans == 0 {
            logging::log::debug!("Discarding orphan block {block_id}: orphan pool capacity is 0");
            return Ok(());
        }

maintainability · low

📄 chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs (L151-L152)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

The typed CacheOperationError is flattened into a String here (and similarly in cached_utxo_block_undo.rs), so downstream code can no longer match on the specific invariant violation (DataChangedOnMultipleLevels / ReadAfterModified / ReadAfterErased). Since UtxosBlockUndoError/BlockUndoError already exist as typed enums, consider adding a #[from] CacheOperationError variant (or storing the enum) instead of CacheInvariantViolation(String) to preserve matchability and avoid allocation in the error path.

💡 Suggested Change

Before:

            let result = combine(self.tx_undos.get(&id).cloned(), Some(op))
                .map_err(|err| BlockUndoError::CacheInvariantViolation(err.to_string()))?;

After:

            let result = combine(self.tx_undos.get(&id).cloned(), Some(op))
                .map_err(BlockUndoError::CacheInvariantViolation)?;

maintainability · low

📄 chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs (L150-L157)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

On a CacheInvariantViolation the merge aborts mid-iteration, leaving self.tx_undos partially merged with entries from other while other's remaining entries are dropped. If the caller retries the merge (or inspects other afterwards), the caches are in a torn state. Since the outer verifier is expected to be discarded on this error this is not blocking, but a debug_assert on entry, or documenting that self is unspecified after an error, would make the contract explicit. Same pattern applies in cached_utxo_block_undo.rs for all three maps.


maintainability · low

📄 common/src/chain/config/builder.rs (L610-L613)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

emission_schedule_tabular is a public builder method that now panics via expect on an invalid table. The only programmatic caller found outside config parsing is scanner-lib (hardcoded table), so risk is limited, but a public API that panics on caller-supplied data is a contract change for all future callers. Consider documenting the panic explicitly in the doc comment (or returning Result from a fallible variant) so the invariant is discoverable.

💡 Suggested Change

Before:

    pub fn emission_schedule_tabular(mut self, es: EmissionScheduleTabular) -> Self {
        // Validate here so every construction path gets the same overflow and
        // monotonicity guarantees as the chain-file parsing path.
        es.validate().expect("invalid emission schedule table");

After:

    /// # Panics
    /// Panics if the table fails `EmissionScheduleTabular::validate` (overflowing or
    /// non-monotonic subsidy periods). Only call with tables known to be valid.
    pub fn emission_schedule_tabular(mut self, es: EmissionScheduleTabular) -> Self {
        // Validate here so every construction path gets the same overflow and
        // monotonicity guarantees as the chain-file parsing path.
        es.validate().expect("invalid emission schedule table");

style · low

📄 common/src/chain/config/emission_schedule.rs (L143-L145)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category style)

periods is a BTreeMap<BlockHeight, CoinUnit>, so iteration is always in ascending height order and checked_sub here can never fail — the NonMonotonicPeriods error path is unreachable dead code for this representation. Also note validate() runs twice on the regtest path (once in regtest_chain_config_builder, again via emission_schedule_tabular). Harmless duplication, but consider documenting that NonMonotonicPeriods exists only for defensive/future non-map representations.


maintainability · low

📄 common/src/chain/config/builder.rs (L430-L434)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

build() now panics via expect when the upgrade schedule fails validate_pos_era_transitions. This is the same public-API contract concern already noted for emission_schedule_tabular: a builder method turning a typed, recoverable error (NetUpgradesInitializeError) into a panic on caller-supplied data. Since the validation error is fully recoverable at this boundary, consider returning Result<ChainConfig, ...> (or deferring validation to the parse path that already surfaces typed errors) so programmatic callers can handle invalid schedules instead of crashing at startup.

💡 Suggested Change

Before:

        consensus_upgrades
            .validate_pos_era_transitions()
            .expect(
                "Invalid chain config. A PoS net-upgrade without an initial difficulty must directly follow a PoS net-upgrade",
            );

After:

        // Prefer propagating this as a typed error if the build() signature can change;
        // today this converts a recoverable NetUpgradesInitializeError into a panic.
        consensus_upgrades
            .validate_pos_era_transitions()
            .expect(
                "Invalid chain config. A PoS net-upgrade without an initial difficulty must directly follow a PoS net-upgrade",
            );

maintainability · low

📄 crypto/src/kdf/argon2.rs (L92-L96)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

This conversion overloads InvalidHashSize for two distinct conditions: a usize hash length that doesn't fit u32 (a representability limit) and a length above MAX_HASH_LEN (a policy limit, reported as KdfParamAboveMaximum only if it fits u32 first). Callers that surface this error to users (e.g. wallet unlock paths) will report a legitimate-but-large request as an 'Invalid hash size'. Consider a dedicated variant (or reuse KdfParamAboveMaximum) so the message distinguishes the two cases.

💡 Suggested Change

Before:

        ensure_param_within_bounds(
            "hash length",
            desired_hash_len.get().try_into().map_err(|_| KdfError::InvalidHashSize)?,
            MAX_HASH_LEN,
        )?;

After:

        let desired_hash_len_u32 = u32::try_from(desired_hash_len.get())
            .map_err(|_| KdfError::KdfParamAboveMaximum {
                parameter: "hash length",
                value: desired_hash_len.get() as u64,
                max_value: MAX_HASH_LEN as u64,
            })?;
        ensure_param_within_bounds("hash length", desired_hash_len_u32, MAX_HASH_LEN)?;

performance · low

📄 dns-server/src/crawler_p2p/crawler/mod.rs (L465-L471)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category performance)

When the ban table is at capacity, each new ban runs a linear min_by_key scan per evicted entry (O(cap) overall, cap = 65,536) and issues one RemoveBannedStatus callback (a synchronous DB transaction in crawler_manager) per eviction. Since a hostile peer can reach the ban threshold repeatedly, this is an amplification path against the DB on attack-heavy networks. Consider periodically purging expired bans in heartbeat (already done) plus keeping a sorted structure by till, or evicting multiple victims per scan.


security · low

📄 crypto/src/kdf/argon2.rs (L48-L51)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category security)

The new parameter bounds reject absurd m_cost/t_cost/hash_len from a crafted KdfChallenge, but the salt field (a decoded length-prefixed Vec) is not bounded anywhere in this path: decoding a tampered wallet-file header can still force an arbitrary-size allocation before argon2id_hash's checks run, partially defeating the stated goal of preventing huge allocations from crafted files. Consider bounding the salt length (e.g. during Decode for KdfChallenge or with a const max checked in the same validation block) to the sizes legitimately produced (32 bytes for wallet/RPC auth).

💡 Suggested Change

Before:

const MAX_M_COST_MEMORY_SIZE_KIB: u32 = 1024 * 1024; // 1 GiB of memory
const MAX_T_COST_ITERATIONS: u32 = 16;
const MAX_P_COST_PARALLELISM: u32 = 64;
const MAX_HASH_LEN: u32 = 1024 * 1024; // 1 MiB hash

After:

const MAX_M_COST_MEMORY_SIZE_KIB: u32 = 1024 * 1024; // 1 GiB of memory
const MAX_T_COST_ITERATIONS: u32 = 16;
const MAX_P_COST_PARALLELISM: u32 = 64;
const MAX_HASH_LEN: u32 = 1024 * 1024; // 1 MiB hash
const MAX_SALT_SIZE: u32 = 1024; // generous bound for legitimately-created salts

documentation · low

📄 mempool/src/config.rs (L179-L183)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category documentation)

The setting's name still says "per peer", but with the new semantics an inbound reservation is keyed by remote IP address (multiple connections from one address share it). Operators sizing this limit from the name may mis-estimate its effect, and the name no longer matches the field doc. Consider renaming (e.g. RemoteOrphanPoolCapacityPerAddress) or at least reflecting the address-based keying in the user-facing setting name/description.

💡 Suggested Change

Before:

make_config_setting!(
    RemoteOrphanPoolCapacityPerPeer,
    usize,
    DEFAULT_REMOTE_ORPHAN_POOL_CAPACITY_PER_PEER
);

After:

make_config_setting!(
    RemoteOrphanPoolCapacityPerAddress,
    usize,
    DEFAULT_REMOTE_ORPHAN_POOL_CAPACITY_PER_PEER
);

bug · low

📄 dns-server/src/crawler_p2p/crawler_manager/mod.rs (L321-L328)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

When an unexpected inbound connection is accepted, the handler only logs a warning; the peer is never disconnected via self.conn.disconnect(peer_id, ...). Since the crawler never calls accept for this peer, the connection stays open (and unread) in the connectivity backend, and a host that repeatedly dials the crawler's port can accumulate dangling sockets until the backend's own limits/timeouts (if any) kick in. Consider actively disconnecting the inbound peer here so the rejection is enforced locally rather than relying on backend cleanup.

💡 Suggested Change

Before:

            ConnectivityEvent::InboundAccepted {
                peer_address: _,
                bind_address: _,
                peer_info: _,
                node_address_as_seen_by_peer: _,
            } => {
                log::warn!("Ignoring unexpected inbound connection in DNS crawler");
            }

After:

            ConnectivityEvent::InboundAccepted {
                peer_address,
                bind_address: _,
                peer_info,
                node_address_as_seen_by_peer: _,
            } => {
                log::warn!("Rejecting unexpected inbound connection from {peer_address} in DNS crawler");
                let _ = self
                    .conn
                    .disconnect(peer_info.peer_id, None)
                    .log_lvl_pfx(log::Level::Debug, "disconnecting inbound peer failed");
            }

maintainability · low

📄 dns-server/src/crawler_p2p/crawler_manager/mod.rs (L307-L314)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

If self.conn.accept fails, the function returns without notifying the crawler: the outbound peer is never registered in outbound_peers and no disconnect is requested, so the connection is left dangling in the connectivity backend while any later events for this peer_id (messages, ConnectionClosed, misbehavior) will hit the "unknown peer" ignore paths. Emitting a disconnect (or forwarding a ConnectionError event for peer_address) would keep the crawler's state machine in sync with the backend.


maintainability · low

📄 networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs (L52-L54)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

The per-IP exemption for loopback/unspecified means that if this listener is ever deployed behind a local reverse proxy or NAT that rewrites source addresses to 127.0.0.1, the per-IP limit silently becomes a no-op for all traffic (all peers share one exempt key). Also note the IPv6 /64 prefix key means many clients behind a single ISP/NAT64 /64 share only MAX_CONCURRENT_HANDSHAKES_PER_IP slots. Consider documenting this trust assumption near the constant, or exempting a configurable trusted-proxy CIDR instead of blanket loopback.


performance · low

📄 networking/src/transport/message_codec.rs (L99-L101)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category performance)

The idle-buffer shrink only triggers when the buffer fully drains between frames. A steady stream of frames larger than MAX_IDLE_BUFFER_CAPACITY (with occasional coalescing in the buffer) retains peak capacity indefinitely. This is acceptable as a bound, but if long-lived connections are expected to be mostly idle after bursts, consider also shrinking (e.g. via src.reserve_mut/truncate or periodic compaction) when the buffer stays empty across consecutive decode calls. Non-blocking; the current approach is simple and correct.


other · low

📄 networking/src/transport/message_codec.rs (L91-L96)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category other)

On 32-bit targets usize equals u32, so checked_add(size_of::<MsgLenHeader>(), length) can actually fail here and this error path is reachable; on 64-bit it is dead code. The diagnostic reports max_size: usize::MAX when no limit is configured, which is slightly misleading. Consider using the configured limit (or MsgLenHeader::MAX as usize) so the error message reflects the real bound.

💡 Suggested Change

Before:

        let frame_len = size_of::<MsgLenHeader>().checked_add(length).ok_or_else(|| {
            MessageCodecError::MessageTooLarge {
                actual_size: length,
                max_size: self.max_encoded_message_size.unwrap_or(usize::MAX),
            }
        })?;

After:

        let frame_len = size_of::<MsgLenHeader>().checked_add(length).ok_or_else(|| {
            MessageCodecError::MessageTooLarge {
                actual_size: length,
                max_size: MsgLenHeader::MAX as usize,
            }
        })?;

test · low

📄 mempool/src/pool/tx_pool/rolling_fee_rate.rs (L150-L150)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category test)

The test name says the rate "is unchanged", but the assertion checks that it halves after one half-life. Rename to reflect what is asserted, e.g. decay_fee_within_half_life_window_behaves_normally.

💡 Suggested Change

Before:

    fn decay_fee_within_half_life_window_is_unchanged() {

After:

    fn decay_fee_within_half_life_window_is_not_altered_by_the_clamps() {

documentation · low

📄 mempool/src/rpc.rs (L101-L107)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category documentation)

This changes the mempool.transactions RPC signature (two new positional parameters), which is a breaking change for existing clients calling the method with the old empty argument list; they will fail parameter deserialization rather than get the old full-pool behavior. This is fine if intentional, but it should be recorded in release notes / an RPC changelog since the method contract change is only discoverable from this doc comment. Also consider documenting the max_count = 0 case: per the documented "shorter page than requested means end" heuristic, a zero-count request returns an empty page indistinguishable from end-of-pool.


maintainability · low

📄 mempool/src/pool/tx_pool/mod.rs (L927-L929)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

An overflow here is silently clamped to BlockHeight::max, which would make the future-timelock check effectively always pass at an absurd height instead of surfacing the anomaly. The height is practically bounded (it comes from the chainstate tip plus a small tolerance constant), but a log::warn!/debug_panic_or_log! on this path would make an unexpected invariant violation visible rather than silently changing timelock semantics.


style · low

📄 node-lib/src/runner.rs (L31-L34)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category style)

This constant is declared in the middle of the use block, breaking the conventional imports-then-items ordering and making the module header harder to scan. Move it above the use statements (after the module doc comment) or below all of them.

💡 Suggested Change

Before:

use common::chain::config::{ChainType, assert_no_ignore_consensus_in_chain_config};

const RECKLESS_MODE_WARNING_BODY: &str = concat!(
    "a system crash while the initial block download is in progress can ",

After:

use common::chain::config::{ChainType, assert_no_ignore_consensus_in_chain_config};

// Placed after all imports.
const RECKLESS_MODE_WARNING_BODY: &str = concat!(
    "a system crash while the initial block download is in progress can ",

bug · low

📄 p2p/src/peer_manager/mod.rs (L1977-L1977)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

This expect relies on the caller (handle_incoming_message) having verified the peer exists in the same synchronous block. That holds today because no await or intervening peer removal happens between the check and this handler, but the invariant is implicit: if handle_incoming_message's guard is ever weakened (or another handler that removes the peer runs first, e.g. a WillDisconnect-triggered disconnection completing synchronously), this becomes a remotely reachable panic. Prefer the debug_panic_or_log!-style defensive handling already used in the dispatcher, or return early on a missing peer instead of panicking.

💡 Suggested Change

Before:

        let peer = self.peers.get_mut(&peer_id).expect("peer must be known");

After:

        let Some(peer) = self.peers.get_mut(&peer_id) else {
            debug_panic_or_log!("Peer context for {peer_id} not found when handling a ping request");
            return;
        };

style · low

📄 p2p/src/message.rs (L205-L209)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category style)

The truncation note uses an incorrect plural: with one character dropped it logs "(1 characters truncated)". This string reaches logs and is asserted verbatim in the test below. Consider pluralizing conditionally, e.g. if dropped == 1 { "character" } else { "characters" }, and update the test expectation.

💡 Suggested Change

Before:

        format!(
            "{} ({} characters truncated)",
            self.reason.chars().take(Self::REASON_MAX_CHARS).collect::<String>(),
            char_count - Self::REASON_MAX_CHARS,
        )

After:

        let dropped = char_count - Self::REASON_MAX_CHARS;
        format!(
            "{} ({} character{} truncated)",
            self.reason.chars().take(Self::REASON_MAX_CHARS).collect::<String>(),
            dropped,
            if dropped == 1 { "" } else { "s" },
        )

performance · low

📄 p2p/src/peer_manager/peerdb/mod.rs (L103-L114)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category performance)

Every first-time offense insert performs two full O(n) scans of the map (the prefix_count count and the min_by_key for the oldest entry) over up to MAX_RECENT_OFFENSES = 65,536 entries, and the caller also computes ipv6_prefix_64 for every existing key inside the prefix_match closure. Under an address-flood (many distinct addresses per /64, which is exactly the scenario this cap targets), inserting N addresses costs O(N^2) work inside the peer manager's synchronous event loop. Consider maintaining a per-prefix counter (incremented/decremented on insert/evict) so the prefix check is O(1), or bucketing offenses into per-prefix BTreeMaps.


bug · low

📄 storage/core/src/adaptor/locking.rs (L175-L181)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

In the Ordering::Equal branch the db entry is consumed with let _ = self.db_iter.next();, discarding its result. If the backend iterator yields Err(...) for that key (which is possible, since db_iter carries Result items), the error is silently dropped and the entry disappears from the iteration as if deleted. Consider propagating the error instead, e.g. match on the popped item and return Some(Err(e)) before applying the delta.

💡 Suggested Change

Before:

                        Ordering::Equal => {
                            let _ = self.db_iter.next();
                            let (k, v_opt) = self.delta_iter.next()?;
                            if let Some(v) = v_opt {
                                return Some(Ok((k.clone(), v.clone())));
                            }
                        }

After:

                        Ordering::Equal => {
                            match self.db_iter.next() {
                                Some(Err(e)) => {
                                    self.errored = true;
                                    return Some(Err(e));
                                }
                                _ => {}
                            }
                            let (k, v_opt) = self.delta_iter.next()?;
                            if let Some(v) = v_opt {
                                return Some(Ok((k.clone(), v.clone())));
                            }
                        }

documentation · low

📄 serialization/src/encoded.rs (L42-L44)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category documentation)

The doc comment presents "the check runs in release builds too" as the differentiator from from_bytes_unchecked, but from_bytes_unchecked now also validates unconditionally (its own doc says so). The stated contrast is no longer accurate; the real difference is only return type (Result vs. panic). Reword to avoid misleading readers about which constructor is safe in release builds.

💡 Suggested Change

Before:

    /// Unlike [Self::from_bytes_unchecked], this constructor reports undecodable input
    /// (e.g. a corrupted database row) as an error instead of aborting the process later,
    /// and the check runs in release builds too.

After:

    /// Unlike [Self::from_bytes_unchecked], this constructor reports undecodable input
    /// (e.g. a corrupted database row) as an error instead of aborting the process.

maintainability · low

📄 storage/lmdb/src/lib.rs (L89-L92)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

process_with_err never returns Ok (its default branch maps success-classified errors to Fatal::InternalError), so the Ok(()) => DatabaseCorrupted fallback is unreachable dead code in both TryPrefixIter::next and try_greater_equal_iter. This is misleading: a reader will assume some LMDB error codes are "successful" here and get mapped to DatabaseCorrupted. Simplify to error::process_with_err::<()>(err).unwrap_err() or map directly, or if the intent was to treat NotFound/KeyExist as success, that behavior is silently lost.

💡 Suggested Change

Before:

            Err(err) => Some(Err(match error::process_with_err::<()>(err) {
                Err(storage_err) => storage_err,
                Ok(()) => storage_core::error::Fatal::DatabaseCorrupted.into(),
            })),

After:

            Err(err) => Some(Err(error::process_with_err(err))),

security · low

📄 rpc/src/rpc_auth/mod.rs (L126-L126)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category security)

Unauthorized and invalid-request logging now goes to debug, which operators running at default levels will never see. Auth failures are the primary signal of an online brute-force attempt; consider rate-limited warning logging (e.g. one WARN line per N consecutive rejections) rather than full silence at default levels.


security · low

📄 rpc/src/rpc_creds.rs (L59-L59)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category security)

The rename is not preceded by an fsync of the temp file (nor a directory fsync after the rename), so on crash/power loss the rename can be persisted while the content is not, leaving a zero-length cookie file. Since the cookie is regenerated on each run and read soon after creation the impact is limited, but if any supervisor-started consumer reads the file after the writing process dies it may see an empty credential. Also, create_new failing on a random-suffix collision aborts cookie creation with no retry; a small retry loop would be more robust.


other · low

📄 rpc/src/subscription.rs (L36-L36)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category other)

MAX_RPC_EVENT_SUBSCRIPTIONS is enforced by a process-global counter, but the bounded connectors are used by both the chainstate and mempool RPC subscription methods, which share one server in a node process. The 8-slot budget is therefore shared across all subscription kinds, so one client holding 8 chainstate subscriptions starves every other client's mempool subscriptions (per-client accounting is impossible, per-kind/per-server accounting could be considered). If this sharing is intended, a doc note on the constant would help.


bug · low

📄 wallet/src/wallet/mod.rs (L1122-L1126)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

When all accounts have been consumed by pop_last, wallet_info now silently returns H256::zero() as the wallet identifier. This value is exposed via RPC/CLI (wallet_id) and will collide across every empty wallet, and callers cannot distinguish "empty wallet" from a valid hash of an account id. Prefer returning an error or an Option so empty-wallet state is explicit.

💡 Suggested Change

Before:

        let acc_hash = self
            .accounts
            .values()
            .next()
            .map_or_else(H256::zero, |acc| hash_encoded(&acc.get_account_id()));

After:

        let acc_hash = self
            .accounts
            .values()
            .next()
            .map_or_else(H256::zero, |acc| hash_encoded(&acc.get_account_id()));
        // TODO: surface the empty-wallet case explicitly instead of a zero wallet id

documentation · low

📄 wallet/src/key_chain/mod.rs (L74-L76)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category documentation)

The doc comment for LOOKAHEAD_SIZE now contains two overlapping sentences — the first line of the old comment was left behind under the new one, producing garbled text: "Default size of the number of unused addresses that need to be checked after the / Default lookahead size for address derivation." Keep only the new sentence.

💡 Suggested Change

Before:

/// Default size of the number of unused addresses that need to be checked after the
/// Default lookahead size for address derivation.
pub const LOOKAHEAD_SIZE: u32 = 20;

After:

/// Default lookahead size for address derivation.
pub const LOOKAHEAD_SIZE: u32 = 20;

maintainability · low

📄 wallet/src/wallet/mod.rs (L1284-L1290)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

On the commit-failure path, the ? on reload_accounts_from_db discards the original commit error: if the recovery read itself fails, the caller sees only the reload error and loses the actual cause of the rollback. Consider logging the commit error or combining both errors before returning.


bug · low

📄 p2p/src/sync/peer/transaction_manager.rs (L725-L731)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

A peer is banned (score 20 via DuplicatedTransactionRequest) for requesting a transaction whose NotFound/Found response is still sitting in pending_tx_responses. The peer has no way to know the response is queued, and since responses here are paced by the tx serving budget (the queue can hold up to 128 responses, draining at tx_serving_refill_rate), the delay before our response reaches the peer can exceed the peer's own request timeout. In that case an honest peer that retries is disconnected and penalized for behavior caused by our own pacing. Consider returning NotFound-style behavior or simply refreshing the existing queued entry instead of a ban-scored error for this case.


maintainability · low

📄 wallet/src/wallet/mod.rs (L333-L335)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category maintainability)

checked_next_height is a general helper (used for token ID derivation and send flows, not just scanning), but the failure it returns reuses the scan-specific WalletError::ScanBlockHeightOverflow variant. Callers outside of block scanning (e.g. create_token/send_to_address) will surface a misleading "overflow while scanning blocks" message to users when the height is merely at u32::MAX. Consider a neutral variant such as BlockHeightOverflow.

💡 Suggested Change

Before:

pub(crate) fn checked_next_height(height: BlockHeight) -> WalletResult<BlockHeight> {
    height.checked_add(1).ok_or(WalletError::ScanBlockHeightOverflow)
}

After:

pub(crate) fn checked_next_height(height: BlockHeight) -> WalletResult<BlockHeight> {
    height.checked_add(1).ok_or(WalletError::BlockHeightOverflow)
}

style · low

📄 wallet/src/signer/trezor_signer/mod.rs (L380-L388)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category style)

sig.encode() is computed twice (once for the verification and once for make_witness). Encoding is deterministic, so this is only wasted work, but binding the encoded signature to a local would make it clear both witnesses use the exact same bytes.

💡 Suggested Change

Before:

                    let sig = AuthorizedPublicKeyHashSpend::new(pk, sig);
                    // The signature comes from an external device, so verify it locally
                    // before marking the input as fully signed.
                    StandardInputSignature::new(sighash_type, sig.encode()).verify_signature(
                        &self.chain_config,
                        destination,
                        &sighash,
                    )?;
                    let sig = make_witness(StandardInputSignature::new(sighash_type, sig.encode()));

After:

                    let sig = AuthorizedPublicKeyHashSpend::new(pk, sig);
                    let input_signature = StandardInputSignature::new(sighash_type, sig.encode());
                    // The signature comes from an external device, so verify it locally
                    // before marking the input as fully signed.
                    input_signature
                        .verify_signature(&self.chain_config, destination, &sighash)?;
                    let sig = make_witness(input_signature);

bug · low

📄 wallet/wallet-cli-commands/src/command_handler/mod.rs (L2966-L2971)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

The new fallback paths make compare_currencies non-transitive when the lookup misses: for a pair of missing tokens it orders by address, but if one of them is present the comparison switches to ticker order. Depending on which pairs the sort examines, the same two orders can compare both Less and Greater, so sorted_by may produce an order that depends on the input permutation. The comment above claims token_infos always contains every encountered token, so the fallback should ideally be consistent (e.g. always fall back to comparing the raw addresses for any miss, or treat a miss as a fixed bucket) rather than mixing ordering keys per pair.

💡 Suggested Change

Before:

                        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);
                        };

After:

                        if let (Some(token1_id), Some(token2_id)) =
                            (token_ids_map.get(token1_id_as_addr), token_ids_map.get(token2_id_as_addr))
                        {
                            if token1_id == token2_id {
                                return Ordering::Equal;
                            }
                            let token1_ticker = ticker_by_id(token1_id);
                            let token2_ticker = ticker_by_id(token2_id);
                            return token1_ticker
                                .cmp(&token2_ticker)
                                .then(token1_id_as_addr.cmp(token2_id_as_addr));
                        }
                        // Consistent fallback: any lookup miss orders purely by address.
                        token1_id_as_addr.cmp(token2_id_as_addr)

bug · high

📄 .github/workflows/release_macos.yml (L3-L8)

⚠️ GitHub could not post this as an inline comment: Lines 3-8 could not be resolved (outside PR diff hunks)

This reusable workflow declares no secrets: under workflow_call, and its body contains no secrets.* references (no codesigning/notarization steps). However, release.yml now explicitly passes six secrets to it (MACOS_CERTIFICATE, MACOS_CERTIFICATE_PASSWORD, MACOS_CERTIFICATE_NAME, APPLE_ID, APPLE_TEAM_ID, APPLE_ID_PASSWORD). Passing secrets that are not declared in the callee's workflow_call triggers a workflow validation error, so the release may fail at dispatch; and even if tolerated, the values are unused, so macOS artifacts are never signed despite the workflow name "Build, Sign and Release". Either declare the secrets in workflow_call and add signing steps, or drop the secret passing from the caller.

💡 Suggested Change

Before:

on:
  workflow_call:
    inputs:
      binary_list:
        required: true
        type: string

After:

on:
  workflow_call:
    inputs:
      binary_list:
        required: true
        type: string
    secrets:
      MACOS_CERTIFICATE:
        required: false
      MACOS_CERTIFICATE_PASSWORD:
        required: false
      MACOS_CERTIFICATE_NAME:
        required: false
      APPLE_ID:
        required: false
      APPLE_TEAM_ID:
        required: false
      APPLE_ID_PASSWORD:
        required: false

bug · high

📄 wallet/src/wallet/mod.rs (L1318-L1333)

⚠️ GitHub could not post this as an inline comment: Lines 1318-1333 could not be resolved (outside PR diff hunks)

The commit-failure recovery here only calls account.reload_keys(), which restores just the key chains. Closures passed to for_account_rw_unlocked/async_for_account_rw_unlocked (e.g. send/issue flows) also mutate the account's output cache (consumed UTXOs, added in-memory transactions) and account info before commit. If the DB commit fails, those in-memory mutations survive while the DB rolls back, leaving the output cache inconsistent with stored state — exactly the class of inconsistency for_account_rw now avoids by calling the full reload_from_database. Consider using reload_from_database here as well (the async path's sign_request writes through db_tx too).

💡 Suggested Change

Before:

                if let Err(err) = db_tx.commit() {
                    let ro_tx = self.db.transaction_ro()?;
                    account.reload_keys(&ro_tx)?;
                    return Err(err.into());
                }
                Ok(value)
            }
            Err(err) => {
                db_tx.abort();
                // In case of an error we should reload the keys, in the case that the operation has issued new ones;
                // we do this to prevent exhausting the keys from many failed operations, and to
                // keep the cache in sync with the DB, as the DB transaction will roll back.
                let db_tx = self.db.transaction_ro()?;
                account.reload_keys(&db_tx)?;
                Err(err)
            }

After:

                if let Err(err) = db_tx.commit() {
                    let ro_tx = self.db.transaction_ro()?;
                    account.reload_from_database(&ro_tx)?;
                    return Err(err.into());
                }
                Ok(value)
            }
            Err(err) => {
                db_tx.abort();
                let db_tx = self.db.transaction_ro()?;
                account.reload_from_database(&db_tx)?;
                Err(err)
            }
Review info

Reviewed commits: c4e1e1e97dcb645755303c34617a47b9e5a46ec8 → 3238f7b1ac88c9f90328be115bc1061e6d20437c

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · medium
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:

Suggested change
- 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

Comment on lines 85 to 88
create-release:
needs: [build-macos, build-linux, build-windows, build-docker-amd64]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
The create-release job has no timeout-minutes (unlike docker-release-status). Add one (e.g. 10) so a stalled artifact download or release publish fails fast rather than hanging.

Comment on lines 83 to 85
runs-on: ubuntu-latest
steps:
- name: Checkout the repository

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
Neither the wasm-build nor wasm-package job declares timeout-minutes. A hung wasm build or artifact step will occupy the runner for the full default window on every daily scheduled run. Add an explicit timeout per job.

Comment on lines +241 to +243
fn is_loopback_host(host: &str) -> bool {
matches!(host, "localhost" | "127.0.0.1" | "::1")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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")
}

Comment on lines +1070 to +1077
let _query_permit = if token_ids.is_empty() {
None
} else {
Some(
tokio::time::timeout(
MEMPOOL_QUERY_WAIT_TIMEOUT,
MEMPOOL_QUERY_PERMITS.acquire(),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
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>;

Comment thread rpc/src/rpc_rate_limit.rs
Comment on lines +232 to +239
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)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment thread rpc/src/subscription.rs
Comment on lines +45 to +46
static LIVE_EVENT_SUBSCRIPTIONS: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
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.

Comment on lines 57 to 65
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
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.

Comment on lines +537 to +540
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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test · medium
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:

Suggested change
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();

Comment thread wallet/storage/src/internal/password.rs Outdated
@@ -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)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
let challenge = kdf_result.into_challenge().map_err(|_| crate::Error::WalletInvalidPassword)?;
let challenge = kdf_result
.into_challenge()
.map_err(|_| crate::Error::WalletDbInconsistentState)?;

Comment on lines +746 to +749
TxOutput::Transfer(value, _)
| TxOutput::LockThenTransfer(value, _, _)
| TxOutput::Htlc(value, _)
| TxOutput::Burn(value) => value.coin_amount(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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)),

Comment on lines +3603 to +3625
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?;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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?;
}

Comment on lines +375 to +385
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))
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
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))

Comment on lines +446 to +448
fn is_main_chain_block(&self, block_id: &Id<Block>) -> bool {
self.main_chain_blocks_table.values().any(|id| id == block_id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
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)
}

Comment on lines +2402 to +2407
"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;",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
"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;

Comment on lines +186 to +193
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,
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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,
}
}

Comment on lines +111 to +112
pub fn try_subscribe(&self, client_ip: IpAddr) -> Option<StreamEventsSubscription> {
let _ip_slot = self.try_acquire_ip_slot(client_ip)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines +52 to +54
if canonical.is_loopback() || canonical.is_unspecified() {
return None;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · medium
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.

Comment on lines +725 to +731
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),
));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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(());
}

Comment thread wallet/src/wallet/mod.rs
Comment on lines +1291 to +1295
Err(err) => {
db_tx.abort();
Self::reload_accounts_from_db(&self.db, &mut self.accounts, unused)?;
Err(err)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
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:

Suggested change
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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
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:

Suggested change
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.

Comment on lines +201 to +204
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 }}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · high
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:

Suggested change
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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
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:

Suggested change
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}"));

Comment on lines +199 to +203
logging::log::info!("Scanner single-writer advisory lock acquired");
Ok(SingleWriterGuard {
_client: client,
_driver: driver,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
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:

Suggested change
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.

Comment on lines +757 to +762
TxOutput::ProduceBlockFromStake(_, _)
| TxOutput::CreateDelegationId(_, _)
| TxOutput::IssueFungibleToken(_)
| TxOutput::IssueNft(_, _, _)
| TxOutput::DataDeposit(_)
| TxOutput::CreateOrder(_) => Some(Amount::ZERO),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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),

Comment on lines +1991 to +1995
// 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
// 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.

Comment on lines +743 to +747
if !self.known_transactions.contains(&tx_id) {
return Err(P2pError::ProtocolError(
ProtocolError::UnknownTransactionRequested(tx_id),
));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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(());
}

Comment on lines +45 to +50
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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.

Comment on lines +60 to +63
assert!(
T::decode_all(&mut this.bytes()).is_ok(),
"from_bytes_unchecked called with an invalid encoding"
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
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:

Suggested change
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.

Comment thread wallet/src/signer/trezor_signer/mod.rs Outdated
/// 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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.

Comment on lines +282 to +283
restrict_history_file_permissions(&file_name)
.map_err(|e| WalletCliError::FileError(file_name, e.to_string()))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · medium
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:

Suggested change
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()))?;

Comment on lines +124 to +125
for arg_id in COMMAND_LINE_REJECTED_ARG_IDS {
if matches.value_source(arg_id) == Some(clap::parser::ValueSource::CommandLine) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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)
{

Comment on lines +1441 to +1445
for transaction_id in transaction_ids {
if let Err(position) = rows.binary_search(&transaction_id) {
rows.insert(position, transaction_id);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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);
}
}

Comment on lines +151 to +157
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;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
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.

Comment on lines +230 to +237
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(())
})?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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);
}
}

Comment on lines +55 to +57
let time_diff = current_time
.saturating_sub(self.last_rolling_fee_update)
.min(config::ROLLING_FEE_MAX_DECAY_WINDOW);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment thread wallet/src/wallet/mod.rs
Comment on lines +2944 to +2949
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);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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);
}

Comment on lines +2933 to +2937
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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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;
}

Comment on lines +2966 to +2971
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);
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines +156 to 164
// 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,
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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:

Suggested change
// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines 1122 to 1126
(last.spend_destination() == address)
.then_some((delegation_id.to_owned(), last.clone()))
})
.take(max_rows as usize)
.collect())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
(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)

Comment on lines +69 to +73
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);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
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.

Comment on lines +143 to +147
// 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines +245 to +250
} else {
match authority.rsplit_once(':') {
Some((host, port)) => (host, Some(port.parse::<u16>().ok()?)),
None => (authority, None),
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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.

Comment on lines +89 to +99
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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;

Comment on lines +79 to +84
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
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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()))
}
}
}

Comment on lines +613 to +614
let address = peer_address.as_bannable();
let accumulated = self.peerdb.record_recent_offense(address, score);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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);

Comment on lines +2027 to +2033
if msg.oversized_reason() {
self.adjust_peer_score(
peer_id,
WILL_DISCONNECT_OVERSIZED_REASON_BAN_SCORE,
"Oversized WillDisconnect reason",
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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()),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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())),

Comment on lines +1435 to +1437
OutputValue::TokenV0(_) => {
continue;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
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:

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant