Merge bitcoin/bitcoin#24576: contrib: testgen: remove redundant base58 implementation

65c49ac750 test: throw `ValueError` for invalid base58 checksum (Sebastian Falbesoner)
219d2c7ee1 contrib: testgen: use base58 methods from test framework (Sebastian Falbesoner)
605fecfb66 scripted-diff: rename `chars` to `b58chars` in test_framework.address (Sebastian Falbesoner)
11c63e374d contrib: testgen: import OP_* constants from test framework (Sebastian Falbesoner)
7d755bb31c contrib: testgen: avoid need for manually setting PYTHONPATH (Sebastian Falbesoner)

Pull request description:

  This PR removes the redundant base58 implementation [contrib/testgen/base58.py](https://github.com/bitcoin/bitcoin/blob/master/contrib/testgen/base58.py) for the test generation script `gen_key_io_test_vectors.py` and uses the one from the test framework instead. Additionally, three other cleanups/improvements are done:
  - import script operator constants `OP_*` from test framework instead of manually defining them
  - add Python path to test framework directly in the script (via `sys.path.append(...)`) instead of needing the caller to specify `PYTHONPATH=...` on the command line (the same approach is done for the signet miner and the message capture scripts)
  - rename `chars` to `b58chars` in the test_framework.address module (is more explicit and makes the diff for the base58 replacement smaller)

ACKs for top commit:
  laanwj:
    Code review ACK 65c49ac750

Tree-SHA512: 92e1534cc320cd56262bf455de7231c6ec821bfcd0ed58aa5718271ecec1a89df7951bf31527a2306db6398e7f2664d2ff8508200c28163c0b164d3f5aaf8b0e
This commit is contained in:
fanquake
2022-04-06 14:02:46 +01:00
4 changed files with 30 additions and 148 deletions

View File

@@ -35,7 +35,7 @@ class AddressType(enum.Enum):
legacy = 'legacy' # P2PKH
chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def create_deterministic_address_bcrt1_p2tr_op_true():
@@ -59,10 +59,10 @@ def byte_to_base58(b, version):
b += hash256(b)[:4] # append checksum
value = int.from_bytes(b, 'big')
while value > 0:
result = chars[value % 58] + result
result = b58chars[value % 58] + result
value //= 58
while b[0] == 0:
result = chars[0] + result
result = b58chars[0] + result
b = b[1:]
return result
@@ -76,8 +76,8 @@ def base58_to_byte(s):
n = 0
for c in s:
n *= 58
assert c in chars
digit = chars.index(c)
assert c in b58chars
digit = b58chars.index(c)
n += digit
h = '%x' % n
if len(h) % 2:
@@ -85,14 +85,14 @@ def base58_to_byte(s):
res = n.to_bytes((n.bit_length() + 7) // 8, 'big')
pad = 0
for c in s:
if c == chars[0]:
if c == b58chars[0]:
pad += 1
else:
break
res = b'\x00' * pad + res
# Assert if the checksum is invalid
assert_equal(hash256(res[:-4])[:4], res[-4:])
if hash256(res[:-4])[:4] != res[-4:]:
raise ValueError('Invalid Base58Check checksum')
return res[1:-4], int(res[0])