aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorPieter Wuille <pieter.wuille@gmail.com>2020-03-18 00:33:43 -0700
committerPieter Wuille <pieter@wuille.net>2020-03-18 13:54:01 -0700
commita3ad6459b77e9b7156e486a9e4a37dbfdc35e324 (patch)
tree0220a1e462f4b9da0c3458433d58d24e2b8c4851 /test
parenta421e0a22f1230abd69b4661a019bed39b72205f (diff)
Simplify bn2vch using int.to_bytes
Diffstat (limited to 'test')
-rw-r--r--test/functional/test_framework/script.py40
1 files changed, 8 insertions, 32 deletions
diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py
index f14191fe51..92725dfcf4 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):