Repository navigation
fix(key-wallet): validate an AddressPool on decode - #1590
xdustinface wants to merge 7 commits into
Conversation
`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
|
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. |
|
CI does not run on this PR while it is a draft. Someone with write access can start it here:
Marking the PR ready for review also starts CI. CI started for c0004f1: Continuous integration, Pre-commit Checks, Sanitizer. |
|
✅ Review complete in 9m 31s Planner (5s) Review (security · full): 8 findings Judge (5m 1s) Posted: 4 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
|
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
There was a problem hiding this comment.
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 beforeHashMap::with_capacity_and_hasher, vec![0u8; len] or Vec::with_capacity runs.
Rare trigger, so not listed · 1 warning
- The hardened-index test also fails the gap check ·
key-wallet/src/managed_account/address_pool.rs:1276
Trigger 3 of 10, below the cut-off of 4.
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-5andgpt-6.2-sol, judged byclaude-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.
|
✅ Review complete in 10m 55s Planner (5s) Review (security · full): 8 findings Judge (5m 17s) Posted: 5 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
|
There was a problem hiding this comment.
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.
- Load a wallet saved by the previous release. Expect it to decode with the same addresses, reservations and used flags.
- Save and reload a pool with a reserved and a used address via JSON and via bincode. Expect identical state after reload.
- Edit a saved pool so
gap_limitis0, then load it and callmaintain_gap_limit. Expect gap limit1and no panic. - Edit a saved pool so
gap_limitis above1000. Expect it clamped to1000. - Remove
address_indexandscript_pubkey_indexcontents from a saved pool. Expect lookups likecontains_addressto still work after load. - Give two entries the same address in saved data. Expect decode to fail with an error, not a panic.
- Delete a middle index from a non-hardened pool's saved addresses. Expect decode to fail.
- 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-5andgpt-6.2-sol, judged byclaude-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 Report❌ Patch coverage is
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
|
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.
|
✅ Review complete in 8m 50s Planner (5s) Review (security · full): 6 findings Judge (4m 37s) Posted: 3 findings Review metadataConfig:
Account limits:
Judge decisions:
Timing:
Last reviewed
|
There was a problem hiding this comment.
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.
- Load wallet state saved by the previous version. Expect it to decode, with the same addresses, reservations and used flags.
- Save a pool and load it with serde JSON and with bincode. Expect the same addresses and lookups as before saving.
- Edit saved JSON so
gap_limitis0. Expect it to load with a gap limit of1. - Edit saved JSON so
gap_limitis far above 1000. Expect it to load with a gap limit of1000. - Remove one middle entry from
addressesin saved JSON. Expect loading to fail with an error and no panic. - Give two entries the same address in saved JSON. Expect loading to fail.
- Replace one address with a mainnet address in a testnet pool. Expect loading to fail.
- Clear
address_indexandscript_pubkey_indexin 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
insertcan no longer be restored ·key-wallet/src/managed_account/address_pool.rs:368
Every caller ofAddressPool::insertbuilds the address from the pool's own network. In key-wallet the only non-decode caller is generation, which usesAddress::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-5andgpt-6.2-sol, judged byclaude-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; |
There was a problem hiding this comment.
✨ 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.
rust-dashcore/key-wallet/src/managed_account/address_pool.rs
Lines 1316 to 1323 in 1f35b4d
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…
rust-dashcore/key-wallet/src/managed_account/address_pool.rs
Lines 1322 to 1329 in 1f35b4d
Converts decoder errors to None, and line 1340 accepts any such error.
rust-dashcore/key-wallet/src/managed_account/address_pool.rs
Lines 1231 to 1235 in 1f35b4d
key-wallet/src/managed_account/address_pool.rs:1301:stored.address_index.clear();key-wallet/src/managed_account/address_pool.rs:1302:stored.script_pubkey_index.clear();key-wallet/src/managed_account/address_pool.rs:1329:stored.addresses.get_mut(&4).unwrap().index = 3;key-wallet/src/managed_account/address_pool.rs:1333:info.address = Address::new(Network::Mainnet, info.address.payload().clone());key-wallet/src/managed_account/address_pool.rs:1340:assert!(decoded.is_none());
- Create an issue for this
- Dismiss this finding
AddressPoolderived its serde and bincode decoding field by field, so a decoded pool skipped the checks that construction andinsertapply. A stored gap limit of 0 or aboveMAX_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 mademaintain_gap_limitunderflow, and a huge one made it derive addresses until memory ran out.Decoding now reads the same fields into a private
StoredAddressPooland rebuilds the pool throughnew_without_generationandinsert. 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