Remove unused Python imports
[bitcoinplatinum.git] / test / functional / test_framework / bignum.py
blobdb5ccd62c2c02d9eac01ba1d50483804043e62c9
1 #!/usr/bin/env python3
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """Big number routines.
7 This file is copied from python-bitcoinlib.
8 """
10 import struct
13 # generic big endian MPI format
15 def bn_bytes(v, have_ext=False):
16 ext = 0
17 if have_ext:
18 ext = 1
19 return ((v.bit_length()+7)//8) + ext
21 def bn2bin(v):
22 s = bytearray()
23 i = bn_bytes(v)
24 while i > 0:
25 s.append((v >> ((i-1) * 8)) & 0xff)
26 i -= 1
27 return s
29 def bn2mpi(v):
30 have_ext = False
31 if v.bit_length() > 0:
32 have_ext = (v.bit_length() & 0x07) == 0
34 neg = False
35 if v < 0:
36 neg = True
37 v = -v
39 s = struct.pack(b">I", bn_bytes(v, have_ext))
40 ext = bytearray()
41 if have_ext:
42 ext.append(0)
43 v_bin = bn2bin(v)
44 if neg:
45 if have_ext:
46 ext[0] |= 0x80
47 else:
48 v_bin[0] |= 0x80
49 return s + ext + v_bin
51 # bitcoin-specific little endian format, with implicit size
52 def mpi2vch(s):
53 r = s[4:] # strip size
54 r = r[::-1] # reverse string, converting BE->LE
55 return r
57 def bn2vch(v):
58 return bytes(mpi2vch(bn2mpi(v)))