Skip to content

fix(key-wallet): validate an AddressPool on decode - #1590

Draft
xdustinface wants to merge 7 commits into
devfrom
fix/validate-decoded-address-pool
Draft

xdustinface wants to merge 7 commits into
devfrom
fix/validate-decoded-address-pool

Conversation

@xdustinface

Copy link
Copy Markdown
Collaborator

AddressPool derived its serde and bincode decoding field by field, so a decoded pool skipped the checks that construction and insert apply. A stored gap limit of 0 or above MAX_GAP_LIMIT, hardened indices, index gaps or duplicate addresses were accepted, and the reverse lookup maps were taken as stored even when they disagreed with the addresses. A gap limit of 0 then made maintain_gap_limit underflow, and a huge one made it derive addresses until memory ran out.

Decoding now reads the same fields into a private StoredAddressPool and rebuilds the pool through new_without_generation and insert. The gap limit is clamped as on construction, invalid addresses fail the decode, and the lookup maps are rebuilt from the addresses. The stored format does not change: data encoded by the current code decodes to the same pool in both formats.

Closes #1443

`AddressPool` derived its serde and bincode decoding field by field, so a decoded pool skipped the checks that construction and `insert` apply. A stored gap limit of 0 or above `MAX_GAP_LIMIT`, hardened indices, index gaps or duplicate addresses were accepted, and the reverse lookup maps were taken as stored even when they disagreed with the addresses. A gap limit of 0 then made `maintain_gap_limit` underflow, and a huge one made it derive addresses until memory ran out.

Decoding now reads the same fields into a private `StoredAddressPool` and rebuilds the pool through `new_without_generation` and `insert`. The gap limit is clamped as on construction, invalid addresses fail the decode, and the lookup maps are rebuilt from the addresses. The stored format does not change.

Fixes #1443
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

This pull request is a draft, so Manki does not review it automatically. Marking it ready for review starts automatic reviews. Until then, someone with write access to this repository can tick a box below: Review this draft reviews the current commit once, Deeper review does so with more effort, and Review every push reviews it now and again after each push.

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

CI does not run on this PR while it is a draft. Someone with write access can start it here:

  • Run CI once on the current commit
  • Run CI on every push, starting now

Marking the PR ready for review also starts CI.

CI started for c0004f1: Continuous integration, Pre-commit Checks, Sanitizer.

@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 9m 31s

Planner (5s)
    feat · 164 lines · 2 agents
    judge effort: high

