Skip to content

Commit

Permalink
Simplify bn2vch using int.to_bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
sipa committed Mar 18, 2020
1 parent a421e0a commit a3ad645
Showing 1 changed file with 8 additions and 32 deletions.
40 changes: 8 additions & 32 deletions test/functional/test_framework/script.py
Expand Up @@ -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):
Expand Down

0 comments on commit a3ad645

Please sign in to comment.