From a3ad6459b77e9b7156e486a9e4a37dbfdc35e324 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Wed, 18 Mar 2020 00:33:43 -0700 Subject: [PATCH] Simplify bn2vch using int.to_bytes --- test/functional/test_framework/script.py | 40 +++++------------------- 1 file changed, 8 insertions(+), 32 deletions(-) diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py index f14191fe510..92725dfcf45 100644 --- a/test/functional/test_framework/script.py +++ b/test/functional/test_framework/script.py @@ -27,38 +27,14 @@ def hash160(s): def bn2vch(v): """Convert number to bitcoin-specific little endian format.""" - # The top bit is used to indicate the sign of the number. If there - # isn't a spare bit in the bit length, add an extension byte. - have_ext = False - ext = bytearray() - if v.bit_length() > 0: - have_ext = (v.bit_length() & 0x07) == 0 - ext.append(0) - - # Is the number negative? - neg = False - if v < 0: - neg = True - v = -v - - # Convert the int to bytes - v_bin = bytearray() - bytes_len = (v.bit_length() + 7) // 8 - for i in range(bytes_len, 0, -1): - v_bin.append((v >> ((i - 1) * 8)) & 0xff) - - # Add the sign bit if necessary - if neg: - if have_ext: - ext[0] |= 0x80 - else: - v_bin[0] |= 0x80 - - v_bytes = ext + v_bin - # Reverse bytes ordering for LE - v_bytes.reverse() - - return bytes(v_bytes) + # We need v.bit_length() bits, plus a sign bit for every nonzero number. + n_bits = v.bit_length() + (v != 0) + # The number of bytes for that is: + n_bytes = (n_bits + 7) // 8 + # Convert number to absolute value + sign in top bit. + encoded_v = 0 if v == 0 else abs(v) | ((v < 0) << (n_bytes * 8 - 1)) + # Serialize to bytes + return encoded_v.to_bytes(n_bytes, 'little') _opcode_instances = [] class CScriptOp(int):