Skip to content

Commit 96bf0bc

Browse files
committed
test: simplify uint256 (de)serialization routines
These routines look fancy, but do nothing more than converting between byte objects of length 32 to/from integers in little endian byte order and can be replaced by simple one-liners, using the int.{from,to}_bytes methods (available since Python 3.2).
1 parent 49d07ea commit 96bf0bc

File tree

1 file changed

+7
-15
lines changed

1 file changed

+7
-15
lines changed

test/functional/test_framework/messages.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ def ser_compact_size(l):
9393
r = struct.pack("<BQ", 255, l)
9494
return r
9595

96+
9697
def deser_compact_size(f):
9798
nit = struct.unpack("<B", f.read(1))[0]
9899
if nit == 253:
@@ -103,35 +104,26 @@ def deser_compact_size(f):
103104
nit = struct.unpack("<Q", f.read(8))[0]
104105
return nit
105106

107+
106108
def deser_string(f):
107109
nit = deser_compact_size(f)
108110
return f.read(nit)
109111

112+
110113
def ser_string(s):
111114
return ser_compact_size(len(s)) + s
112115

116+
113117
def deser_uint256(f):
114-
r = 0
115-
for i in range(8):
116-
t = struct.unpack("<I", f.read(4))[0]
117-
r += t << (i * 32)
118-
return r
118+
return int.from_bytes(f.read(32), 'little')
119119

120120

121121
def ser_uint256(u):
122-
rs = b""
123-
for _ in range(8):
124-
rs += struct.pack("<I", u & 0xFFFFFFFF)
125-
u >>= 32
126-
return rs
122+
return u.to_bytes(32, 'little')
127123

128124

129125
def uint256_from_str(s):
130-
r = 0
131-
t = struct.unpack("<IIIIIIII", s[:32])
132-
for i in range(8):
133-
r += t[i] << (i * 32)
134-
return r
126+
return int.from_bytes(s[:32], 'little')
135127

136128

137129
def uint256_from_compact(c):

0 commit comments

Comments
 (0)