Skip to content

Commit a3ad645

Browse files
committed
Simplify bn2vch using int.to_bytes
1 parent a421e0a commit a3ad645

File tree

1 file changed

+8
-32
lines changed

1 file changed

+8
-32
lines changed

test/functional/test_framework/script.py

Lines changed: 8 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -27,38 +27,14 @@ def hash160(s):
2727

2828
def bn2vch(v):
2929
"""Convert number to bitcoin-specific little endian format."""
30-
# The top bit is used to indicate the sign of the number. If there
31-
# isn't a spare bit in the bit length, add an extension byte.
32-
have_ext = False
33-
ext = bytearray()
34-
if v.bit_length() > 0:
35-
have_ext = (v.bit_length() & 0x07) == 0
36-
ext.append(0)
37-
38-
# Is the number negative?
39-
neg = False
40-
if v < 0:
41-
neg = True
42-
v = -v
43-
44-
# Convert the int to bytes
45-
v_bin = bytearray()
46-
bytes_len = (v.bit_length() + 7) // 8
47-
for i in range(bytes_len, 0, -1):
48-
v_bin.append((v >> ((i - 1) * 8)) & 0xff)
49-
50-
# Add the sign bit if necessary
51-
if neg:
52-
if have_ext:
53-
ext[0] |= 0x80
54-
else:
55-
v_bin[0] |= 0x80
56-
57-
v_bytes = ext + v_bin
58-
# Reverse bytes ordering for LE
59-
v_bytes.reverse()
60-
61-
return bytes(v_bytes)
30+
# We need v.bit_length() bits, plus a sign bit for every nonzero number.
31+
n_bits = v.bit_length() + (v != 0)
32+
# The number of bytes for that is:
33+
n_bytes = (n_bits + 7) // 8
34+
# Convert number to absolute value + sign in top bit.
35+
encoded_v = 0 if v == 0 else abs(v) | ((v < 0) << (n_bytes * 8 - 1))
36+
# Serialize to bytes
37+
return encoded_v.to_bytes(n_bytes, 'little')
6238

6339
_opcode_instances = []
6440
class CScriptOp(int):

0 commit comments

Comments
 (0)