Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/btclib/block/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
from btclib.tx.limits import LOCKTIME_THRESHOLD
from btclib.tx.tx_context import is_final
from btclib.utils import (
_message_text,
assert_no_trailing,
assert_type,
bytes_from_octets,
Expand Down Expand Up @@ -566,7 +565,6 @@ def _assert_valid_contextual_header(self, context: BlockContext) -> None:
time = int(self.header.time.timestamp())
if time <= context.median_time_past:
err_msg = f"invalid timestamp (not after the median past): {time}"
err_msg += f" <= {_message_text(context.median_time_past)}"
raise BTClibValueError(err_msg)

self.header.assert_valid_time(context.now)
Expand Down
4 changes: 2 additions & 2 deletions src/btclib/block/block_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from btclib.hashes import hash256
from btclib.utils import (
_assert_valid_4_byte_field,
_message_hex,
_message_text,
assert_no_trailing,
assert_type,
bytes_from_octets,
Expand Down Expand Up @@ -68,7 +68,7 @@ def _assert_valid_version(value: int) -> None:
if not isinstance(value, int):
raise BTClibTypeError(f"invalid version type: {type(value).__name__}")
if not -0x80000000 <= value <= 0x7FFFFFFF:
raise BTClibValueError(f"invalid version: {_message_hex(value)}")
raise BTClibValueError(f"invalid version: {_message_text(value)}")


def _timestamp_of(time: datetime) -> int:
Expand Down
2 changes: 1 addition & 1 deletion src/btclib/block/header_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def header_at_height(
raise BTClibValueError(f"invalid height: {_message_text(height)}")
if not 0 <= target_height <= height:
err_msg = f"invalid target height: {_message_text(target_height)}"
err_msg += f" is not between 0 and {_message_text(height)}"
err_msg += " is not between 0 and the height"
raise BTClibValueError(err_msg)

for _ in range(height - target_height):
Expand Down
2 changes: 1 addition & 1 deletion src/btclib/p2p/compact_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def serialize(
difference = self.index - previous_index - 1
if difference < 0:
err_msg = f"index {_message_text(self.index)}"
err_msg += f" not past previous_index {previous_index}"
err_msg += f" not past previous_index {_message_text(previous_index)}"
raise BTClibValueError(err_msg)

out = var_int.serialize(difference)
Expand Down
20 changes: 11 additions & 9 deletions src/btclib/script/engine/script_op_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@
)
from btclib.tx.tx import Tx
from btclib.utils import (
_message_hex,
_message_text,
_message_field,
assert_type,
decode_num,
encode_num,
Expand Down Expand Up @@ -973,21 +972,23 @@ def op_checklocktimeverify(
raise ScriptError("no transaction to hold the lock time", unsatisfied)
# different lock time type
if tx.lock_time >= LOCKTIME_THRESHOLD > lock_time:
tx_lock_time = _message_field(tx.lock_time, 32, "d")
err_msg = (
f"block height lock time {lock_time} against "
f"the timestamp lock time {_message_text(tx.lock_time)} of the transaction"
f"the timestamp lock time {tx_lock_time} of the transaction"
)
raise ScriptError(err_msg, unsatisfied)
if lock_time >= LOCKTIME_THRESHOLD > tx.lock_time:
tx_lock_time = _message_field(tx.lock_time, 32, "d")
err_msg = (
f"timestamp lock time {lock_time} against "
f"the block height lock time {_message_text(tx.lock_time)} of the transaction"
f"the block height lock time {tx_lock_time} of the transaction"
)
raise ScriptError(err_msg, unsatisfied)

if lock_time > tx.lock_time:
err_msg = f"lock time {lock_time} > {_message_text(tx.lock_time)}"
raise ScriptError(err_msg, unsatisfied)
tx_lock_time = _message_field(tx.lock_time, 32, "d")
raise ScriptError(f"lock time {lock_time} > {tx_lock_time}", unsatisfied)
if tx.vin[i].sequence == 0xFFFFFFFF:
raise ScriptError(f"final sequence for input {i}", unsatisfied)

Expand Down Expand Up @@ -1022,18 +1023,19 @@ def op_checksequenceverify(
if tx is None:
raise ScriptError("no transaction to hold the sequence", unsatisfied)
if tx.version < 2:
err_msg = f"transaction version {_message_text(tx.version)} < 2"
raise ScriptError(err_msg, unsatisfied)
version = _message_field(tx.version, 32, "d")
raise ScriptError(f"transaction version {version} < 2", unsatisfied)
if tx.vin[i].sequence & SEQUENCE_LOCKTIME_DISABLE_FLAG:
err_msg = f"relative lock time disabled for input {i}"
raise ScriptError(err_msg, unsatisfied)
if (
sequence & SEQUENCE_LOCKTIME_TYPE_FLAG
!= tx.vin[i].sequence & SEQUENCE_LOCKTIME_TYPE_FLAG
):
tx_sequence = _message_field(tx.vin[i].sequence, 32, "#x")
err_msg = (
f"relative lock time unit mismatch: {hex(sequence)} against "
f"the sequence {_message_hex(tx.vin[i].sequence)} of input {i}"
f"the sequence {tx_sequence} of input {i}"
)
raise ScriptError(err_msg, unsatisfied)
if (
Expand Down
5 changes: 2 additions & 3 deletions src/btclib/script/sig_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
)
from btclib.utils import (
_assert_valid_8_byte_signed_field,
_message_hex,
_message_text,
bytes_from_octets,
is_integer,
Expand Down Expand Up @@ -113,7 +112,7 @@ def assert_valid_hash_type(hash_type: int) -> None:
err_msg = f"invalid hash_type type: {type(hash_type).__name__}"
raise BTClibTypeError(err_msg)
if hash_type not in SIG_HASH_TYPES:
raise BTClibValueError(f"invalid sig_hash type: {_message_hex(hash_type)}")
raise BTClibValueError(f"invalid sig_hash type: {_message_text(hash_type)}")


def _serialized_hash_type(hash_type: int) -> bytes:
Expand Down Expand Up @@ -863,7 +862,7 @@ def _epoch_and_agg_mode(agg_mode: int | None, ext_flag: int) -> bytes:
err_msg = f"invalid aggregation mode type: {type(agg_mode).__name__}"
raise BTClibTypeError(err_msg)
if agg_mode not in _AGG_MODES:
raise BTClibValueError(f"invalid aggregation mode: {_message_hex(agg_mode)}")
raise BTClibValueError(f"invalid aggregation mode: {_message_text(agg_mode)}")
if is_integer(ext_flag) and 0 < ext_flag <= 0x7F:
raise BTClibValueError("aggregation mode for a script path spend")
return bytes([0x01, agg_mode])
Expand Down
9 changes: 5 additions & 4 deletions src/btclib/tx/tx_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
)
from btclib.tx.tx import Tx
from btclib.tx.tx_out import TxOut
from btclib.utils import _message_text, assert_type, is_integer
from btclib.utils import _message_field, _message_text, assert_type, is_integer

__all__ = [
"AncestorMedianTimePast",
Expand Down Expand Up @@ -253,7 +253,7 @@ def assert_coinbase_value(coinbase: Tx, subsidy: int, fees: int) -> None:
ceiling = subsidy + fees
if coinbase_value > ceiling:
err_msg = f"bad-cb-amount: {_message_text(coinbase_value)}"
err_msg += f" instead of {_message_text(ceiling)}"
err_msg += " above the subsidy and fees"
raise BTClibValueError(err_msg)


Expand Down Expand Up @@ -330,8 +330,9 @@ def assert_bip54_coinbase(coinbase: Tx, height: int) -> None:
if height == 0:
return
if coinbase.lock_time != height - 1:
err_msg = f"bad-cb-locktime: {_message_text(coinbase.lock_time)}"
err_msg += f" instead of {_message_text(height - 1)}"
lock_time = _message_field(coinbase.lock_time, 32, "d")
expected = _message_field(height - 1, 32, "d")
err_msg = f"bad-cb-locktime: {lock_time} instead of {expected}"
raise BTClibValueError(err_msg)
if coinbase.vin[0].sequence == SEQUENCE_FINAL:
raise BTClibValueError("bad-cb-sequence")
76 changes: 47 additions & 29 deletions src/btclib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,22 @@ def bytes_from_octets(octets: Octets, out_size: NoneOneOrMoreInt = None) -> byte
if size in sizes:
return octets

err_msg = f"invalid size: {size} bytes instead of {_message_text(out_size)}"
err_msg = f"invalid size: {size} bytes instead of {_sizes_text(sizes)}"
raise BTClibValueError(err_msg)


def _sizes_text(sizes: tuple[int, ...]) -> str:
"""Return the sizes octets were expected to have, for a refusal's message.

A size is the library's constant or the caller's `out_size`, and no
field of a format, so it is written in full only where it fits four
bytes, through `_message_field`, and described otherwise. One size
stands alone, any other count of them in parentheses.
"""
text = ", ".join(_message_field(size, 32, "d") for size in sizes)
return text if len(sizes) == 1 else f"({text})"


def str_from_string(s: String, what: str) -> str:
"""Return the text of a String, whether it came as text or as ascii bytes.

Expand Down Expand Up @@ -330,26 +342,52 @@ def assert_no_trailing(data: BinaryData, stream: BytesIO, what: str) -> None:
def _message_text(value: object) -> str:
"""Return the text of a value for a refusal's message, never raising.

`str()` of an int past `sys.get_int_max_str_digits()` digits, 4300 by
default, raises ValueError, and so does `str()` of what is written
with such an int, a Fraction for one; a `__str__` of the caller's own
can raise anything. A message quoting such a value would leave
An int, a bool excepted, is described by its sign and bit length and
never written out, in decimal or in hex: an argument in the wrong
place may be a key, and section 7 of the btclib-org standard, *A
refusal carries no secret*, lets a refusal print its length and not
its digits. `_message_field` is the exception, for a field the
format defines.

Anything else is quoted as `str()` writes it. `str()` of what is
written with an int past `sys.get_int_max_str_digits()` digits, a
Fraction for one, raises ValueError, and a `__str__` of the caller's
own can raise anything. A message quoting such a value would leave
through the refusal it was building, as that error rather than this
library's. So a value `str()` cannot write is described and not
quoted: an int by its sign and bit length, anything else by its type
library's. So a value `str()` cannot write is described by its type
name, never by its text.
"""
if isinstance(value, int) and not isinstance(value, bool):
return _int_description(value)
# every Exception and not only ValueError: what is caught is a
# failure to describe a value, and no failure of that kind may
# replace the refusal the description is for
try:
return str(value)
except Exception: # noqa: BLE001
if isinstance(value, int):
return _int_description(value)
return f"a {type(value).__name__} str() cannot write"


def _message_field(value: int, bits: int, spec: str) -> str:
"""Return a field's value for a refusal's message, never raising.

Section 7 of the btclib-org standard lets a refusal print a field
its format defines, of at most four bytes, where the value has the
length the format gives it and is one of the values the format
defines. A field every value of whose width is defined meets the
second condition wherever it meets the first, as a transaction's
lock time, version and sequence do: an int from 0 to `2**bits - 1`
is written with `format(value, spec)`, `"#x"` for hex. Any other
value is `_message_text`'s to write, since one wider than its field
may be a key passed in its place. A field whose width holds values
the format does not define is no field for this function.
"""
# int's own methods, for the reason _int_description gives
if is_integer(value) and not int.__lt__(value, 0) and int.bit_length(value) <= bits:
return int.__format__(value, spec)
return _message_text(value)


def _assert_valid_4_byte_field(name: str, value: int) -> None:
"""Refuse a value that cannot be written as four unsigned bytes.

Expand Down Expand Up @@ -405,26 +443,6 @@ def _int_description(value: int) -> str:
return f"{sign} int of {int.bit_length(value)} bits"


def _message_hex(value: object) -> str:
"""Return an int in hex for a refusal's message, never raising.

Hex has no digit limit, so `hex()` writes in kilobytes an int `str()`
refuses. Such an int is described as `_message_text` describes it
instead, so that one value reads the same way in every refusal, hex
or decimal. What is no int is `_message_text`'s to write.
"""
if not isinstance(value, int):
return _message_text(value)
# int's own repr and format, for the reason _int_description gives:
# the repr answers whether str() can write the value, raising
# ValueError exactly where str() of a plain int does
try:
int.__repr__(value)
except ValueError:
return _int_description(value)
return int.__format__(value, "#x")


def is_integer(value: Any) -> bool:
"""Return whether the value is an integer, a bool not being one.

Expand Down
3 changes: 1 addition & 2 deletions src/btclib/var_int.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from btclib.alias import BinaryData
from btclib.exceptions import BTClibTypeError, BTClibValueError
from btclib.utils import (
_message_hex,
_message_text,
bytesio_from_binarydata,
hex_string,
Expand Down Expand Up @@ -141,4 +140,4 @@ def serialize(i: int) -> bytes:
return b"\xfe" + i.to_bytes(4, byteorder="little", signed=False)
if i <= 0xFFFFFFFFFFFFFFFF: # 8 bytes
return b"\xff" + i.to_bytes(8, byteorder="little", signed=False)
raise BTClibValueError(f"integer too big for var_int encoding: {_message_hex(i)}")
raise BTClibValueError(f"integer too big for var_int encoding: {_message_text(i)}")
8 changes: 6 additions & 2 deletions tests/amount_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,9 +546,13 @@ def test_an_int_amount_in_range_still_reads() -> None:
"""The int bound runs ahead of `str()` and admits every int in range."""
assert valid_btc_amount(21_000_000) == 21_000_000
assert valid_btc_amount(0) == 0
with pytest.raises(BTClibValueError, match="invalid BTC amount: 21000001$"):
with pytest.raises(
BTClibValueError, match="invalid BTC amount: an int of 25 bits$"
):
valid_btc_amount(21_000_001)
with pytest.raises(BTClibValueError, match="invalid BTC amount: -1$"):
with pytest.raises(
BTClibValueError, match="invalid BTC amount: a negative int of 1 bits$"
):
valid_btc_amount(-1)


Expand Down
27 changes: 10 additions & 17 deletions tests/block/block_context_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ def test_a_context_is_a_height_and_an_instant() -> None:
BlockContext(height=0, now=now.replace(tzinfo=None))

# a height is a position in a chain: there is no negative one
with pytest.raises(BTClibValueError, match="invalid height: -1"):
with pytest.raises(
BTClibValueError, match="invalid height: a negative int of 1 bits"
):
BlockContext(height=-1, now=now)

# a float would compare fine and read as a height, so it is reported
Expand Down Expand Up @@ -127,7 +129,9 @@ def test_median_time_past_and_required_bits_default_to_none_and_are_skipped() ->

with pytest.raises(BTClibTypeError, match="invalid median_time_past type: str"):
BlockContext(height=0, now=now, median_time_past="0") # type: ignore[arg-type]
with pytest.raises(BTClibValueError, match="invalid median_time_past: -1"):
with pytest.raises(
BTClibValueError, match="invalid median_time_past: a negative int of 1 bits"
):
BlockContext(height=0, now=now, median_time_past=-1)

with pytest.raises(BTClibTypeError, match="invalid required_bits type: str"):
Expand Down Expand Up @@ -316,7 +320,7 @@ def test_time_too_old_compares_the_header_against_the_median_past() -> None:
time = int(block.header.time.timestamp())

# strictly after the median is required, so the median itself refuses
err_msg = f"invalid timestamp \\(not after the median past\\): {time} <= {time}"
err_msg = f"invalid timestamp \\(not after the median past\\): {time}$"
with pytest.raises(BTClibValueError, match=err_msg):
block.assert_valid_contextual(
BlockContext(height=1, now=now, median_time_past=time)
Expand All @@ -326,19 +330,6 @@ def test_time_too_old_compares_the_header_against_the_median_past() -> None:
)


def test_a_median_past_str_cannot_write_is_described() -> None:
"""The refusal names an int past the digit limit by its bit length.

`str()` refuses such an int with a ValueError of its own, which the
message quoting it would raise instead (issue #2394).
"""
block = block_of("block_1.bin")
context = BlockContext(height=1, now=block.header.time, median_time_past=10**5000)
err_msg = "not after the median past\\): .* <= an int of 16610 bits"
with pytest.raises(BTClibValueError, match=err_msg):
block.assert_valid_contextual(context)


def test_bad_diffbits_is_checked_before_time_too_old_and_time_too_new() -> None:
"""Core's own order: bad-diffbits, then time-too-old, then time-too-new.

Expand Down Expand Up @@ -550,7 +541,9 @@ def test_the_block_rules_can_be_asked_without_the_header_rules() -> None:

# the context is checked here too, before any rule reads it
unchecked = BlockContext(height=-1, now=now, check_validity=False)
with pytest.raises(BTClibValueError, match="invalid height: -1"):
with pytest.raises(
BTClibValueError, match="invalid height: a negative int of 1 bits"
):
block.assert_valid_contextual_block(unchecked)


Expand Down
6 changes: 4 additions & 2 deletions tests/block/block_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,12 @@ def test_exceptions() -> None:
# a strict comparison refuses the end itself, and one moved outward
# lets through a version the four bytes cannot hold
header.version = 0x7FFFFFFF + 1
with pytest.raises(BTClibValueError, match="invalid version: 0x80000000"):
with pytest.raises(BTClibValueError, match="invalid version: an int of 32 bits"):
header.assert_valid()
header.version = -0x80000000 - 1
with pytest.raises(BTClibValueError, match="invalid version: -0x80000001"):
with pytest.raises(
BTClibValueError, match="invalid version: a negative int of 32 bits"
):
header.assert_valid()
# refusing zero and below is Core's contextual bad-version, where an
# activation height sets a floor, not a range check (issue #2309):
Expand Down
Loading
Loading