Review (security · full): 8 findings
    ✅ Claude Opus 5.5 · high: 0 findings (2m 1s)
    ✅ GPT 6.2 Sol · high: 7 findings (2m 40s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 18 of 18 done, 1 finding (57s)
    ✅ Second reads: 1 of 1 done (48s)

Judge (5m 1s)
    graded 8 findings: 5 kept · 3 dropped
    dropped, as the finders filed them: 2 blockers · 1 suggestion
    refuter: 3 checked · 2 confirmed · 1 disproved
    origin checks: 2 checked
    verdict reader: read the diff (46s)

Posted: 4 findings
    1 warning · 3 suggestions
    not posted: 1 rare trigger

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner, security-sensitive paths)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 58% (resets 2026-12-04 20:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Kept: "Serde decoding changes the name of the stored struct" (warning): "warning. serde(try_from = "StoredAddressPool") at address_pool.rs:306 makes AddressPool::deserialize call the derived StoredAddressPool visitor. serde_derive passes the container name, which is now StoredAddressPool, to deserialize_struct (serde_derive struct_.rs:144-146). Serialize on AddressPool still writes AddressPool. The field names are kept by the renames at :336 and :338, but the container name is not. For any format that checks struct names, data the old code and the current code write no longer decodes, which breaks the AGENTS.md rule that existing data must stay decodable. Whether a format callers use actually checks the name is library code not shown here, so the blocker cell is held at a warning. The fix is a one-line #[serde(rename = "AddressPool")] on StoredAddressPool.
    Refutation unsettled: The serde formats this repo uses ignore the name passed to deserialize_struct: serde_json and the serde side of grovedb-bincode both throw it away. No Cargo.toml in the repo or in dashpay/platform names ron or any other format that checks the name, so whether a downstream user's format would reject the data depends on code I can't read. Rule checked: A serde_derive struct passes its container name to Deserializer::deserialize_struct, and only a format that compares that name with one stored in the data can tell AddressPool from StoredAddressPool.
  • Premise "A serde data format such as ron compares the name passed to deserialize_struct with the struct name stored in the data and returns an error when they differ." unsettled. ron is not a dependency of this repo; no Cargo.toml here or in dashpay/platform names it and the repo has no lockfile. Its name check can't be read, and the formats that are in use (serde_json, the serde side of grovedb-bincode) ignore the name.
  • Premise "An AddressPool serialized before this PR, or by the current Serialize derive, in such a format fails AddressPool::deserialize after this PR." unsettled. With serde_json and the serde side of grovedb-bincode, the only serde formats I could read, a pool written as AddressPool still decodes through StoredAddressPool, because neither checks the struct name. Whether a format that does check the name is ever used with this public library type depends on code I can't read.
    Pair refutation confirmed: The PR makes the writer supply AddressPool and the reader request StoredAddressPool. A name-checking token decoder exposes the mismatch, but the wallet round-trip test uses JSON and native bincode, and I found no wallet caller or stored data using a format that checks the name. Rule checked: Serde passes the derived struct name to the format, which can reject input when its stored name differs from the name requested by the decoder.
  • Premise "A serde data format such as ron compares the name passed to deserialize_struct with the struct name stored in the data and returns an error when they differ." confirmed. The serde_test token format checks the name when it reads a Struct token; RON itself was not available in the PR's dependencies to verify.
  • Premise "An AddressPool serialized before this PR, or by the current Serialize derive, in such a format fails AddressPool::deserialize after this PR." confirmed. For a format that checks struct names, the current derive supplies AddressPool on write, but the new try_from decoder requests StoredAddressPool, so the name check fails before conversion."
  • Dropped: "Bincode can exhaust memory before pool validation runs" (ignore): "ignore. The up-front allocation sized by a declared length is bincode's generic container decoding. It runs decoder.claim_container_read::<(K, V)>(len) first (grovedb-bincode impl_std.rs:488), which enforces whatever limit the caller puts in its config. This Decode impl is generic over the caller's config and delegates to the derived decoders, so it honours a configured limit. The decoded fields and their types are the same ones the old derived Decode read. A caller decoding untrusted bytes with standard() and NoLimit has opted out of the limit. That is the caller's configuration choice, not a guard this PR removes or a defect in its lines.
    Refutation disproved: The drop's premise holds: when the caller's config sets a byte limit, the claim of len × size_of::() bytes returns LimitExceeded before HashMap::with_capacity_and_hasher, vec![0u8; len] or Vec::with_capacity runs. Repository callers do decode with standard() (NoLimit), but the up-front allocation also happened under the old derived Decode. Whether standard() reaches untrusted saved bytes holding an AddressPool, and so whether the PR adds a defect, is not settled by what I read. Rule checked: bincode 2's container decoders call claim_container_read before they allocate from a declared length, and that call only refuses the length when the decode config sets a byte limit; with NoLimit it always succeeds.
  • Premise "bincode's claim_container_read returns an error before HashMap::with_capacity_and_hasher or Vec::with_capacity allocates when the caller's decode config sets a byte limit smaller than the declared length." confirmed. When a limit is set, claim_container_read checks len × size_of::() against it, and claim_bytes_read returns LimitExceeded once bytes_read passes the limit. Both the HashMap and Vec decoders make this claim before they allocate, so a limit smaller than the declared length fails before any allocation, because every entry type here takes at least one byte.
    Pair refutation disproved: The standard-config pool round trip reaches the same length-based allocations as the base commit, before the new validation runs. It supplies valid bytes, so it does not establish that a corrupt save supplies a length large enough to abort the process. Rule checked: Bincode checks a configured container budget before allocating, but with no limit it can allocate from a stored length before reading the payload or running application validation.
  • Premise "bincode's claim_container_read returns an error before HashMap::with_capacity_and_hasher or Vec::with_capacity allocates when the caller's decode config sets a byte limit smaller than the declared length." confirmed. With a configured byte limit, bincode checks the declared count times the element size and propagates a limit error before either map or vector allocation, including the specialized byte-vector path."
  • Kept: "Both decoders keep the discarded lookup tables alive while building replacements" (suggestion): "note. for (index, info) in stored.addresses at :355 moves only addresses. _address_index and _script_pubkey_index stay alive until try_from returns, while insert builds the new maps at :612-613. Pools hold up to the gap limit plus the used addresses, typically tens to a few thousand entries, so two extra short-lived maps cost little memory. Destructuring stored and dropping the old maps before the loop removes the overlap."
  • Kept: "A decoded pool can hand out addresses for the wrong network" (suggestion): "note. insert (address_pool.rs:585-616) has never checked an address's network, and this PR applies exactly the checks that construction and insert apply, as it states. A stored address whose network differs from the pool's is therefore accepted, as it was before. It can only come from a corrupt or hand-edited store. Such a store can equally plant a same-network address that no decode check can catch, because insert never re-derives addresses. Adding a network check to insert is a useful hardening, not a defect of this change."
  • Not listed, its trigger is rated below review.min_warning_trigger: "The hardened-index test also fails the gap check" (warning): "warning. populated_pool builds an External pool with indices 0..=4. The "hardened index" case removes index 4 and re-inserts the entry at 1 << 31. After 0..=3 are inserted, next_index_to_derive() is 4, so the gap check at :588-589 rejects 1 << 31 even without the ChildIndex::new check at :586. The case only asserts decoded.is_none(), so it cannot fail when the hardened-index check it is named after breaks. Testing it in an AbsentHardened pool, which skips the gap check, isolates the hardened-index check.
    Refutation confirmed: populated_pool builds an External pool with gap limit 5, which derives indices 0..=4. The "hardened index" case moves entry 4 to key 1<<31. try_from inserts 0..=3 first, so next_index_to_derive() is 4. The gap check at :588-589 then rejects 1<<31 whether or not the ChildIndex::new check at :586 runs. The test only asserts decoded.is_none(), so it passes either way. Rule checked: An assertion that only checks that decoding failed cannot tell which of two rejecting checks failed it, so removing one of them leaves the test passing.
  • Premise "This trigger happens in realistic use: When the ChildIndex::new check in insert is removed or weakened, the "hardened index" case still passes" confirmed. Without :586, insert for index 1<<31 in the External pool reaches :588-589. There 1<<31 > 4 = next_index_to_derive() returns an error, so the decode still fails and the test's only assertion, is_none(), holds.
    Pair refutation confirmed: The fixture moves index 4 to 1 << 31 in an External pool, leaving indices 0 through 3. If the ChildIndex check no longer rejects that value, the gap check still rejects it because the next index is 4. Rule checked: An assertion that checks only whether decoding failed cannot distinguish which validation check rejected the input.
  • Premise "This trigger happens in realistic use: When the ChildIndex::new check in insert is removed or weakened, the "hardened index" case still passes" confirmed. If ChildIndex::new accepts the fixture's mutated index or the call is removed, the unchanged External-pool gap check still produces the rejection that the assertion accepts.", trigger 3 and harm 3 of 10: "The weakness only shows if someone later removes or breaks the hardened-index check ChildIndex::new, since the test would still pass; normal runs never expose it."
  • Kept: "The new valid-pool round trip does not check compatibility with previous saves" (suggestion): "note. test_valid_pool_round_trips_unchanged encodes with the current writers and decodes with the current readers (:1229-1233). It does not pin bytes or JSON from before the change, and serde_json ignores struct names. A fixture of pre-change output in each format would guard the format claim in the description. Missing test coverage is a note."
  • Dropped: "Repeated stored address indices may be collapsed before validation" (ignore): "ignore. The encoder writes a BTreeMap<u32, AddressInfo>, so it never produces repeated keys. Only hand-crafted or corrupt data can contain them. If a later entry replaces an earlier one, every surviving entry still goes through the index check at :356 and through insert at :362. The decoded pool therefore still meets every invariant this PR enforces, which is the PR's goal of a pool that is valid or refused. No damage follows from the collapse."
  • Dropped: "ManagedPlatformAccount decode does not check that its network matches the decoded address pool's network" (ignore): "ignore. managed_platform_account.rs is not changed by this PR, and its Decode (:275-302) read network and addresses separately before this PR as well. A fix in address_pool.rs does not make the same kind of gap in an untouched file part of this change. The mismatch may be real, but it belongs in its own issue."

Timing:

  • Parse: 9.2s
  • Review agents: 260.2s
  • Judge: 300.9s
  • Total: 570.3s

@coderabbitai

coderabbitai Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ 1 warning to address. Fix it, reply in its thread with a reason Manki accepts, or tick Create an issue for this to track it for later. The PR is also a draft, so mark it ready for review too. If no approval follows, comment /manki check.


Checked and left out: 2 findings (1 disproved, 1 rare)

Disproved by a check of the code · 1 finding

  • Bincode can exhaust memory before pool validation runs · key-wallet/src/managed_account/address_pool.rs:371
    The drop's premise holds: when the caller's config sets a byte limit, the claim of len × size_of::() bytes returns LimitExceeded before HashMap::with_capacity_and_hasher, vec![0u8; len] or Vec::with_capacity runs.

Rare trigger, so not listed · 1 warning

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed db4e7b7, round 1
  • 164 changed lines read in 9m 31s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 3.8M in (3.0M from cache) · 85k out · about $4.95 at API prices
  • Runner: self-hosted · started after 11s · peak memory 5.3 GiB of 30.0 GiB
  • How Manki reviews

Decoding an `AddressPool` kept the stored `address_index` and `script_pubkey_index` maps alive while `insert` built their replacements, so a large pool held two copies of both maps at its peak. The stored pool is now destructured and both stored maps are dropped before the rebuild starts.
Serde decoding went through `StoredAddressPool`, so a format that records struct names saw `AddressPool` written but `StoredAddressPool` requested, and could refuse existing pools and pools just written. The stored struct now deserializes under the name `AddressPool`.

A `serde_test` token check asserts the name the decoder requests. `serde_test` is already a workspace dependency and becomes a dev-dependency of `key-wallet`.
A decoded `AddressPool` accepted an address whose prefix does not belong to the pool network. The rebuilt lookups counted it as part of the pool and `next_unused` could hand it out as a receive address. Decoding now refuses an address that is not valid for the pool network, using the prefix check so devnet and regtest pools still accept their testnet-prefixed addresses.
The round trip test only fed the current writer's output to the current reader, so it could not catch a change to the stored format. It now holds the JSON and bincode of a one-address pool written by the code before decoding validated the pool, and checks both that the current writer produces the same bytes and that the current reader decodes them to the expected pool.
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 10m 55s

Planner (5s)
    feat · 217 lines · 2 agents
    judge effort: high

Review (security · full): 8 findings
    ✅ Claude Opus 5.5 · high: 0 findings (2m 19s)
    ✅ GPT 6.2 Sol · high: 7 findings (3m 46s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 19 of 19 done, 1 finding (1m 40s)

Judge (5m 17s)
    graded 8 findings: 6 kept · 2 dropped
    dropped, as the finders filed them: 1 blocker · 1 warning
    refuter: 3 checked · 2 confirmed · 1 unsettled
    origin checks: 3 checked · 2 older than this PR
    sweeps: 2 of 2 done (17s)
    verdict reader: read the diff (40s)

Posted: 5 findings
    2 warnings · 3 suggestions
    not posted: 1 no realistic trigger

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner, security-sensitive paths, CI or dependency paths)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 68% (resets 2026-12-04 20:00 UTC)
  • ChatGPT subscription: weekly 2% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Kept: "Bincode allocates from stored lengths before pool validation" (blocker): "blocker, held until the length check is confirmed. StoredAddressPool is new in this PR (address_pool.rs:331-339) and its derived Decode at address_pool.rs:383 decodes both reverse maps before try_from runs. The cited grovedb-bincode code at impl_std.rs:491 calls HashMap::with_capacity_and_hasher(len, ..) with the length read from the input, and Address decoding at dash/src/address.rs:507 reads a String whose length also comes from the input. A few bytes that declare a huge length can abort or exhaust memory before any pool check runs. The maps are dropped at address_pool.rs:358 only after they were allocated in full. A public decode API is reached by any caller that passes untrusted bytes. The only open question is whether bincode's limit hook bounds the length under the default config.
    Refutation confirmed: Under standard(), claim_container_read returns Ok without looking at len. The HashMap and Vec<u8> decoders then call with_capacity_and_hasher(len, ..) and vec![0u8; len] before reading any entry. AddressPool::decode decodes all of StoredAddressPool, including both discarded maps, before try_from runs. This allocation was already there with the old derived Decode on AddressPool, so the PR keeps it rather than introducing it. Rule checked: In bincode 2 (grovedb-bincode 2.1.0), claim_container_read checks the declared length only when the config sets a byte limit, and bincode::config::standard() sets none (NoLimit), so container decoders allocate whatever length the input declares.
  • Premise "Under bincode::config::standard() with no byte limit, claim_container_read and the String/Vec<u8> decoders in grovedb-bincode 2.1.0 do not bound the declared length before HashMap::with_capacity_and_hasher(len, ..) and vec![0u8; len] allocate it" confirmed. claim_container_read only checks len when LIMIT.is_some(), and standard() builds Configuration with the default L = NoLimit. So under standard() the declared length goes straight into HashMap::with_capacity_and_hasher(len, ..) and vec![0u8; len].
    Pair refutation confirmed: The standard config disables the container limit check. Both reverse maps are decoded before pool validation can discard them; the base revision already decoded the same maps, so this PR leaves the allocation risk in place rather than introducing it. Rule checked: A decoder that allocates from a stored length before checking the remaining input can incur memory costs proportional to the declared length rather than the data supplied.
  • Premise "Under bincode::config::standard() with no byte limit, claim_container_read and the String/Vec<u8> decoders in grovedb-bincode 2.1.0 do not bound the declared length before HashMap::with_capacity_and_hasher(len, ..) and vec![0u8; len] allocate it" confirmed. With standard() the limit is None, so claim_container_read returns Ok without checking the length, and neither the map decoder nor the byte-vector decoder checks the remaining input before allocation; String delegates to that byte-vector decoder."
  • Kept: "The next top-up multiplies an unchecked stored derivation path" (blocker): "blocker, held until the path depth question is settled. This PR clamps only gap_limit on decode and passes the stored base_path through unchanged (address_pool.rs:360, address_pool.rs:418-420). Each generated address clones the full path (address_pool.rs:515), and generate_address_at_index stores one clone and returns another (address_pool.rs:588-589). A top-up of an empty pool with gap limit 1000 therefore makes about 2000 copies of a path the input controls. A stored path of a few megabytes becomes gigabytes on the next top-up. The PR set out to stop decoded pools from exhausting memory on top-up, so this path is an unfinished part of the same fix.
    Refutation confirmed: Decoding a pool only clamps gap_limit and keeps base_path as it was stored, at any depth. The next maintain_gap_limit then derives up to 1000 addresses, and each one gets its own full clone of base_path. A path of about 2 bytes per entry in the input becomes a pool holding about 1000 copies of it, roughly 8 bytes per entry each. Rule checked: In Rust, cloning a Vec-backed value copies every element, so N clones of a path with k entries take N*k memory; and decoding a length-prefixed Vec, or splitting a string with collect, gives as many entries as the input has.
  • Premise "Decoding a DerivationPath with serde or bincode accepts a path with any number of ChildNumber entries, with no depth limit" confirmed. Both decoders accept any depth. The bincode Decode for DerivationPath decodes a plain Vec with no length check. The serde Deserialize parses the string with FromStr, which splits on '/' and collects every part with no limit. try_from passes the result on unchanged.
    Pair refutation confirmed: Both decoders pass the stored path through unchanged. The BIP32 depth check does not stop the top-up: key derivation uses a short relative path, while the full stored path is copied into each address record. Rule checked: Cloning a Vec copies its elements, so limiting the number of clones does not bound their total size when the vector length comes from stored input.
  • Premise "Decoding a DerivationPath with serde or bincode accepts a path with any number of ChildNumber entries, with no depth limit" confirmed. Serde collects all valid path components from a string, and bincode decodes a length-prefixed vector; neither imposes a derivation-depth limit, though a caller can configure a general bincode size limit."
  • Not listed, it names no trigger that happens in realistic use: "Pools accepted by public insertion can no longer be restored" (warning): "warning. The public insert (address_pool.rs:597-627) never compares an address's prefix with the pool network. AddressInfo::new_from_script_pubkey_p2pkh (address_pool.rs:248-253) builds entries for any network the caller names, and the encoders write such a pool unchanged. The decode check added at address_pool.rs:368 now refuses the whole pool in both formats. A saved wallet built that way can no longer be loaded, which breaks the key-wallet rule that existing data must stay decodable. No caller in the repository is shown inserting a wrong-network address, so the trigger is rare and the finding stays a warning. Putting the same check in insert, as the earlier thread suggested, stops new bad data but does not restore pools already saved.
    Refutation unsettled: If a saved pool held an address whose prefix does not match the pool network, the new decode check would reject the whole pool. That part holds. But no caller found builds such an entry: the in-repo caller of insert and the platform consumer's restore paths all make addresses from the pool's or wallet's own network. Only a library user who passes a different network on purpose could produce the pool, and no such user was found. Rule checked: A public library method that accepts any value counts as a real trigger only when callers, tests, documentation or outside input actually pass the bad value, not merely when the type allows it.
  • Premise "This trigger happens in realistic use: the sequence of events the description names" disproved. No caller found passes insert an address built for a network other than the pool's. AddressInfo::new_from_script_pubkey_p2pkh has no caller anywhere in the repository. The other in-repo callers of insert are the pool's own address generation (line 588) and the new decode path (line 374). The platform consumer builds its restored rows with Address::from_script using pool.network() or the wallet's network. So nothing in normal use stores a pool that contains a wrong-network address.
    Pair refutation unsettled: Public insertion accepts a valid address with the opposite network prefix at an existing index, and neither encoder checks the prefix against the pool network. The PR adds that comparison to the conversion shared by both decoders. Rule checked: A decoder-only check breaks backward compatibility when it rejects a value that the existing public API and encoders accept.
  • Premise "This trigger happens in realistic use: the sequence of events the description names" unsettled. Insertion is documented for restoring persisted entries, and Platform uses it for that purpose, but the checked paths do not show an application inserting an opposite-prefix row and then saving the pool with either encoder; the mismatch test constructs the stored entry directly."
  • Kept: "Repeated stored indices can erase entries before validation" (suggestion): "note. The claim is correct: addresses is a BTreeMap (address_pool.rs:336), and the cited bincode decoder at impl_alloc.rs:115 calls map.insert, so a repeated key keeps only the last entry. The encoder never writes duplicate keys, so only corrupt input reaches this. The surviving entry still passes every check, and the decoded pool is valid. No invalid state gets through, so this is a stricter-decoding improvement and no defect."
  • Dropped: "Public address generation accepts an unbounded batch size" (ignore): "ignore. generate_addresses (address_pool.rs:482-491) is unchanged by this PR, and the diff does not change how its count is reached. It derives exactly the number of addresses its caller asks for, which is what it is for. It is not a sibling of the decode fix."
  • Kept: "The hardened-index test also fails the gap check" (suggestion): "note. The claim is correct: the fixture is an External pool, so index 1 << 31 is also refused by the gap check at address_pool.rs:600-607. Without the ChildIndex::new check at address_pool.rs:598 the case still passes. Decode still refuses hardened indices in External pools either way, so the asserted behaviour holds. What is missing is a case for an AbsentHardened pool, where only the child-index check refuses the entry. Line 598 is not changed by this PR, so no changed line goes uncovered."
  • Kept: "The fixture comment describes the previous implementation" (suggestion): "note. The comment at address_pool.rs:1239 says the fixture was written "before decoding validated the pool". That describes a previous implementation, which the root AGENTS.md rule "No history in code" forbids. The fix is wording only."
  • Dropped: "ManagedPlatformAccount::decode accepts a network that differs from the network of its decoded AddressPool" (ignore): "ignore. managed_platform_account.rs is not changed by this PR, and its decode (lines 275-302) skipped this network check before the PR too. A fix in address_pool.rs does not make the same gap in an unchanged file part of this change."

Timing:

  • Parse: 9.6s
  • Review agents: 328.9s
  • Judge: 316.8s
  • Total: 655.3s

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approval held: this PR is a draft. Mark it ready for review, and Manki approves it if nothing else holds the approval. If the latest commit has no review yet, Manki reviews it first when automatic review runs on this PR. If nothing happens, as for a PR from a fork or while automatic review is off or paused, comment /manki check, and Manki approves or says what holds the approval.

✅ Approved. 2 warnings and 3 suggestions, none of which block.

  • Check approval

What this does: Saved address pools were loaded as stored, so a zero gap limit could crash later and corrupt entries went unnoticed. Loading now rebuilds the pool with the normal checks, clamps the gap limit and returns an error for corrupt data.


Pre-existing · 2 warnings

This PR did not cause these, so none of them block: each is on lines the PR did not change, or the code fails the same way without the PR.

⚠️ Bincode allocates from stored lengths before pool validation
Warning, not blocking · Pre-existing · Security · Moderate · key-wallet/src/managed_account/address_pool.rs:383

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/managed_account/address_pool.rs:301, so it doesn't block this PR.

What goes wrong: A corrupt pool can exhaust memory or panic during native bincode decoding before any pool validation runs. Both reverse indexes allocate from their declared counts before reading the entries, even though the decoder discards them, and nested address strings and public key vectors also allocate before reading their contents.

How to fix it
Preserve the existing field order and encodings, but enforce a decode budget before allocating, read collections incrementally, and consume the reverse indexes without retaining them. Bound nested byte reads too, and preserve any stricter limit the caller configured.

  • Create an issue for this
⚠️ The next top-up multiplies an unchecked stored derivation path
Warning, not blocking · Pre-existing · Security · Quick fix · key-wallet/src/managed_account/address_pool.rs:360

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/managed_account/address_pool.rs:301, so it doesn't block this PR.

What goes wrong: A decoded pool with a long base_path can still exhaust memory on its next gap-limit top-up. Clamping the gap to 1000 limits the number of new entries, not their size: each generated entry copies the full path into both the pool and the returned batch.

How to fix it
Validate path depth against the supported derivation limits before accepting stored pools. Enforce the same bound before generation from pools built through the public constructor so all generation paths reject oversized paths before copying them.

  • Create an issue for this

What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Build key-wallet with the serde and bincode features and have a wallet saved by the previous release.

  1. Load a wallet saved by the previous release. Expect it to decode with the same addresses, reservations and used flags.
  2. Save and reload a pool with a reserved and a used address via JSON and via bincode. Expect identical state after reload.
  3. Edit a saved pool so gap_limit is 0, then load it and call maintain_gap_limit. Expect gap limit 1 and no panic.
  4. Edit a saved pool so gap_limit is above 1000. Expect it clamped to 1000.
  5. Remove address_index and script_pubkey_index contents from a saved pool. Expect lookups like contains_address to still work after load.
  6. Give two entries the same address in saved data. Expect decode to fail with an error, not a panic.
  7. Delete a middle index from a non-hardened pool's saved addresses. Expect decode to fail.
  8. Replace one entry with a mainnet address in a testnet pool. Expect decode to fail.
About this review
  • Reviewed c0004f1, round 2
  • 217 changed lines read in 10m 55s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 4.8M in (3.9M from cache) · 96k out · about $5.90 at API prices
  • Runner: self-hosted · started after 14s · peak memory 3.9 GiB of 30.0 GiB
  • How Manki reviews

@codecov

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.72727% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.18%. Comparing base (9329b3e) to head (c0004f1).
⚠️ Report is 1 commits behind head on dev.

Files with missing lines Patch % Lines
key-wallet/src/managed_account/address_pool.rs 97.72% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1590      +/-   ##
==========================================
+ Coverage   88.16%   88.18%   +0.01%     
==========================================
  Files         270      270              
  Lines       72623    72754     +131     
==========================================
+ Hits        64031    64160     +129     
- Misses       8592     8594       +2     
Flag Coverage Δ
core 83.91% <97.72%> (+0.04%) ⬆️
rpc 83.91% <97.72%> (+0.04%) ⬆️
spv 95.44% <ø> (-0.01%) ⬇️
wallet 83.91% <97.72%> (+0.04%) ⬆️
Files with missing lines Coverage Δ
key-wallet/src/managed_account/address_pool.rs 92.55% <97.72%> (+1.88%) ⬆️

... and 6 files with indirect coverage changes

The hardened index case moved an entry past the end of an `External` pool, so the gap check refused it even without the child index check. The case now uses an `AbsentHardened` pool, where gaps are allowed, so only the child index check can refuse it.
The fixture comment described when decoding started to validate the pool. It now says what the fixture is: a pinned sample of the stored format.
@manki-review

manki-review Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Review complete in 8m 50s

Planner (5s)
    feat · 218 lines · 2 agents
    judge effort: high

Review (security · full): 6 findings
    ✅ Claude Opus 5.5 · high: 0 findings (2m 25s)
    ✅ GPT 6.2 Sol · high: 5 findings (2m 24s)
    ✅ Comparisons, related checks, claim checks and pattern checks: 18 of 18 done, 1 finding (1m 49s)

Judge (4m 37s)
    graded 6 findings: 5 kept · 1 dropped
    dropped, as the finders filed them: 1 suggestion
    refuter: 3 checked · 2 confirmed · 1 disproved
    origin checks: 2 checked · 2 older than this PR
    sweeps: 2 of 2 done (12s)
    verdict reader: read the diff (38s)

Posted: 3 findings
    2 warnings · 1 suggestion
    not posted: 1 on code an earlier round reviewed · 1 disproved by a check of the code

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner, security-sensitive paths, CI or dependency paths)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 18% (resets 2026-12-08 05:00 UTC)
  • ChatGPT subscription: weekly 3% (resets 2026-12-10 07:41 UTC)

Judge decisions:

  • Dropped: "Pools accepted by insert can no longer be restored" (ignore): "warning. insert at key-wallet/src/managed_account/address_pool.rs:597-627 checks the child index, gaps and duplicates, but not the address network. The new try_from at :368 refuses any address that is not valid for the pool network. So the public API can build and encode a pool that the decoder then rejects. Before this PR such data decoded. This contradicts the PR's own claim that data the current code encodes decodes again, and the key-wallet rule that persisted bytes stay decodable. Whether real stored pools hold such entries depends on callers of insert that are not shown, so the defect premise stays open. A clean fix that keeps the new check is to apply the same network check in insert, so the writer and the reader agree.
    Refutation disproved: Every caller of AddressPool::insert builds the address from the pool's own network. In key-wallet the only non-decode caller is generation, which uses Address::new(self.network, ..). In the platform consumer, core_pool uses Address::from_script(&script, pool.network()) and the platform-node restore uses the wallet's network, and both skip or refuse scripts that do not decode for that network. So no pool with a wrong-network address is built and then saved. Rule checked: A decoder that is stricter than a public setter only breaks round-trips when some caller actually passes the setter data the decoder rejects; here that would be an address whose prefix differs from the pool network.
  • Premise "A caller of the public AddressPool::insert passes an AddressInfo whose address is not valid for the pool's network, and the pool is then persisted with serde or bincode." disproved. No caller in the repo or the platform consumer passes insert an address built for a network other than the pool's. Generation uses self.network, core_pool decodes with pool.network(), and the platform-node restore decodes with the wallet network and skips scripts that fail to decode.
  • Premise "Decoding a wallet backup or ManagedWalletInfo that contains such a pool fails as a whole, because the AddressPool decode error propagates to the outer decode." confirmed. AddressPool::decode maps a try_from error to a DecodeError. The types that contain pools, such as ManagedAccountType, derive Decode, which passes a field's error up with ?, so the outer decode fails as a whole.
    Pair refutation unsettled: insert stores addresses without checking their network, but both decoders reject a wrong-network entry. The mismatch test changes the stored representation directly; it does not establish that a caller inserts and saves such an entry. Rule checked: A persisted type should round-trip values accepted by its public mutation API.
  • Premise "A caller of the public AddressPool::insert passes an AddressInfo whose address is not valid for the pool's network, and the pool is then persisted with serde or bincode." unsettled. The documented restore API permits the mismatch, but the in-tree generator uses the pool's network and the mismatch test bypasses insert; no checked caller was shown to insert and persist a mismatched address.
  • Premise "Decoding a wallet backup or ManagedWalletInfo that contains such a pool fails as a whole, because the AddressPool decode error propagates to the outer decode." confirmed. If a mismatched pool is present in the serialized accounts, its deserialization error fails the enclosing ManagedWalletInfo serde decode rather than dropping just that pool."
  • Kept: "A gap top-up can still exhaust memory after a successful decode" (blocker): "warning, kept on the cell from the earlier round because the code at this spot did not change. DerivationPath decodes Vec<ChildNumber> with no depth limit (key-wallet/src/bip32.rs:847). The new try_from passes it unchecked to new_without_generation (address_pool.rs:360, :418). A top-up of up to MAX_GAP_LIMIT entries then clones the full path into every entry (:515), and :588 keeps a copy in the pool and another in the returned batch. A few megabytes of input can therefore grow to gigabytes. The gap-limit clamp bounds the entry count but not the size of each entry. The issue this PR closes names a hostile store as the threat. Whether any caller bounds the path before a top-up is still open.
    Refutation confirmed: The decoded base_path reaches the pool unchecked, and a later top-up of up to MAX_GAP_LIMIT entries clones the whole path into each entry. Key derivation uses only a short relative path, so nothing fails or stops the generation. Rule checked: Cloning a value N times allocates N times its size, so a gap-limit clamp bounds the number of entries but not the size of each one; a Vec decoded from bincode or serde has no length bound beyond the input size.
  • Premise "No code between decoding an AddressPool and calling maintain_gap_limit or generate_addresses on it limits the depth of base_path." confirmed. try_from passes base_path straight to new_without_generation, which only clamps gap_limit. No depth check on base_path exists in key-wallet. The restore path goes from restore_utxos to extend_pools to maintain_gap_limit with no check in between.
    Pair refutation confirmed: Restoration stores the decoded base path unchanged and clamps only the gap limit. The JSON path alone demonstrates the amplification; I could not verify the binary codec's own input limits. Rule checked: Cloning a Vec copies its elements, so limiting the number of generated entries does not bound their memory cost when each entry owns an input-sized vector.
  • Premise "No code between decoding an AddressPool and calling maintain_gap_limit or generate_addresses on it limits the depth of base_path." confirmed. The shared restore conversion preserves the path unchanged, and the tested decode-to-top-up call reaches generation without an intervening depth check."
  • Kept: "Malformed-input tests construct pool state through private fields" (suggestion): "note. The tests do set fields on the private StoredAddressPool, but only to build input. decode_stored (address_pool.rs:1228-1236) serializes that input to JSON and bincode and runs both public decoders on the bytes. The malformed bytes are exactly what production decoding can receive, so the rule's concern about states production never reaches does not apply. The useful part of the finding is that decoded.is_none() (:1340) accepts any decode error. Asserting the specific error would stop an unrelated failure from satisfying a case."
  • Not listed, on code an earlier round reviewed: "The bincode decoder uses fully qualified paths instead of imports" (suggestion): "note. core::result::Result at address_pool.rs:382 and bincode::Decode::decode at :383 each use two qualifiers, and the root AGENTS.md allows only one. The module's own Result alias explains the need for the standard Result, but use core::result; with result::Result satisfies the rule. This is style only, with no effect at run time."
  • Kept: "Stored lookup lengths may allocate memory before pool validation" (blocker): "warning, kept on the cell from the earlier round because the decode path at this spot did not change. The new StoredAddressPool decodes address_index and script_pubkey_index as HashMaps (address_pool.rs:337-338) through the bincode call at :383, before try_from drops them at :358-359. If the dependency allocates from the declared length, a short blob can exhaust memory before any validation runs. The allocation sits in grovedb-bincode, which is not shown, so that premise is named again for a check with tools.
    Refutation confirmed: grovedb-bincode 2.1.0 does preallocate the HashMap from the declared length under standard() with no limit. But no production path in this repo or in the platform consumer bincode-decodes an AddressPool from unbounded untrusted bytes: the consumer uses a bounded config and stores pools as SQL rows. The same HashMap decode existed before the PR through the derived Decode. Rule checked: With a bincode config that has no byte limit, claim_container_read is a no-op, so container decoders preallocate from the declared length before reading entries.
  • Premise "Under bincode::config::standard() with no byte limit, grovedb-bincode 2.1.0 calls HashMap::with_capacity_and_hasher(len, ..) for a map, and vec![0u8; len] for a string or byte vector, with the declared len before it reads the entries, and does not bound len by the remaining input." confirmed. HashMap::decode reads len, calls claim_container_read (which returns Ok without any check when the config has no limit, and standard() defaults to NoLimit), then calls HashMap::with_capacity_and_hasher(len, ..) before decoding entries. Vec similarly calls vec![0u8; len] before reading, with no bound against the remaining input.
    Pair refutation confirmed: Both lookup maps are allocated from their declared lengths before pool validation can run. The standard-config test decodes a valid fixture; I found no caller or stored input that supplies a length large enough to establish memory exhaustion. Rule checked: A decoder that reserves capacity from a stored length before checking the payload can request memory out of proportion to the bytes supplied.
  • Premise "Under bincode::config::standard() with no byte limit, grovedb-bincode 2.1.0 calls HashMap::with_capacity_and_hasher(len, ..) for a map, and vec![0u8; len] for a string or byte vector, with the declared len before it reads the entries, and does not bound len by the remaining input." confirmed. With standard() the container claim does nothing, so both decode paths allocate maps and byte vectors from the declared length before reading the payload, and String uses the byte-vector decoder; a configured limit instead checks the length-times-element-size claim against the byte budget before allocation, not against the remaining input."
  • Dropped: "ManagedPlatformAccount::decode does not check that its stored network matches its address pool's network" (ignore): "ignore. key-wallet/src/managed_account/managed_platform_account.rs is not changed by this PR, and its decode at :275-302 behaves exactly as before. A fix in another file does not make the same gap in an unchanged file part of this change."

