@@ -120,6 +120,26 @@ def deser_compact_size(f):
120
120
return nit
121
121
122
122
123
+ def ser_varint (l ):
124
+ r = b""
125
+ while True :
126
+ r = bytes ([(l & 0x7f ) | (0x80 if len (r ) > 0 else 0x00 )]) + r
127
+ if l <= 0x7f :
128
+ return r
129
+ l = (l >> 7 ) - 1
130
+
131
+
132
+ def deser_varint (f ):
133
+ n = 0
134
+ while True :
135
+ dat = f .read (1 )[0 ]
136
+ n = (n << 7 ) | (dat & 0x7f )
137
+ if (dat & 0x80 ) > 0 :
138
+ n += 1
139
+ else :
140
+ return n
141
+
142
+
123
143
def deser_string (f ):
124
144
nit = deser_compact_size (f )
125
145
return f .read (nit )
@@ -1913,3 +1933,20 @@ def check_addrv2(ip, net):
1913
1933
check_addrv2 ("2bqghnldu6mcug4pikzprwhtjjnsyederctvci6klcwzepnjd46ikjyd.onion" , CAddress .NET_TORV3 )
1914
1934
check_addrv2 ("255fhcp6ajvftnyo7bwz3an3t4a4brhopm3bamyh2iu5r3gnr2rq.b32.i2p" , CAddress .NET_I2P )
1915
1935
check_addrv2 ("fc32:17ea:e415:c3bf:9808:149d:b5a2:c9aa" , CAddress .NET_CJDNS )
1936
+
1937
+ def test_varint_encode_decode (self ):
1938
+ def check_varint (num , expected_encoding_hex ):
1939
+ expected_encoding = bytes .fromhex (expected_encoding_hex )
1940
+ self .assertEqual (ser_varint (num ), expected_encoding )
1941
+ self .assertEqual (deser_varint (BytesIO (expected_encoding )), num )
1942
+
1943
+ # test cases from serialize_tests.cpp:varint_bitpatterns
1944
+ check_varint (0 , "00" )
1945
+ check_varint (0x7f , "7f" )
1946
+ check_varint (0x80 , "8000" )
1947
+ check_varint (0x1234 , "a334" )
1948
+ check_varint (0xffff , "82fe7f" )
1949
+ check_varint (0x123456 , "c7e756" )
1950
+ check_varint (0x80123456 , "86ffc7e756" )
1951
+ check_varint (0xffffffff , "8efefefe7f" )
1952
+ check_varint (0xffffffffffffffff , "80fefefefefefefefe7f" )
0 commit comments