Skip to content

Describe a refused int by its sign and bit length, never its digits (closes #2998) - #3004

Merged
fametrano merged 1 commit into
mainfrom
iss-2998-int-refusal
Nov 8, 2026
Merged

fametrano merged 1 commit into
mainfrom
iss-2998-int-refusal

Conversation

@fametrano

Copy link
Copy Markdown
Member

_message_text and _message_hex in utils.py wrote a refused int in full, so a 256-bit key passed in an int's place was printed whole by every refusal built on them: _assert_valid_4_byte_field("version", k) raised invalid version: <digits> and sig_hash._epoch_and_agg_mode(k, 0) raised invalid aggregation mode: 0x<hex>. Section 7 of the btclib-org standard, A refusal carries no secret, says an argument in the wrong place may be a key. _message_text now describes every int but a bool by its sign and bit length, as _int_description already did, and _message_hex is gone. A new _message_field writes a value in full only where it fits a field of at most four bytes that the format defines, every value of which is a defined one: the transaction's lock time, version and sequence in the script engine, and the coinbase lock time of BIP54. A BIP155 network id and a BIP157 filter type are described, as their byte holds values the format does not define. A message that names a bound already (bad-cb-amount, the median time past, a target height) keeps the bound alone.

What it breaks: the text of every refusal that quoted an int changes, so a caller matching invalid height: -1 now reads invalid height: a negative int of 1 bits, and several expected sizes print in parentheses whatever iterable held them. Prefixes are unchanged, and no caller in btclib-node parses past one. btclib-wallet's tests/psbt/psbt_test.py matches invalid sig_hash type: 0x4 and will read the new text (btclib-wallet#746); base58-bech32's parity test with _message_text will fail against the release that carries this (base58-bech32#118); the two base conversions that relay its text are xfail, strict, until then.

Evidence

Check Result
suite, -n 3, coverage floor exit 0, 24651 passed, 103 skipped, 2 xfailed, 100.00%
pre-commit run --all-files exit 0
docs sphinx-build -n -W exit 0
signature, git log --format='%h %G? %GS' 51c6b2b6.. b863baab G
Sign-off script on 51c6b2b6..b863baab exit 0 (control exits 1)
the held 256-bit scalar fed to 103 refusals, chain read with assert_secret_free and each byte as 0x and hex none prints it
18 mutants of the helpers and sites, plus 3 of the second round all killed
dedicated local review CHANGES REQUESTED on 06c8ddda (the _message_field docstring left out the second condition of section 7; two sites printed an undefined byte), then CLEARED b863baab
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. The plain f-string refusals outside the helpers are #3003, the str, Decimal and float cases #3002.

Closes #2998

🤖 Generated with Claude Code

…loses #2998)

A refusal built on `utils._message_text` or `utils._message_hex` wrote a
refused int in full, so a 256-bit key passed in an int's place was
printed: `_assert_valid_4_byte_field("version", k)` raised
`invalid version: <digits>`, and `sig_hash._epoch_and_agg_mode(k, 0)`
`invalid aggregation mode: 0x<hex>`. Section 7 of the btclib-org
standard, *A refusal carries no secret*, says an argument in the wrong
place may be a key.

The design: an int refused for its width or its range is described by
its sign and bit length, as `_int_description` already did for an int
`str()` cannot write, or the message names the bound alone where it
already names one. It is never written in full, in decimal or in hex.
`_message_text` now describes every int but a bool, and `_message_hex`
is gone, its callers taking `_message_text`.

Where the full value is the point, the new `_message_field` writes
it when it fits its field and describes it otherwise. Section 7 lets a
refusal print a field its format defines, of at most four bytes, where
the value has the field's length and is one of the values the format
defines. The fields it writes are the lock time, the version and the
sequence of the transaction the script engine checks a lock time
against, and a coinbase's lock time and the one BIP54 asks of it:
every value of their four bytes is a defined one.

A BIP155 network id refused as no ip address and a BIP157 filter type
refused as no basic filter are described: their byte holds values the
format does not define.

The sizes `bytes_from_octets` expected are the library's constants or
the caller's `out_size`, not a field of a format. `_sizes_text` writes
each in full where it fits four bytes and describes it otherwise; a
tuple holding a key was written out whole by `str()`.

The bound alone: `bad-cb-amount` reads "above the subsidy and fees",
the time-too-old refusal ends at the header's timestamp, and a target
height reads "is not between 0 and the height".
`PrefilledTransaction.serialize` describes the previous index it
printed beside the index.

What this breaks: the text of every refusal quoting an int changes, so
a caller matching `invalid height: -1` now reads
`invalid height: a negative int of 1 bits`. Several expected sizes
print in parentheses whatever iterable held them.

`tests/huge_int_message_test.py` feeds a held 256-bit scalar to every
refusal it lists, with cases added for refusals it did not reach, and
checks the chain with `assert_secret_free` and each byte as `0x` and
its hex. The two base conversions relay base58-bech32's own text, which
prints the int, and are `xfail` until btclib-org/base58-bech32#118
lands.

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

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved validation messages across amounts, blocks, transactions, scripts, and network data. Integer values are now described by sign and bit length rather than printed directly, and supported field values use consistent formatting.
    • Clarified several range and timing error messages.
    • Block-height commitments now reject non-integer heights and correctly encode small integer values.

The shared refusal-message helpers now describe integers by sign and bit length and format values that fit bounded fields. Related refusal messages and tests have been updated to use or expect these formats.

Changes: Refusal message formatting

Layer / File(s) Summary
Integer formatting helpers
src/btclib/utils.py, tests/utils_test.py
_message_text describes integers by sign and bit length. _message_field formats fitting integers in the requested field format and uses the descriptive fallback otherwise. Invalid-size messages use the field formatter.
Refusal call sites and coverage
src/btclib/block/*, src/btclib/p2p/compact_blocks.py, src/btclib/script/engine/script_op_codes.py, src/btclib/script/sig_hash.py, src/btclib/tx/tx_context.py, src/btclib/var_int.py, tests/amount_test.py, tests/block/*, tests/consensus_test.py, tests/fee_test.py, tests/huge_int_message_test.py, tests/p2p/*, tests/script/*
Call sites use the revised integer formatters or omit supplied values from refusal messages. Tests update expected error text and add coverage for refusals involving large integers and scalar values.

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

Change: Bug fix · Severity of issue fixed: High

Possibly related issues

  • btclib-org/btclib issue 3002: It concerns non-integer values that _message_text leaves unchanged; this PR changes integer formatting but does not report changes for those other types.
  • btclib-org/btclib issue 3001: It identifies an OP_CHECKSEQUENCEVERIFY refusal that prints a sequence value outside the shared message helpers; the PR changes related opcode refusal formatting but does not report addressing that separate output.
  • btclib-org/btclib issue 3003: It describes ChainStart refusals that print integers outside the shared helper path; this PR does not report changing those sites.

Possibly related PRs

  • btclib-org/btclib#2908: It uses _message_text for a negative offset, which follows the integer-description behavior changed here.

Suggested reviewers: pmazzocchi

Merge Risk: Minimal · up to b863b

No PR-introduced issue remains from this review; the change is mergeable after normal checks.

Security architecture risk: Low · up to b863b

The change reduces accidental integer disclosure through validation errors. One existing error path still exposes an oversized input, but the inspected comparisons show no increased reachability or weaker validation. Error-text compatibility and incomplete coverage remain limitations.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is through exception text returned to a caller. Further disclosure requires that text to cross another boundary, such as logging or an external response; such downstream handling was not established. The inspected changes do not demonstrate increased attacker authority or broader independently attackable scope.

Security Findings and Attack Paths

  • observed — The retained low-severity disclosure concerns ChainStart's median_time_past upper-bound rejection, which directly interpolates an oversized supplied integer. A secret integer passed there can therefore enter exception text. Base/head inspection establishes that both this condition and its local exposure predate the PR; no worsening was established.

Trust Boundaries and Controls

  • observed — The changed control reduces transfer of caller-supplied integer contents into diagnostics. It does not cover every refusal: the retained positive upper-bound path bypasses the formatter, whereas the negative-value check uses it. Unchecked ChainStart objects remain subject to revalidation by the sync constructor.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title states the main change: refused integers are now described by sign and bit length rather than by their digits, which matches the raw summary's changes to _message_text, the removal of _messa…
Description check Passed The description is closely tied to the changeset. It explains that _message_text and _message_hex in utils.py printed full integers, that _message_hex was removed, and that the new _message_field writ…
Linked Issues check Passed [#2998] Requirement: no refusal built on _message_text or _message_hex prints an int wider than its field, and a test feeds a held scalar to each such refusal and checks the chain with assert_secret_f…
Out of Scope Changes check Passed Verified diffs (merge base 51c6b2b to head b863baa):

- src/btclib/block/block.py: the diff removes the _message_text import and the ' <= {median_time_past}' suffix from the median-time-past error. …
Full details: Title check

Explanation

The title states the main change: refused integers are now described by sign and bit length rather than by their digits, which matches the raw summary's changes to _message_text, the removal of _message_hex, and the new _message_field. It also references issue #2998. The title is specific and describes the core change, so it passes the relevance check. The title-requirements link was not reviewed, so casing or format rules from the organization standard are not verified.

Full details: Description check

Explanation

The description is closely tied to the changeset. It explains that _message_text and _message_hex in utils.py printed full integers, that _message_hex was removed, and that the new _message_field writes values only for small defined fields. It also lists the affected call sites (script engine lock time, version and sequence, BIP54 coinbase lock time, BIP155 network id, BIP157 filter type) and the test and downstream impacts. It is detailed and on topic, so it passes.

Full details: Linked Issues check

Explanation

[#2998] Requirement: no refusal built on _message_text or _message_hex prints an int wider than its field, and a test feeds a held scalar to each such refusal and checks the chain with assert_secret_free, decimal included.

Code at head (src/btclib/utils.py): _message_text returns _int_description(value) for every int that is not a bool. It does not call str() on ints, so no decimal digits are printed. _message_hex is removed. _message_field writes an int in full only when it is nonnegative and int.bit_length(value) <= bits. Any other value goes to _message_text. Sites in block_header.py, header_context.py, sig_hash.py, var_int.py, compact_blocks.py, script_op_codes.py, tx_context.py and utils.py now call these helpers. Named bounds (bad-cb-amount, median time past, target height) keep the bound alone.

Test: tests/huge_int_message_test.py imports assert_secret_free and holds a fixed 256-bit scalar (_SCALAR). It has a case table (_CASES, _BOUND_CASES) that covers the helper-built refusals. The PR reports 103 refusals run, and the test file's case table supports that count. I read the file only up to a truncation point, so I did not read the body of the scalar test. I could not run the suite.

Not required by #2998: plain f-string refusals that do not use the helpers (#3003), and str, Decimal and float cases (#3002). The Done-when covers helper-built refusals only.

Residual uncertainty: I could not grep the call sites to confirm that every helper call site appears in the case table. The helper-level guarantee covers each site that passes an int to a helper unchanged.

Full details: Out of Scope Changes check

Explanation

Verified diffs (merge base 51c6b2b to head b863baa):

  • src/btclib/block/block.py: the diff removes the _message_text import and the ' <= {median_time_past}' suffix from the median-time-past error. Nothing else changes. The AI-generated summary of this file claims a bip34_commitment change (height type check, op_int encoding). That claim does not appear in the diff, so I disregard it. The line count (+0/-2) matches the diff.
  • src/btclib/utils.py: adds _sizes_text for expected-size messages in bytes_from_octets, rewrites _message_text, adds _message_field, and removes _message_hex. All changes serve the refusal text in #2998.

By summary only (diffs not read): block_header.py, header_context.py, compact_blocks.py, script_op_codes.py, sig_hash.py, tx_context.py and var_int.py change refusal text where a helper is called. The tests change to match the new text. The summaries describe no change of validation logic, return values or exception types.

Note: the _sizes_text docstring says expected sizes are 'no field of a format', yet it calls _message_field with 32 bits. The _message_field docstring limits full output to defined format fields. This is a documentation inconsistency. It does not change scope, and it does not change the #2998 result.

Residual uncertainty: the diffs for the seven files named above were not read. The verdict relies on their summaries, which the block.py summary contradicted.

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 51c6b2b and b863baa.

Files selected for processing: 22

  • src/btclib/block/block.py
  • src/btclib/block/block_header.py
  • src/btclib/block/header_context.py
  • src/btclib/p2p/compact_blocks.py
  • src/btclib/script/engine/script_op_codes.py
  • src/btclib/script/sig_hash.py
  • src/btclib/tx/tx_context.py
  • src/btclib/utils.py
  • src/btclib/var_int.py
  • tests/amount_test.py
  • tests/block/block_context_test.py
  • tests/block/block_test.py
  • tests/block/header_context_test.py
  • tests/consensus_test.py
  • tests/fee_test.py
  • tests/huge_int_message_test.py
  • tests/p2p/addrv2_test.py
  • tests/p2p/block_filters_test.py
  • tests/p2p/headers_sync_test.py
  • tests/script/sig_hash_script_code_test.py
  • tests/script/taproot_test.py
  • tests/utils_test.py
Files with no reviewable changes: 1

  • src/btclib/block/block.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 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 b863baa

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.

A refused int argument is printed whole, so a key passed in its place is printed

1 participant