Timing:

  • Parse: 9.6s
  • Review agents: 243.7s
  • Judge: 276.8s
  • Total: 530.1s

Last reviewed 1f35b4d · head 1f35b4d · up to date

  • Pause automatic reviews
  • Review again
  • Deeper review
  • Review this draft
  • Review every push

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approval held: this PR is a draft. Mark it ready for review, and Manki approves it if nothing else holds the approval. If the latest commit has no review yet, Manki reviews it first when automatic review runs on this PR. If nothing happens, as for a PR from a fork or while automatic review is off or paused, comment /manki check, and Manki approves or says what holds the approval.

✅ Approved. 2 warnings and 1 suggestion, none of which block.

  • Check approval

What this does: Saved address pools were trusted as read, so corrupt data could load an inconsistent pool. Loading now rebuilds the pool from its address list.


Pre-existing · 2 warnings

This PR did not cause these, so none of them block: each is on lines the PR did not change, or the code fails the same way without the PR.

⚠️ A gap top-up can still exhaust memory after a successful decode
Warning, not blocking · Pre-existing · Security · Moderate · key-wallet/src/managed_account/address_pool.rs:360

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/managed_account/address_pool.rs:301, so it doesn't block this PR.

What goes wrong: Both decoders accept a pool with an arbitrarily long base_path. A normal top-up can then copy that entire path into each of up to 1,000 generated entries, retaining copies both in the pool and in the returned vector. This can exhaust memory even though the decoded gap_limit is within bounds.

