Make bytes_from_octets the whole of what Octets means - #766
Merged
Conversation
Contributor
There was a problem hiding this comment.
Sorry @fametrano, you have reached your weekly rate limit of 500000 diff characters.
Please try again later or upgrade to continue using Sourcery
Contributor
Reviewer's GuideStandardize Octets coercion via bytes_from_octets, propagate btclib-specific error classes/messages for malformed hex/entropy across utilities and mnemonic/borromean modules, and tighten argument validation while preserving secrecy of key/entropy material. Sequence diagram for standardized Octets coercion via bytes_from_octetssequenceDiagram
actor Caller
participant to_prv_key
participant bytes_from_octets
participant BTClibValueError
participant BTClibTypeError
Caller->>to_prv_key: int_from_prv_key(prv_key)
to_prv_key->>bytes_from_octets: bytes_from_octets(prv_key, ec.n_size)
alt hex string input
bytes_from_octets->>bytes_from_octets: bytes.fromhex(octets)
opt malformed hex string
bytes_from_octets-->>BTClibValueError: raise BTClibValueError("invalid hex string: ...")
end
else non-buffer, non-str input
bytes_from_octets-->>BTClibTypeError: raise BTClibTypeError("invalid octets type: ...")
else bytes/bytearray/memoryview
bytes_from_octets-->>to_prv_key: octets (unchanged buffer)
to_prv_key->>to_prv_key: int.from_bytes(prv_key, "big")
to_prv_key-->>Caller: q (private key integer)
end
rect rgb(230,230,230)
Note over to_prv_key: Error handling path
end
to_prv_key-->>Caller: raise BTClibValueError("not a private key: ...")
note right of Caller: to_prv_key catches (TypeError, ValueError)
note right of Caller: and re-raises BTClibValueError without echoing key material
Sequence diagram for mnemonic entropy parsing via _int_from_bin_strsequenceDiagram
actor Caller
participant wordlist_indexes_from_bin_str_entropy
participant _int_from_bin_str
participant BTClibValueError
participant BTClibTypeError
Caller->>wordlist_indexes_from_bin_str_entropy: wordlist_indexes_from_bin_str_entropy(entropy, base)
wordlist_indexes_from_bin_str_entropy->>wordlist_indexes_from_bin_str_entropy: bits = len(entropy)
wordlist_indexes_from_bin_str_entropy->>_int_from_bin_str: _int_from_bin_str(entropy)
alt entropy is binary 0/1 string
_int_from_bin_str->>_int_from_bin_str: int(entropy, 2)
_int_from_bin_str-->>wordlist_indexes_from_bin_str_entropy: int_entropy
wordlist_indexes_from_bin_str_entropy->>wordlist_indexes_from_bin_str_entropy: divmod loop to compute indexes
wordlist_indexes_from_bin_str_entropy-->>Caller: indexes
else entropy has wrong type
_int_from_bin_str-->>BTClibTypeError: raise BTClibTypeError("invalid entropy type: ...")
else entropy not binary 0/1 string
_int_from_bin_str-->>BTClibValueError: raise BTClibValueError("invalid entropy: not a binary 0/1 string")
end
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
fametrano
force-pushed
the
block-type-guards
branch
from
August 13, 2026 17:49
1a43513 to
c1316b7
Compare
fametrano
force-pushed
the
octets-are-total
branch
from
August 13, 2026 17:51
7b4eded to
29051ca
Compare
fametrano
force-pushed
the
block-type-guards
branch
from
August 13, 2026 19:34
c1316b7 to
ab649e0
Compare
It is the coercion every `Octets` parameter of the library runs through, and it had two holes. A hex string that is not one left through `bytes.fromhex`'s bare ValueError -- the class the contract promises, with nothing saying it came from here. And anything that was not a `str` went through *untouched*, so `len` of a tuple of 33 ints was 33, which is how `taproot.assert_valid_control_block` accepted one as a control block size and how `bin_str_entropy_from_entropy(())` was reported as zero bits. Both are refused now. Every buffer is still taken, and returned as it came: a read must not rewrite the field it reads, which is what `bytes()` here would do to a bytearray a caller built. The message is `bytes.fromhex`'s own, which names a position and never the string: an Octets parameter is candidate key material as often as not, and `to_prv_key` puts this very message inside its own "not a private key" (issue #137). `to_prv_key`'s two "it must be octets" fallbacks catch a TypeError beside the ValueError, as `to_pub_key` already did. `mnemonic.entropy`'s five `int(x, 2)` parses and its `int(x, 16)` and `int(x)` ones are BTClibValueError too, and say a base rather than the digits. `borromean.sign` checks that its rings, signing indexes and nonces are of one length rather than leaving it to `zip(strict=True)`, whose message named "argument 3" and no parameter of the function; strict=True stays, as the assertion that the check and the loops cannot drift apart. Six test files stop asserting the bare class, `docs/source/guide.rst` shows the new spelling, and HISTORY.md carries the breaking-changes bullet for this and for the three slices before it. The last slice of #744.
fametrano
force-pushed
the
octets-are-total
branch
from
August 13, 2026 19:35
29051ca to
0635559
Compare
fametrano
added a commit
that referenced
this pull request
Aug 13, 2026
* Ask a value what it is before asking what it holds Ten places in `block/`, `hashes` and `utils` compared, added to or read an attribute off an argument nothing had checked. `"5" <= 16`, `"2015" + 1` and `"hard" <= 0` are bare TypeErrors about operands, raised from underneath the library and naming neither the parameter nor the function; `.tzinfo` on a str is an AttributeError, outside *both* halves of this library's exception contract, so nothing a caller is told to catch would have caught it; and two datetimes given as unix timestamps subtract to an int, whose missing `total_seconds` is an AttributeError again. The guard is `var_int.serialize`'s and the vocabulary `is_integer`'s: a bool is not a number, it being the height one, the block count one, the leaf index one. `bip34_commitment`, and `Block.assert_valid_coinbase_height` through it; `BlockHeader.assert_valid`'s timestamp and `assert_valid_time`'s `now`; `mining.mine`'s max_tries and its header, which `dataclasses.replace` used to complain about; `next_bits`'s two datetimes; `retarget_first_height`; all three numbers of `hash_rate`, where a difficulty and a timespan are float and an integer is one of those; `hashes.merkle_root_from_branch`'s leaf index, which is what `merkle_proof.assert_as_valid` and `merkle_proof.verify` reach it through; and `utils.encode_num`. `BlockHeader._assert_valid_types` is an extraction and not only a check: `assert_valid` was one branch under C901's ten. The bool half of the eight new integer guards goes in `tests/integer_policy_test.py`, where the other twenty-five already are. The fourth slice of #744. * Make `bytes_from_octets` the whole of what Octets means (#766) It is the coercion every `Octets` parameter of the library runs through, and it had two holes. A hex string that is not one left through `bytes.fromhex`'s bare ValueError -- the class the contract promises, with nothing saying it came from here. And anything that was not a `str` went through *untouched*, so `len` of a tuple of 33 ints was 33, which is how `taproot.assert_valid_control_block` accepted one as a control block size and how `bin_str_entropy_from_entropy(())` was reported as zero bits. Both are refused now. Every buffer is still taken, and returned as it came: a read must not rewrite the field it reads, which is what `bytes()` here would do to a bytearray a caller built. The message is `bytes.fromhex`'s own, which names a position and never the string: an Octets parameter is candidate key material as often as not, and `to_prv_key` puts this very message inside its own "not a private key" (issue #137). `to_prv_key`'s two "it must be octets" fallbacks catch a TypeError beside the ValueError, as `to_pub_key` already did. `mnemonic.entropy`'s five `int(x, 2)` parses and its `int(x, 16)` and `int(x)` ones are BTClibValueError too, and say a base rather than the digits. `borromean.sign` checks that its rings, signing indexes and nonces are of one length rather than leaving it to `zip(strict=True)`, whose message named "argument 3" and no parameter of the function; strict=True stays, as the assertion that the check and the loops cannot drift apart. Six test files stop asserting the bare class, `docs/source/guide.rst` shows the new spelling, and HISTORY.md carries the breaking-changes bullet for this and for the three slices before it. The last slice of #744.
fametrano
added a commit
that referenced
this pull request
Aug 13, 2026
* Ask a value what it is before asking what it holds Ten places in `block/`, `hashes` and `utils` compared, added to or read an attribute off an argument nothing had checked. `"5" <= 16`, `"2015" + 1` and `"hard" <= 0` are bare TypeErrors about operands, raised from underneath the library and naming neither the parameter nor the function; `.tzinfo` on a str is an AttributeError, outside *both* halves of this library's exception contract, so nothing a caller is told to catch would have caught it; and two datetimes given as unix timestamps subtract to an int, whose missing `total_seconds` is an AttributeError again. The guard is `var_int.serialize`'s and the vocabulary `is_integer`'s: a bool is not a number, it being the height one, the block count one, the leaf index one. `bip34_commitment`, and `Block.assert_valid_coinbase_height` through it; `BlockHeader.assert_valid`'s timestamp and `assert_valid_time`'s `now`; `mining.mine`'s max_tries and its header, which `dataclasses.replace` used to complain about; `next_bits`'s two datetimes; `retarget_first_height`; all three numbers of `hash_rate`, where a difficulty and a timespan are float and an integer is one of those; `hashes.merkle_root_from_branch`'s leaf index, which is what `merkle_proof.assert_as_valid` and `merkle_proof.verify` reach it through; and `utils.encode_num`. `BlockHeader._assert_valid_types` is an extraction and not only a check: `assert_valid` was one branch under C901's ten. The bool half of the eight new integer guards goes in `tests/integer_policy_test.py`, where the other twenty-five already are. The fourth slice of #744. * Make `bytes_from_octets` the whole of what Octets means (#766) It is the coercion every `Octets` parameter of the library runs through, and it had two holes. A hex string that is not one left through `bytes.fromhex`'s bare ValueError -- the class the contract promises, with nothing saying it came from here. And anything that was not a `str` went through *untouched*, so `len` of a tuple of 33 ints was 33, which is how `taproot.assert_valid_control_block` accepted one as a control block size and how `bin_str_entropy_from_entropy(())` was reported as zero bits. Both are refused now. Every buffer is still taken, and returned as it came: a read must not rewrite the field it reads, which is what `bytes()` here would do to a bytearray a caller built. The message is `bytes.fromhex`'s own, which names a position and never the string: an Octets parameter is candidate key material as often as not, and `to_prv_key` puts this very message inside its own "not a private key" (issue #137). `to_prv_key`'s two "it must be octets" fallbacks catch a TypeError beside the ValueError, as `to_pub_key` already did. `mnemonic.entropy`'s five `int(x, 2)` parses and its `int(x, 16)` and `int(x)` ones are BTClibValueError too, and say a base rather than the digits. `borromean.sign` checks that its rings, signing indexes and nonces are of one length rather than leaving it to `zip(strict=True)`, whose message named "argument 3" and no parameter of the function; strict=True stays, as the assertion that the check and the loops cannot drift apart. Six test files stop asserting the bare class, `docs/source/guide.rst` shows the new spelling, and HISTORY.md carries the breaking-changes bullet for this and for the three slices before it. The last slice of #744.
fametrano
added a commit
that referenced
this pull request
Aug 13, 2026
* Ask a value what it is before asking what it holds Ten places in `block/`, `hashes` and `utils` compared, added to or read an attribute off an argument nothing had checked. `"5" <= 16`, `"2015" + 1` and `"hard" <= 0` are bare TypeErrors about operands, raised from underneath the library and naming neither the parameter nor the function; `.tzinfo` on a str is an AttributeError, outside *both* halves of this library's exception contract, so nothing a caller is told to catch would have caught it; and two datetimes given as unix timestamps subtract to an int, whose missing `total_seconds` is an AttributeError again. The guard is `var_int.serialize`'s and the vocabulary `is_integer`'s: a bool is not a number, it being the height one, the block count one, the leaf index one. `bip34_commitment`, and `Block.assert_valid_coinbase_height` through it; `BlockHeader.assert_valid`'s timestamp and `assert_valid_time`'s `now`; `mining.mine`'s max_tries and its header, which `dataclasses.replace` used to complain about; `next_bits`'s two datetimes; `retarget_first_height`; all three numbers of `hash_rate`, where a difficulty and a timespan are float and an integer is one of those; `hashes.merkle_root_from_branch`'s leaf index, which is what `merkle_proof.assert_as_valid` and `merkle_proof.verify` reach it through; and `utils.encode_num`. `BlockHeader._assert_valid_types` is an extraction and not only a check: `assert_valid` was one branch under C901's ten. The bool half of the eight new integer guards goes in `tests/integer_policy_test.py`, where the other twenty-five already are. The fourth slice of #744. * Make `bytes_from_octets` the whole of what Octets means (#766) It is the coercion every `Octets` parameter of the library runs through, and it had two holes. A hex string that is not one left through `bytes.fromhex`'s bare ValueError -- the class the contract promises, with nothing saying it came from here. And anything that was not a `str` went through *untouched*, so `len` of a tuple of 33 ints was 33, which is how `taproot.assert_valid_control_block` accepted one as a control block size and how `bin_str_entropy_from_entropy(())` was reported as zero bits. Both are refused now. Every buffer is still taken, and returned as it came: a read must not rewrite the field it reads, which is what `bytes()` here would do to a bytearray a caller built. The message is `bytes.fromhex`'s own, which names a position and never the string: an Octets parameter is candidate key material as often as not, and `to_prv_key` puts this very message inside its own "not a private key" (issue #137). `to_prv_key`'s two "it must be octets" fallbacks catch a TypeError beside the ValueError, as `to_pub_key` already did. `mnemonic.entropy`'s five `int(x, 2)` parses and its `int(x, 16)` and `int(x)` ones are BTClibValueError too, and say a base rather than the digits. `borromean.sign` checks that its rings, signing indexes and nonces are of one length rather than leaving it to `zip(strict=True)`, whose message named "argument 3" and no parameter of the function; strict=True stays, as the assertion that the check and the loops cannot drift apart. Six test files stop asserting the bare class, `docs/source/guide.rst` shows the new spelling, and HISTORY.md carries the breaking-changes bullet for this and for the three slices before it. The last slice of #744.
fametrano
added a commit
that referenced
this pull request
Aug 13, 2026
* Check every width a sig_hash preimage writes, and every index `int.to_bytes` answers a field too wide for it with an OverflowError, an ArithmeticError that no `except BTClibValueError` catches; a list index out of range is an IndexError, a LookupError, outside it too. #724 made the version and lock-time checks unconditional in `Tx.serialize`, which closed those two fields for `legacy` -- the one sig_hash routed through it. `segwit_v0` and `taproot` assemble their preimage from their own `to_bytes` calls and never reach it, and `TxIn.serialize` and `TxOut.serialize` check nothing when told not to, so the same leak survived on the sequence, on the output value and on the outpoint's vout. The checks go in the serializations rather than in the callers -- `_serialized_4_byte_field`, `_serialized_camount`, `_serialized_out_point`, `_serialized_output`, `_serialized_spend_type` -- so `PrecomputedTxData` and both `sha_`/`hash_` families get them for free. `legacy` checks what its branches leave behind, NONE dropping the outputs it does not commit to. `vin_i` is bounded in `legacy`, `segwit_v0`, `from_tx` and `taproot_annex_and_ext` as it is in `taproot`; `from_tx` also refuses a prevout list of a different length from the vin, with the message `PrecomputedTxData` gives for the same mismatch. `ext_flag` is seven bits, and `message_extension` takes Octets like every other octets parameter here. `_assert_valid_4_byte_field` is imported from `tx.tx` rather than written a second time, and `_serialized_spend_type` is an extraction and not only a check: `taproot` was one branch under C901's ten. The third slice of #744. * Ask a value what it is before asking what it holds (#765) * Ask a value what it is before asking what it holds Ten places in `block/`, `hashes` and `utils` compared, added to or read an attribute off an argument nothing had checked. `"5" <= 16`, `"2015" + 1` and `"hard" <= 0` are bare TypeErrors about operands, raised from underneath the library and naming neither the parameter nor the function; `.tzinfo` on a str is an AttributeError, outside *both* halves of this library's exception contract, so nothing a caller is told to catch would have caught it; and two datetimes given as unix timestamps subtract to an int, whose missing `total_seconds` is an AttributeError again. The guard is `var_int.serialize`'s and the vocabulary `is_integer`'s: a bool is not a number, it being the height one, the block count one, the leaf index one. `bip34_commitment`, and `Block.assert_valid_coinbase_height` through it; `BlockHeader.assert_valid`'s timestamp and `assert_valid_time`'s `now`; `mining.mine`'s max_tries and its header, which `dataclasses.replace` used to complain about; `next_bits`'s two datetimes; `retarget_first_height`; all three numbers of `hash_rate`, where a difficulty and a timespan are float and an integer is one of those; `hashes.merkle_root_from_branch`'s leaf index, which is what `merkle_proof.assert_as_valid` and `merkle_proof.verify` reach it through; and `utils.encode_num`. `BlockHeader._assert_valid_types` is an extraction and not only a check: `assert_valid` was one branch under C901's ten. The bool half of the eight new integer guards goes in `tests/integer_policy_test.py`, where the other twenty-five already are. The fourth slice of #744. * Make `bytes_from_octets` the whole of what Octets means (#766) It is the coercion every `Octets` parameter of the library runs through, and it had two holes. A hex string that is not one left through `bytes.fromhex`'s bare ValueError -- the class the contract promises, with nothing saying it came from here. And anything that was not a `str` went through *untouched*, so `len` of a tuple of 33 ints was 33, which is how `taproot.assert_valid_control_block` accepted one as a control block size and how `bin_str_entropy_from_entropy(())` was reported as zero bits. Both are refused now. Every buffer is still taken, and returned as it came: a read must not rewrite the field it reads, which is what `bytes()` here would do to a bytearray a caller built. The message is `bytes.fromhex`'s own, which names a position and never the string: an Octets parameter is candidate key material as often as not, and `to_prv_key` puts this very message inside its own "not a private key" (issue #137). `to_prv_key`'s two "it must be octets" fallbacks catch a TypeError beside the ValueError, as `to_pub_key` already did. `mnemonic.entropy`'s five `int(x, 2)` parses and its `int(x, 16)` and `int(x)` ones are BTClibValueError too, and say a base rather than the digits. `borromean.sign` checks that its rings, signing indexes and nonces are of one length rather than leaving it to `zip(strict=True)`, whose message named "argument 3" and no parameter of the function; strict=True stays, as the assertion that the check and the loops cannot drift apart. Six test files stop asserting the bare class, `docs/source/guide.rst` shows the new spelling, and HISTORY.md carries the breaking-changes bullet for this and for the three slices before it. The last slice of #744. * Gate the input-validation rule, and let the gate enumerate (#774) `tests/input_validation_test.py` holds every public module-level function whose required parameters are all library input types to the rule of #744: a malformed argument leaves as a BTClibException. One predicate and not a tuple, which is what #743's base class was landed for. It calls with every argument malformed at once, and that is what makes it automatic: no valid values have to be tabulated -- a valid Octets is 20 bytes here, 32 there and any length elsewhere -- and whichever argument the function refuses first, the rule says it must refuse it as a btclib error. Three lists carry what the run finds, and each ratchets one way. `_MALFORMED` is the vocabulary, and a type renamed out of it fails rather than shrinking the walk in silence. `_EXCLUDED` is the nine `is_p2*` predicates, with the reason `script_pub_key._is_funct` already gives. `_OPEN` is what the census of #744 has left, each entry naming the class that escapes; an entry that has become compliant fails the run, as RUF100 fails an unused noqa, so a fix cannot land without deleting its line. What the walk cannot reach is stated rather than omitted: a parameter behind a default is never driven, `hf` and `network` among them, and a function taking a Tx, a Psbt or a callback needs an instance the vocabulary cannot build. It found what the reading missed: `ecc.dleq.verify_proof` answers False for a pub key that is None, where its own comment says a caller error must raise -- the shape #745 closed in five other verifications, in a function written after that census was taken.
This was referenced Aug 13, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The last slice of #744.
Stacked on #765, which is
on #764, which is on #763. Review the last commit.
The issue proposed this "possibly as a documented decision rather than a
fix". It is a fix: the decision would have been defensible for the class
alone —
BTClibValueErroris aValueError— but not for the holeunderneath it.
Two holes, not one
bytes_from_octetsis the coercion everyOctetsparameter of thelibrary runs through.
bytes.fromhex's bareValueError. The class the contract promises, with nothing saying itcame from here and no way to pin the message.
strwent through untouched. Solenofa tuple of 33 ints is 33, which is exactly how
taproot.assert_valid_control_blockaccepted one as a control blocksize ( Refuse the malformed input twelve places answered anyway #763 fixed the character-count half and could not fix this
one), and how
bin_str_entropy_from_entropy(())was reported aszero bits — a number it never carried.
Decisions worth a reviewer's eye
bytes.fromhex's own, carried through rather thanreplaced. It names a position and never the string, which is the
point: an
Octetsparameter is candidate key material as often asnot, and
to_prv_keyputs this very message inside its own "not aprivate key" (issue Private keys reach exception messages and the generated repr #137). A first draft interpolated
{octets!r}andtests/to_prv_key_test.py::test_a_mistyped_wif_is_reported_as_onecaught it — the suite has a test for exactly this.
bytesalonewould have broken
tests/bip32/bip32_test.py::test_assert_valid_does_not_rewrite_the_key_data,which pins that a read must not coerce a
bytearraya caller built.bytearrayandmemoryvieware accepted with a# type: ignoreatthe call in the test:
Octetsnames the two spellings a callerwrites, not everything a field can hold.
to_prv_keycatchesTypeErrorbesideValueErrorat its two"it must be octets" fallbacks, as
to_pub_keyalready did: what isneither octets nor a spelling of them means the same thing a wrong
size does — this input is not a private key.
borromean.signchecks the three lengths itself.strict=Truesaid "zip() argument 3 is shorter than argument 1", naming no
parameter of the function; the comment above it defended the class,
which was right, and left the message. The check is the function's
now, and
strict=Truestays as the assertion that the two cannotdrift apart.
slices, not just this one. Refuse the malformed input twelve places answered anyway #763 and Check every width a sig_hash preimage writes, and every index #764 turn
OverflowErrorandIndexErrorinto btclib classes and Ask a value what it is before asking what it holds #765 anAttributeError; acaller catching those three has to act, and that is a release note
rather than four. Say the word if you want it split per PR.
What moves for a caller
The class is narrower and the control flow identical —
BTClibValueErroris a
ValueError. A test matchingbytes.fromhex's message stillmatches. The one non-narrowing is hole 2: a non-
Octetsargument is nowa
BTClibTypeErrorwhere it used to be no error, or an error aboutsomething else.
Six test files stop asserting the bare class, and
docs/source/guide.rstshows the new spelling.Gates
uv run pytest— 26508 passed, coverage 100.00%uv run pre-commit run --all-files— exit 0sphinx-build -W --keep-going— exit 0Summary by Sourcery
Tighten octet handling across the library so malformed or non-octet inputs are consistently rejected with btclib-specific errors and clearer messages, without exposing potentially sensitive data.
Bug Fixes:
Enhancements:
Documentation:
Tests: