Skip to content

Name a refused count, length or script number by its bound (issue #3005) - #3013

Merged
fametrano merged 2 commits into
mainfrom
iss-3005-parser-counts
Nov 9, 2026
Merged

fametrano merged 2 commits into
mainfrom
iss-3005-parser-counts

Conversation

@fametrano

Copy link
Copy Markdown
Member

This is the second of three pull requests for #3005. A refusal that read a count, a length or a number from the octets it refuses, or from the stack of a script, printed that number, and an argument passed in the wrong place can be a key: Inv.parse(b"\xfd" + k[:2]) said invalid items count: 55198, a number of k. Section 7 of the btclib-org standard, A refusal carries no secret, lets a refusal print a field only where it holds a value its format defines. Each refusal now names its bound or what was expected (at most N expected) and still says which rule broke: the counts and lengths of the p2p and block parsers (addr, addrv2, inv, headers, block filters, the partial Merkle tree, the message payload length), the numbers the script engine reads from the stack (the multisig key and signature counts, the pushdata length, OP_PICK and OP_ROLL depths, the lock time of OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY), and script_from_dict's asm does not match hex, which no longer prints either rendering. The transaction's own lock time, version and sequence are written where they fit their four bytes, under #2998 and #3003. The hashes and whole values that the block and p2p checks print are the third part, which closes the issue.

What it breaks: the text of the refusals it names changes; prefixes that callers match stay. btclib-wallet quotes three of the changed texts in tests (btclib-org/btclib-wallet#748). The same leak in btclib-node's own code is btclib-org/btclib-node#2351 and btclib-org/btclib-node#2358.

Evidence

Check Result
suite, -n 3, coverage floor exit 0, 25383 passed, 103 skipped, 5 xfailed, 100.00%
lane "Run the suite with no bindings installed", run locally with the job's command exit 0, 19990 passed, 5396 skipped, 5 xfailed
union of both lanes' coverage, coverage combine and report exit 0, 100.00%
pre-commit run --all-files exit 0
docs sphinx-build -n -W exit 0
signature, git log --format='%h %G? %GS' d6f30596.. 7bfde54b G
Sign-off script on d6f30596..7bfde54b exit 0 (control exits 1)
the 27 rows of tests/refused_counts_test.py against d6f30596's src all fail there, pass on the branch
26 boundary mutants and 4 more for the bounds of AddrV2 and OP_ROLL all killed
dedicated local review CHANGES REQUESTED on 2b22a96e (a docstring saying the refusal names both renderings; wording of the keep list; two surviving boundary mutants), then CLEARED 7bfde54b
fresh review in Codex missing: ERROR: Your workspace is out of credits. Add credits to continue., 2026-11-08 09:18 CET

The dedicated reviewer's CLEARED of the head stands in for the fresh review.

Part of #3005

🤖 Generated with Claude Code

A refusal of octets printed a number it had read from them: with k a
key passed in their place, Inv.parse(b"\xfd" + k[:2]) said "invalid
items count: 55198", k's first two bytes, and a script pushing k[3:7]
before OP_CHECKLOCKTIMEVERIFY printed them as its lock time. Section 7
of the btclib-org standard, *A refusal carries no secret*, lets such a
refusal print a length, and a version or prefix field the format
defines, but no other byte of the value. Each refusal below now names
the bound it expected, or the length, and not the number it read.

Changed:

- the parsed counts of Addr, AddrV2, CFHeaders, Inv, GetBlocks and
  Headers, and NetworkAddressV2's address length ("at most N
  expected"); Headers' per-header transaction count ("0 expected");
  Message.parse's payload length
- BasicBlockFilter's out-of-range element, whose bound is the parsed
  element count, and PartialMerkleTree's transaction count against its
  hashes
- the script engine's numbers read from the stack: the multisig key and
  signature counts, a non-minimal number, the pushdata length past the
  script and past the element size, OP_PICK's and OP_ROLL's depths, and
  CHECKLOCKTIMEVERIFY's and CHECKSEQUENCEVERIFY's lock times and
  sequences; the transaction's own lock time and sequence are still
  written, as the int policy of issue #2998 writes a value that fits
  its field
- script_from_dict's asm against hex, which wrote both renderings of a
  script that may push a key

Examined and kept: the constructors' counts and lengths and
_assert_valid_count's, each a len() of what a caller holds; Block's
transaction count and stripped size; the block filter's bits left and
trailing bytes; Tx.assert_standard's version, BlockHeader's timestamps,
the header-context time comparisons and bad-cb-locktime, each a field
read at its size whose every value the format defines, refused against
policy or context; and the engine's minimal-push refusal, whose one byte
is a value the minimal-push rule names. Message.parse's payload length
and PartialMerkleTree's transaction count are fields read at their size
too, and are described anyway: each is refused against a bound the
refusal names instead, which is the stricter reading.

tests/refused_counts_test.py feeds a fixed random key to each changed
refusal, compares its text whole, asserts that the text of every
exception in its chain is a prefix of it, and checks it with
assert_secret_free and a per-byte 0x check. A second test there holds
AddrV2's count and OP_ROLL's depth at their bound and one past it. The
tests quoting the old texts now quote the new ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>
@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes

    • Error messages for invalid network messages, block filters, Merkle trees, and scripts no longer include supplied counts, lengths, values, or bytes. Validation rules and rejection behavior remain unchanged.
    • Some errors now state the applicable maximum or expected value, while others use a concise fixed message.
  • Tests

    • Updated and expanded coverage to verify revised error messages, validation behavior, and boundary conditions.

Several block, P2P, and script refusal messages now omit selected values from input. Validation conditions and error codes remain unchanged. Tests check the revised messages and selected boundary behavior.

Changes: Input-Derived Refusal Messages

Layer / File(s) Summary
Block and P2P parser messages
src/btclib/block/*, src/btclib/p2p/*, tests/block/partial_merkle_tree_test.py, tests/p2p/*, tests/huge_int_message_test.py
Parser refusal messages omit selected received counts and lengths, or state the expected value. Related tests expect the revised text.
Script refusal messages
src/btclib/script/engine/*, src/btclib/script/script.py, tests/script/*, tests/script_engine/script_test.py, tests/huge_int_message_test.py, tests/tx/*
Script refusal messages omit selected operand values, counts, and assembly text. Tests assert the updated messages.
Refusal-message regression coverage
tests/refused_counts_test.py
New parameterized cases check exact refusal text, exception chains, key-derived values, and selected address-count and stack-depth boundaries.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

  • btclib-org/btclib#3004 — Both PRs change lock-time and sequence refusal messages in script_op_codes.py, and their expected messages depend on integer formatting.
  • btclib-org/btclib#2918 — Both PRs change the Headers.parse transaction-count refusal message and its test expectation.

Suggested reviewers: pmazzocchi

Merge Risk: Minimal · up to a11bb

No actionable issue is established from the supplied evidence; the change is mergeable after normal checks.

Security architecture risk: Low · up to a11bb

The reviewed changes reduce disclosure of rejected input without weakening validation checks. No introduced security concern was established. Residual uncertainty concerns downstream consumers of exception text and refusal paths outside the reviewed scope.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly affected disclosure surface is exception text available to callers of the reviewed parsers and script operations. Exposure through application logs or remote responses depends on downstream handling, which is not established by this review.

Trust Boundaries and Controls

  • observed — The reviewed changes remove selected rejected values at the exception-construction boundary without relaxing the underlying controls. Script number minimality, multisig count ranges, and pushdata size checks retain their error identities and validation conditions.

Resilience and Maintainability Implications

  • observed — The new regression cases assert exact refusal text, inspect chained exceptions, and check selected count and stack-depth boundaries. These assertions support the intended confidentiality contract but do not establish exhaustive coverage of every refusal or downstream consumer.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Name a refused count, length or script number by its bound (issue #3005)" matches the main change. The PR changes refusal messages in count, length, and script-number checks so they state t…
Description check Passed The description states the purpose (a refusal should not print a count, length, or number read from refused input), lists the changed parsers and script-engine checks, and names the changed message te…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Name a refused count, length or script number by its bound (issue #3005)" matches the main change. The PR changes refusal messages in count, length, and script-number checks so they state the bound or expected value instead of echoing the received number. The title is specific and describes the core change. It does not name the exact scope (p2p, block, script engine), but it is not overly broad or misleading. The title check requirements point to the organization standard, which the title does not visibly violate on its face. No evidence of a prefix or JIRA key requirement is present in the supplied requirements text.

Full details: Description check

Explanation

The description states the purpose (a refusal should not print a count, length, or number read from refused input), lists the changed parsers and script-engine checks, and names the changed message text (asm does not match hex). It also gives test and verification evidence and links the work to issue #3005 and related PRs. It is closely related to the changeset.

Finishing Touches

Generate docstrings

  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d6f3059 and a11bb5a.

Files selected for processing: 19

  • src/btclib/block/block_filter.py
  • src/btclib/block/partial_merkle_tree.py
  • src/btclib/p2p/address.py
  • src/btclib/p2p/addrv2.py
  • src/btclib/p2p/block_filters.py
  • src/btclib/p2p/inventory.py
  • src/btclib/p2p/message.py
  • src/btclib/script/engine/script.py
  • src/btclib/script/engine/script_op_codes.py
  • src/btclib/script/script.py
  • tests/block/partial_merkle_tree_test.py
  • tests/huge_int_message_test.py
  • tests/p2p/block_filters_test.py
  • tests/p2p/inventory_test.py
  • tests/refused_counts_test.py
  • tests/script/script_test.py
  • tests/script_engine/script_test.py
  • tests/tx/tx_in_test.py
  • tests/tx/tx_out_test.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@claude claude 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.

ACK 7bfde54

  • Non-blocking: the description says "prefixes that callers match stay" under What it breaks, and that is not true of several of the changed texts. non-minimal encoding of is now non-minimal number encoding of, and pushdata of N bytes, … is now pushdata longer than the … (src/btclib/script/engine/script_op_codes.py:144, :310). N signatures for M public keys is now invalid number of signatures: … (src/btclib/script/engine/script.py:520). asm does not match hex: lost its : (src/btclib/script/script.py:770). This tree's own tests matched those prefixes, and the diff changes them in tests/script_engine/script_test.py, tests/script/script_test.py and tests/tx/tx_{in,out}_test.py. That statement is the cost a downstream caller reads, so it should list these changes rather than say the prefixes stay.

@coderabbitai coderabbitai 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.

Additional comments: 1

tests/block/partial_merkle_tree_test.py-125-128: 1

125-128: Trivial · Maintainability & Code Quality · Low value

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Exact-match regex pins the full message and the hash count.

The anchored pattern makes the test fail on harmless wording changes. It also keeps the input-derived count in the contract. Match a stable prefix instead.

Based on learnings, tests should prefer "key substrings" over full-text comparisons of prose.

Proposed fix

-    with pytest.raises(
-        BTClibValueError,
-        match=r"^partial merkle tree: 2 hashes for fewer transactions$",
-    ):
+    with pytest.raises(BTClibValueError, match="for fewer transactions"):

Source: Learnings

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d6f3059 and 7bfde54.

Files selected for processing: 19

  • src/btclib/block/block_filter.py
  • src/btclib/block/partial_merkle_tree.py
  • src/btclib/p2p/address.py
  • src/btclib/p2p/addrv2.py
  • src/btclib/p2p/block_filters.py
  • src/btclib/p2p/inventory.py
  • src/btclib/p2p/message.py
  • src/btclib/script/engine/script.py
  • src/btclib/script/engine/script_op_codes.py
  • src/btclib/script/script.py
  • tests/block/partial_merkle_tree_test.py
  • tests/huge_int_message_test.py
  • tests/p2p/block_filters_test.py
  • tests/p2p/inventory_test.py
  • tests/refused_counts_test.py
  • tests/script/script_test.py
  • tests/script_engine/script_test.py
  • tests/tx/tx_in_test.py
  • tests/tx/tx_out_test.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

assert_signature_num built its refusal from two string literals, an
assignment and an augmented assignment to the same name, which
Sourcery's merge-assign-and-aug-assign refuses. The text is now one
literal, and reads as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>

@claude claude 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.

ACK a11bb5a

@fametrano
fametrano merged commit 7057c08 into main Nov 9, 2026
22 checks passed
@fametrano
fametrano deleted the iss-3005-parser-counts branch November 9, 2026 05:40
fametrano added a commit to btclib-org/ai-agents-process that referenced this pull request Nov 9, 2026
Sourcery is a pull request's check and not a local gate, as section 10
of the organization standard says. Two rules that btclib's
.sourcery.yaml leaves on failed a pull request after its local gates
passed, each costing a commit and a round of checks: invert-any-all on
tests/b58_test.py in PR btclib-org/btclib#2982, and
merge-assign-and-aug-assign on src/btclib/script/engine/script.py in
PR btclib-org/btclib#3013.

A bullet of The gates points to that section and names the two rules,
with the shape each refuses and the shape that passes. The session on
whose pull request another rule fires proposes it for the list at its
Wrap-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ferdinando Ametrano <ferdinando@ametrano.net>
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