How to fix it
Enforce a derivation-path depth bound at the shared path-validation boundary before any generation clones the path, and apply it during restoration too. Make the failure a typed error and cover both restored pools and paths supplied by callers.

  • Create an issue for this
⚠️ Stored lookup lengths may allocate memory before pool validation
Warning, not blocking · Pre-existing · Security · Moderate · key-wallet/src/managed_account/address_pool.rs:383

Manki could not confirm this, so please check it.

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/managed_account/address_pool.rs:301, so it doesn't block this PR.

What goes wrong: The bincode decoder reads both stored lookup maps before validation discards them. The dependency's allocation order determines whether a declared map length can exhaust memory before the decoder checks the input or returns an error.

  • Create an issue for this

What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Build key-wallet with the serde and bincode features, and keep a wallet state saved by the previous version.

  1. Load wallet state saved by the previous version. Expect it to decode, with the same addresses, reservations and used flags.
  2. Save a pool and load it with serde JSON and with bincode. Expect the same addresses and lookups as before saving.
  3. Edit saved JSON so gap_limit is 0. Expect it to load with a gap limit of 1.
  4. Edit saved JSON so gap_limit is far above 1000. Expect it to load with a gap limit of 1000.
  5. Remove one middle entry from addresses in saved JSON. Expect loading to fail with an error and no panic.
  6. Give two entries the same address in saved JSON. Expect loading to fail.
  7. Replace one address with a mainnet address in a testnet pool. Expect loading to fail.
  8. Clear address_index and script_pubkey_index in saved JSON. Expect the pool to load and both lookups to be rebuilt.

