Skip to content

Commit

Permalink
improved error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
fametrano committed May 28, 2020
1 parent 39a086e commit c4c55c3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 6 additions & 2 deletions btclib/base58.py
Expand Up @@ -121,8 +121,12 @@ def b58decode(v: String, out_size: Optional[int] = None) -> bytes:
v = v.encode("ascii")

result = _b58decode(v)
result, checksum = result[:-4], result[-4:]
if len(result) < 4:
m = "not enough bytes for checksum, "
m += f"invalid base58 decoded size: {len(result)}"
raise ValueError(m)

result, checksum = result[:-4], result[-4:]
h256 = hash256(result)
if checksum != h256[:4]:
m = f"invalid checksum: 0x{checksum.hex()} instead of 0x{h256[:4].hex()}"
Expand All @@ -131,6 +135,6 @@ def b58decode(v: String, out_size: Optional[int] = None) -> bytes:
if out_size is None or len(result) == out_size:
return result

m = "Invalid base58 decoded size: "
m = "valid checksum, invalid decoded size: "
m += f"{len(result)} bytes instead of {out_size}"
raise ValueError(m)
14 changes: 12 additions & 2 deletions btclib/tests/test_base58.py
Expand Up @@ -25,20 +25,26 @@ def test_empty():
assert _b58encode(b"") == b""
assert _b58decode(_b58encode(b"")) == b""

assert b58decode(b58encode(b""), 0) == b""


def test_hello_world():
assert _b58encode(b"hello world") == b"StV1DL6CwTryKyV"
assert _b58decode(b"StV1DL6CwTryKyV") == b"hello world"
assert _b58decode(_b58encode(b"hello world")) == b"hello world"
assert _b58encode(_b58decode(b"StV1DL6CwTryKyV")) == b"StV1DL6CwTryKyV"

assert b58decode(b58encode(b"hello world"), 11) == b"hello world"


def test_trailing_zeros():
assert _b58encode(b"\x00\x00hello world") == b"11StV1DL6CwTryKyV"
assert _b58decode(b"11StV1DL6CwTryKyV") == b"\x00\x00hello world"
assert _b58decode(_b58encode(b"\0\0hello world")) == b"\x00\x00hello world"
assert _b58decode(_b58encode(b"\x00\x00hello world")) == b"\x00\x00hello world"
assert _b58encode(_b58decode(b"11StV1DL6CwTryKyV")) == b"11StV1DL6CwTryKyV"

assert b58decode(b58encode(b"\x00\x00hello world")) == b"\x00\x00hello world"


def test_exceptions():

Expand All @@ -48,7 +54,7 @@ def test_exceptions():
encoded = b58encode(b"test")

wrong_length = len(encoded) - 1
with pytest.raises(ValueError, match="Invalid base58 decoded size: "):
with pytest.raises(ValueError, match="invalid decoded size: "):
b58decode(encoded, wrong_length)

invalidChecksum = encoded[:-4] + b"1111"
Expand All @@ -58,6 +64,10 @@ def test_exceptions():
with pytest.raises(ValueError, match="'ascii' codec can't encode character "):
b58decode("hèllo world")

err_msg = "not enough bytes for checksum, invalid base58 decoded size: "
with pytest.raises(ValueError, match=err_msg):
b58decode(_b58encode(b"123"))


def test_wif():
# https://en.bitcoin.it/wiki/Wallet_import_format
Expand Down

0 comments on commit c4c55c3

Please sign in to comment.