-
Notifications
You must be signed in to change notification settings - Fork 14
/
BitcoinAddress.py
348 lines (305 loc) · 11.7 KB
/
BitcoinAddress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from __future__ import print_function, division
import myecdsa
from hashing import *
import base58
import bech32
import re
import convert
import struct
import binascii
import hashlib
def byt(c):
return struct.pack("<B", c)
"""
By Willem Hengeveld <itsme@xs4all.nl>
Objects representing all bitcoin address releated information
note on uniqueness:
'small': less than: 2^256 - the group order 'n'
'small' priv keys can be represented as both 'x', and 'x+n'
pubkeys with 'small' x-coordinate can be represented both as:
(x,y) and (x+n,y)
both of which lead to different addresses.
"""
# the bitcoin wallet version.
wallet_version = 0x80
address_version = 0x00
B = myecdsa.secp256k1()
def setversions(aver, wver):
global address_version
global wallet_version
address_version= aver
wallet_version= wver
"""
represent hashed address
either from compressed or full pubkey
knows how to convert between hash and base58 representation
"""
class Address:
def __init__(self):
global address_version
self.hash= None
self.version= address_version # global
self.hrp = "bc" # 'human readable prefix'
@staticmethod
def fromhash(hash):
self= Address()
self.hash= hash
return self
@staticmethod
def frombase58(b58):
self= Address()
data= base58.decode(b58)
if len(data)>25:
print("addr len > 25: %s" % binascii.b2a_hex(data))
raise Exception("Invalid base58 length")
if len(data)<25:
data= "\x00" * (25-len(data))
self.version= ord(data[0:1])
self.hash= data[1:21]
if shasha(data[0:21])[:4] != data[21:]:
print("addr: %s: %s != %s" % (binascii.b2a_hex(data[:21]), binascii.b2a_hex(data[21:]), shasha(data[0:21])[:4]))
raise Exception("Invalid base58 checksum")
return self
@staticmethod
def frombech32(b32):
self = Address()
self.hrp, self.version, self.hash = bech32.decode(b32)
return self
def base58(self):
data= byt(self.version) + self.hash
data += shasha(data)[0:4]
return base58.encode(data)
def bech32(self):
return bech32.encode(self.hrp, self.version, self.hash)
def dump(self):
print("%-20s: %3d %-34s - %s" % (binascii.b2a_hex(self.hash).decode('ascii'), self.version, self.base58(), self.bech32()))
"""
represent the public key
knows how to encode/decode a pubkey into bytes
"""
class PublicKey:
def __init__(self):
self.point= None
def compressed(self):
if self.point is None or self.point.x is None or self.point.y is None:
return b"\x00" * 33
return struct.pack("<B", 2 + self.point.y.sqrtflag()) + convert.bytesfromnum(self.point.x)
def uncompressed(self):
if self.point is None or self.point.x is None or self.point.y is None:
return b"\x00" * 65
return struct.pack("<B", 4) + convert.bytesfromnum(self.point.x) + convert.bytesfromnum(self.point.y)
def dump(self):
print("%-20s: %s" % ("compressed", binascii.b2a_hex(self.compressed()).decode('ascii')))
print("%-20s: %s" % ("full", binascii.b2a_hex(self.uncompressed()).decode('ascii')))
@staticmethod
def frompubkey(key):
self= PublicKey()
if not key:
raise Exception("invalid point representation")
tag, = struct.unpack_from("<B", key, 0)
if len(key)==33 and (tag==2 or tag==3):
self.point= B.ec.decompress(convert.numfrombytes(key[1:]), tag-2)
elif len(key)==65 and tag==4:
self.point= B.ec.point(convert.numfrombytes(key[1:33]), convert.numfrombytes(key[33:65]))
else:
print(binascii.b2a_hex(key))
raise Exception("invalid point representation")
return self
@staticmethod
def frompoint(pt):
self= PublicKey()
self.point= pt
return self
"""
represent the private part of the bitcoin address
knows how to convert between wallet and privkey,
can be initialized from minikey.
"""
class PrivateKey:
def __init__(self):
global wallet_version
self.privkey= None
self.minikey= None
self.version= wallet_version # global
self.compressed= None
@staticmethod
def fromwallet(b58):
self= PrivateKey()
data= base58.decode(b58)
if not len(data) in (37, 38):
print("wallet len != 37/38: %s" % binascii.b2a_hex(data))
raise Exception("Invalid wallet length")
self.version= ord(data[0:1])
self.privkey= convert.numfrombytes(data[1:33])
if len(data)==38:
# a compressed walled has:
# <wallet-tag> <32-byte-privkey> <01> <4-byte-hash>
self.compressed= ord(data[33:34])
if shasha(data[:-4])[:4] != data[-4:]:
print("wallet: %s: %s != %s" % (binascii.b2a_hex(data[:33]), binascii.b2a_hex(data[33:]), shasha(data[0:33])[:4]))
raise Exception("Invalid base58 checksum")
return self
@staticmethod
def fromminikey(key):
if type(key)==str:
key = key.encode('utf-8')
self= PrivateKey()
self.privkey= convert.numfrombytes(sha256(key))
return self
@staticmethod
def fromprivkey(key):
self= PrivateKey()
self.privkey= convert.numfrombytes(key)
return self
def publickey(self):
return PublicKey.frompoint(B.calcpub(self.privkey))
def wallet(self):
data= byt(self.version)+convert.bytesfromnum(self.privkey)
data += shasha(data)[:4]
return base58.encode(data)
def compwallet(self):
""" bip0178 wallet indicating a compressed pubkey """
data= byt(self.version)+convert.bytesfromnum(self.privkey) + byt(1)
data += shasha(data)[:4]
return base58.encode(data)
def dump(self):
if self.minikey: print("%-20s: %s" % ("minikey", self.minikey))
print("%-20s: %064x" % ("privkey", self.privkey))
print("%-20s: %s" % ("wallet", self.wallet()))
print("%-20s: %s" % ("cwallet", self.compwallet()))
if self.version is not None and self.compressed is not None:
print("version: %d compressed: %d" % (self.version, self.compressed))
elif self.compressed is not None:
print("compressed: %d" % self.compressed)
elif self.version is not None:
print("version: %d" % self.version)
class WSH:
@staticmethod
def frompubkey(pubkey):
o = WSH()
o.script = struct.pack("<BB33sBB", 0x51, 0x21, pubkey, 0x51, 0xae)
o.hash = sha256(o.script)
o.version = 0
o.hrp = "bc"
return o
def bech32(self):
return bech32.encode(self.hrp, self.version, self.hash)
def dump(self):
print("%-32s: - %s" % (binascii.b2a_hex(self.hash).decode('ascii'), self.bech32()))
"""
represent all components of a bitcoin address combined
"""
class BitcoinAddress:
def __init__(self, arg):
if isinstance(arg, PrivateKey):
self.privkey= arg
elif isinstance(arg, PublicKey):
self.privkey= None
self.pubkey= arg
elif isinstance(arg, Address):
self.privkey= None
self.pubkey= None
self.compaddr = self.fulladdr = arg
else:
self.privkey= None
self.pubkey= None
self.compaddr = self.fulladdr = None
self.p2sh = None
self.p2shfull = None
if self.privkey:
self.pubkey= self.privkey.publickey()
if self.pubkey:
self.compaddr= Address.fromhash(sharip(self.pubkey.compressed()))
self.fulladdr= Address.fromhash(sharip(self.pubkey.uncompressed()))
if self.privkey and self.privkey.version:
# most coins have walletversion = 128 + addressversion
if self.privkey.version >= 128:
self.compaddr.version= self.privkey.version-128
self.fulladdr.version= self.privkey.version-128
else:
print("WARNING: privkey has invalid version: 0x%02x, should be >= 0x80" % self.privkey.version)
self.compaddr.version= self.privkey.version
self.fulladdr.version= self.privkey.version
if self.compaddr:
self.p2sh = Address.fromhash(sharip(struct.pack(">H", len(self.compaddr.hash))+self.compaddr.hash))
self.p2sh.version = 5
if self.fulladdr:
self.p2shfull = Address.fromhash(sharip(struct.pack(">H", len(self.fulladdr.hash))+self.fulladdr.hash))
self.p2shfull.version = 5
self.p2wsh = None
if self.pubkey:
self.p2wsh = WSH.frompubkey(self.pubkey.compressed())
@staticmethod
def from_privkey(arg):
if type(arg)==str: arg = binascii.a2b_hex(arg)
return BitcoinAddress(PrivateKey.fromprivkey(arg))
@staticmethod
def from_wallet(arg):
return BitcoinAddress(PrivateKey.fromwallet(arg))
@staticmethod
def from_minikey(arg):
return BitcoinAddress(PrivateKey.fromminikey(arg))
@staticmethod
def from_pubkey(arg):
return BitcoinAddress(PublicKey.frompubkey(binascii.a2b_hex(arg)))
@staticmethod
def from_hash(arg):
return BitcoinAddress(Address.fromhash(binascii.a2b_hex(arg)))
@staticmethod
def from_base58(arg):
return BitcoinAddress(Address.frombase58(arg))
@staticmethod
def from_bech32(arg):
return BitcoinAddress(Address.frombech32(arg))
@staticmethod
def from_auto(arg):
ishex= re.match(r'[0-9a-fA-F]+$', arg)
isb58= re.match('['+base58.charset+']+$', arg)
isb32= re.match('(?:\w+1)?['+bech32.alphabet+']+$', arg)
if len(arg)==51 and arg[0]=='5' and 'H' <= arg[1] <= 'K' and isb58:
# a wallet private key
return BitcoinAddress(PrivateKey.fromwallet(arg))
if len(arg)==52 and "Kw" <= arg[:2] <='L5' and isb58:
# a wallet private key
return BitcoinAddress(PrivateKey.fromwallet(arg))
elif 31<=len(arg)<=34 and arg[0]=='1' and isb58:
# a 'p2pkh' address
return BitcoinAddress(Address.frombase58(arg))
elif 31<=len(arg)<=34 and arg[0]=='3' and isb58:
# a 'p2sh' address
return BitcoinAddress(Address.frombase58(arg))
elif len(arg)==42 and isb32:
# a 'p2wpkh' address
return BitcoinAddress(Address.frombech32(arg))
elif len(arg)==62 and isb32:
# a 'p2wsh' address
return BitcoinAddress(Address.frombech32(arg))
elif len(arg)==130 and arg[:2]=='04' and ishex:
# a full public key
return BitcoinAddress(PublicKey.frompubkey(binascii.a2b_hex(arg)))
elif len(arg)==66 and arg[0]=='0' and arg[1] in ('2','3') and ishex:
# a compressed public key
return BitcoinAddress(PublicKey.frompubkey(binascii.a2b_hex(arg)))
elif len(arg)==64 and ishex:
# a hex private key
return BitcoinAddress(PrivateKey.fromprivkey(binascii.a2b_hex(arg)))
else:
print("unknown string: %s" % arg)
def dump(self):
if self.privkey: self.privkey.dump()
if self.pubkey: self.pubkey.dump()
if self.fulladdr==self.compaddr:
if self.compaddr:
self.compaddr.dump()
else:
print("comp:", end=" ")
self.compaddr.dump()
print("full:", end=" ")
self.fulladdr.dump()
print("p2sh:", end=" ")
self.p2sh.dump()
print("p2sh(full):", end=" ")
self.p2shfull.dump()
if self.p2wsh:
print("p2wsh:", end=" ")
self.p2wsh.dump()