Checked and left out: 1 finding

Disproved by a check of the code · 1 finding

  • Pools accepted by insert can no longer be restored · key-wallet/src/managed_account/address_pool.rs:368
    Every caller of AddressPool::insert builds the address from the pool's own network. In key-wallet the only non-decode caller is generation, which uses Address::new(self.network, ..).

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed 1f35b4d, round 3
  • 218 changed lines read in 8m 50s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 4.5M in (3.7M from cache) · 92k out · about $5.59 at API prices
  • Runner: self-hosted · started after 12s · peak memory 3.8 GiB of 30.0 GiB
  • How Manki reviews

fn test_decode_clamps_gap_limit_and_rebuilds_lookups(stored_gap_limit: u32, gap_limit: u32) {
let original = populated_pool();
let mut stored = stored_pool(&original);
stored.gap_limit = stored_gap_limit;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ Suggestion, not blocking · Testing · Moderate

Malformed-input tests construct pool state through private fields

Why: The clamp, lookup, and rejection cases set fields on the private production StoredAddressPool type to make their fixtures. That couples the malformed input to the same type and derives that the tests are supposed to check.

How to fix it and 12 places read

How to fix it
Prepare malformed JSON and bincode at the serialized boundary, then feed it to the public decoders. Assert the expected error for each rejection case so an unrelated decoding error cannot satisfy the test.

Checked in the code
On the commented line: Sets stored.gap_limit and clears both private lookup maps.

Mutates an entry's address, and line 1320 removes an entry to make a gap.

let address = stored.addresses[&0].address.clone();
stored.addresses.get_mut(&1).unwrap().address = address;
}; "duplicate address")]
#[test_case(|stored| {
stored.addresses.remove(&1);
}; "index gap")]
#[test_case(|stored| {
stored.pool_type = AddressPoolType::AbsentHardened;

Changes stored.pool_type and moves an entry to a hardened numeric index, line 1329 changes the entry index alone, and line 1333 replaces the address with one…

#[test_case(|stored| {
stored.pool_type = AddressPoolType::AbsentHardened;
let mut info = stored.addresses.remove(&4).unwrap();
info.index = 1 << 31;
stored.addresses.insert(info.index, info);
}; "hardened index")]
#[test_case(|stored| {
stored.addresses.get_mut(&4).unwrap().index = 3;

Converts decoder errors to None, and line 1340 accepts any such error.

[
serde_json::from_str(&json).ok(),
bincode::decode_from_slice(&bytes, bincode::config::standard())
.ok()
.map(|(pool, _)| pool),

  • Create an issue for this
  • Dismiss this finding

This branch has not been deployed

No deployments
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.

key-wallet: decoding AddressPool skips the gap_limit clamp and insert checks

1 participant