Debian Codegraph @

bip32utils/BIP32Key.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/python3
2 #
3 # Copyright 2014 Corgan Labs
4 # See LICENSE.txt for distribution terms
5 #
6
7 import os
8 import hmac
9 import hashlib
10 import ecdsa
11 import struct
12 import codecs
13 from . import Base58
14
15 from hashlib import sha256
16 from ecdsa.curves import SECP256k1
17 from ecdsa.ecdsa import int_to_string, string_to_int
18 from ecdsa.numbertheory import square_root_mod_prime as sqrt_mod
19
20 MIN_ENTROPY_LEN = 128 # bits
21 BIP32_HARDEN = 0x80000000 # choose from hardened set of child keys
22 CURVE_GEN = ecdsa.ecdsa.generator_secp256k1
23 CURVE_ORDER = CURVE_GEN.order()
24 FIELD_ORDER = SECP256k1.curve.p()
25 INFINITY = ecdsa.ellipticcurve.INFINITY
26 EX_MAIN_PRIVATE = codecs.decode('0488ade4', 'hex') # Version string for mainnet extended private keys
27 EX_MAIN_PUBLIC = codecs.decode('0488b21e', 'hex') # Version string for mainnet extended public keys
28 EX_TEST_PRIVATE = codecs.decode('04358394', 'hex') # Version string for testnet extended private keys
29 EX_TEST_PUBLIC = codecs.decode('043587CF', 'hex') # Version string for testnet extended public keys
30
31 class BIP32Key(object):
32
33 # Static initializers to create from entropy or external formats
34 #
35 @staticmethod
36 def fromEntropy(entropy, public=False, testnet=False):
37 "Create a BIP32Key using supplied entropy >= MIN_ENTROPY_LEN"
38 if entropy == None:
39 entropy = os.urandom(MIN_ENTROPY_LEN/8) # Python doesn't have os.random()
40 if not len(entropy) >= MIN_ENTROPY_LEN/8:
41 raise ValueError("Initial entropy %i must be at least %i bits" %
42 (len(entropy), MIN_ENTROPY_LEN))
43 I = hmac.new(b"Bitcoin seed", entropy, hashlib.sha512).digest()
44 Il, Ir = I[:32], I[32:]
45 # FIXME test Il for 0 or less than SECP256k1 prime field order
46 key = BIP32Key(secret=Il, chain=Ir, depth=0, index=0, fpr=b'\0\0\0\0', public=False, testnet=testnet)
47 if public:
48 key.SetPublic()
49 return key
50
51 @staticmethod
52 def fromExtendedKey(xkey, public=False):
53 """
54 Create a BIP32Key by importing from extended private or public key string
55
56 If public is True, return a public-only key regardless of input type.
57 """
58 # Sanity checks
59 raw = Base58.check_decode(xkey)
60 if len(raw) != 78:
61 raise ValueError("extended key format wrong length")
62
63 # Verify address version/type
64 version = raw[:4]
65 if version == EX_MAIN_PRIVATE:
66 is_testnet = False
67 is_pubkey = False
68 elif version == EX_TEST_PRIVATE:
69 is_testnet = True
70 is_pubkey = False
71 elif version == EX_MAIN_PUBLIC:
72 is_testnet = False
73 is_pubkey = True
74 elif version == EX_TEST_PUBLIC:
75 is_testnet = True
76 is_pubkey = True
77 else:
78 raise ValueError("unknown extended key version")
79
80 # Extract remaining fields
81 # Python 2.x compatibility
82 if type(raw[4]) == int:
83 depth = raw[4]
84 else:
85 depth = ord(raw[4])
86 fpr = raw[5:9]
87 child = struct.unpack(">L", raw[9:13])[0]
88 chain = raw[13:45]
89 secret = raw[45:78]
90
91 # Extract private key or public key point
92 if not is_pubkey:
93 secret = secret[1:]
94 else:
95 # Recover public curve point from compressed key
96 # Python3 FIX
97 lsb = secret[0] & 1 if type(secret[0]) == int else ord(secret[0]) & 1
98 x = string_to_int(secret[1:])
99 ys = (x**3+7) % FIELD_ORDER # y^2 = x^3 + 7 mod p
100 y = sqrt_mod(ys, FIELD_ORDER)
101 if y & 1 != lsb:
102 y = FIELD_ORDER-y
103 point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y)
104 secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1)
105
106 key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=is_pubkey, testnet=is_testnet)
107 if not is_pubkey and public:
108 key = key.SetPublic()
109 return key
110
111
112 # Normal class initializer
113 def __init__(self, secret, chain, depth, index, fpr, public=False, testnet=False):
114 """
115 Create a public or private BIP32Key using key material and chain code.
116
117 secret This is the source material to generate the keypair, either a
118 32-byte string representation of a private key, or the ECDSA
119 library object representing a public key.
120
121 chain This is a 32-byte string representation of the chain code
122
123 depth Child depth; parent increments its own by one when assigning this
124
125 index Child index
126
127 fpr Parent fingerprint
128
129 public If true, this keypair will only contain a public key and can only create
130 a public key chain.
131 """
132
133 self.public = public
134 if public is False:
135 self.k = ecdsa.SigningKey.from_string(secret, curve=SECP256k1)
136 self.K = self.k.get_verifying_key()
137 else:
138 self.k = None
139 self.K = secret
140
141 self.C = chain
142 self.depth = depth
143 self.index = index
144 self.parent_fpr = fpr
145 self.testnet = testnet
146
147
148 # Internal methods not intended to be called externally
149 #
150 def hmac(self, data):
151 """
152 Calculate the HMAC-SHA512 of input data using the chain code as key.
153
154 Returns a tuple of the left and right halves of the HMAC
155 """
156 I = hmac.new(self.C, data, hashlib.sha512).digest()
157 return (I[:32], I[32:])
158
159
160 def CKDpriv(self, i):
161 """
162 Create a child key of index 'i'.
163
164 If the most significant bit of 'i' is set, then select from the
165 hardened key set, otherwise, select a regular child key.
166
167 Returns a BIP32Key constructed with the child key parameters,
168 or None if i index would result in an invalid key.
169 """
170 # Index as bytes, BE
171 i_str = struct.pack(">L", i)
172
173 # Data to HMAC
174 if i & BIP32_HARDEN:
175 data = b'\0' + self.k.to_string() + i_str
176 else:
177 data = self.PublicKey() + i_str
178 # Get HMAC of data
179 (Il, Ir) = self.hmac(data)
180
181 # Construct new key material from Il and current private key
182 Il_int = string_to_int(Il)
183 if Il_int > CURVE_ORDER:
184 return None
185 pvt_int = string_to_int(self.k.to_string())
186 k_int = (Il_int + pvt_int) % CURVE_ORDER
187 if (k_int == 0):
188 return None
189 secret = (b'\0'*32 + int_to_string(k_int))[-32:]
190
191 # Construct and return a new BIP32Key
192 return BIP32Key(secret=secret, chain=Ir, depth=self.depth+1, index=i, fpr=self.Fingerprint(), public=False, testnet=self.testnet)
193
194
195 def CKDpub(self, i):
196 """
197 Create a publicly derived child key of index 'i'.
198
199 If the most significant bit of 'i' is set, this is
200 an error.
201
202 Returns a BIP32Key constructed with the child key parameters,
203 or None if index would result in invalid key.
204 """
205
206 if i & BIP32_HARDEN:
207 raise Exception("Cannot create a hardened child key using public child derivation")
208
209 # Data to HMAC. Same as CKDpriv() for public child key.
210 data = self.PublicKey() + struct.pack(">L", i)
211
212 # Get HMAC of data
213 (Il, Ir) = self.hmac(data)
214
215 # Construct curve point Il*G+K
216 Il_int = string_to_int(Il)
217 if Il_int >= CURVE_ORDER:
218 return None
219 point = Il_int*CURVE_GEN + self.K.pubkey.point
220 if point == INFINITY:
221 return None
222
223 # Retrieve public key based on curve point
224 K_i = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1)
225
226 # Construct and return a new BIP32Key
227 return BIP32Key(secret=K_i, chain=Ir, depth=self.depth+1, index=i, fpr=self.Fingerprint(), public=True, testnet=self.testnet)
228
229
230 # Public methods
231 #
232 def ChildKey(self, i):
233 """
234 Create and return a child key of this one at index 'i'.
235
236 The index 'i' should be summed with BIP32_HARDEN to indicate
237 to use the private derivation algorithm.
238 """
239 if self.public is False:
240 return self.CKDpriv(i)
241 else:
242 return self.CKDpub(i)
243
244
245 def SetPublic(self):
246 "Convert a private BIP32Key into a public one"
247 self.k = None
248 self.public = True
249
250
251 def PrivateKey(self):
252 "Return private key as string"
253 if self.public:
254 raise Exception("Publicly derived deterministic keys have no private half")
255 else:
256 return self.k.to_string()
257
258
259 def PublicKey(self):
260 "Return compressed public key encoding"
261 padx = (b'\0'*32 + int_to_string(self.K.pubkey.point.x()))[-32:]
262 if self.K.pubkey.point.y() & 1:
263 ck = b'\3'+padx
264 else:
265 ck = b'\2'+padx
266 return ck
267
268
269 def ChainCode(self):
270 "Return chain code as string"
271 return self.C
272
273
274 def Identifier(self):
275 "Return key identifier as string"
276 cK = self.PublicKey()
277 return hashlib.new('ripemd160', sha256(cK).digest()).digest()
278
279
280 def Fingerprint(self):
281 "Return key fingerprint as string"
282 return self.Identifier()[:4]
283
284
285 def Address(self):
286 "Return compressed public key address"
287 addressversion = b'\x00' if not self.testnet else b'\x6f'
288 vh160 = addressversion + self.Identifier()
289 return Base58.check_encode(vh160)
290
291
292 def WalletImportFormat(self):
293 "Returns private key encoded for wallet import"
294 if self.public:
295 raise Exception("Publicly derived deterministic keys have no private half")
296 addressversion = b'\x80' if not self.testnet else b'\xef'
297 raw = addressversion + self.k.to_string() + b'\x01' # Always compressed
298 return Base58.check_encode(raw)
299
300
301 def ExtendedKey(self, private=True, encoded=True):
302 "Return extended private or public key as string, optionally Base58 encoded"
303 if self.public is True and private is True:
304 raise Exception("Cannot export an extended private key from a public-only deterministic key")
305 if not self.testnet:
306 version = EX_MAIN_PRIVATE if private else EX_MAIN_PUBLIC
307 else:
308 version = EX_TEST_PRIVATE if private else EX_TEST_PUBLIC
309 depth = bytes(bytearray([self.depth]))
310 fpr = self.parent_fpr
311 child = struct.pack('>L', self.index)
312 chain = self.C
313 if self.public is True or private is False:
314 data = self.PublicKey()
315 else:
316 data = b'\x00' + self.PrivateKey()
317 raw = version+depth+fpr+child+chain+data
318 if not encoded:
319 return raw
320 else:
321 return Base58.check_encode(raw)
322
323 # Debugging methods
324 #
325 def dump(self):
326 "Dump key fields mimicking the BIP0032 test vector format"
327 print(" * Identifier")
328 print(" * (hex): ", self.Identifier().encode('hex'))
329 print(" * (fpr): ", self.Fingerprint().encode('hex'))
330 print(" * (main addr):", self.Address())
331 if self.public is False:
332 print(" * Secret key")
333 print(" * (hex): ", self.PrivateKey().encode('hex'))
334 print(" * (wif): ", self.WalletImportFormat())
335 print(" * Public key")
336 print(" * (hex): ", self.PublicKey().encode('hex'))
337 print(" * Chain code")
338 print(" * (hex): ", self.C.encode('hex'))
339 print(" * Serialized")
340 print(" * (pub hex): ", self.ExtendedKey(private=False, encoded=False).encode('hex'))
341 print(" * (prv hex): ", self.ExtendedKey(private=True, encoded=False).encode('hex'))
342 print(" * (pub b58): ", self.ExtendedKey(private=False, encoded=True))
343 print(" * (prv b58): ", self.ExtendedKey(private=True, encoded=True))
344
345
346 if __name__ == "__main__":
347 import sys
348
349 # BIP0032 Test vector 1
350 entropy='000102030405060708090A0B0C0D0E0F'.decode('hex')
351 m = BIP32Key.fromEntropy(entropy)
352 print("Test vector 1:")
353 print("Master (hex):", entropy.encode('hex'))
354 print("* [Chain m]")
355 m.dump()
356
357 print("* [Chain m/0h]")
358 m = m.ChildKey(0+BIP32_HARDEN)
359 m.dump()
360
361 print("* [Chain m/0h/1]")
362 m = m.ChildKey(1)
363 m.dump()
364
365 print("* [Chain m/0h/1/2h]")
366 m = m.ChildKey(2+BIP32_HARDEN)
367 m.dump()
368
369 print("* [Chain m/0h/1/2h/2]")
370 m = m.ChildKey(2)
371 m.dump()
372
373 print("* [Chain m/0h/1/2h/2/1000000000]")
374 m = m.ChildKey(1000000000)
375 m.dump()
376
377 # BIP0032 Test vector 2
378 entropy = 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'.decode('hex')
379 m = BIP32Key.fromEntropy(entropy)
380 print("Test vector 2:")
381 print("Master (hex):", entropy.encode('hex'))
382 print("* [Chain m]")
383 m.dump()
384
385 print("* [Chain m/0]")
386 m = m.ChildKey(0)
387 m.dump()
388
389 print("* [Chain m/0/2147483647h]")
390 m = m.ChildKey(2147483647+BIP32_HARDEN)
391 m.dump()
392
393 print("* [Chain m/0/2147483647h/1]")
394 m = m.ChildKey(1)
395 m.dump()
396
397 print("* [Chain m/0/2147483647h/1/2147483646h]")
398 m = m.ChildKey(2147483646+BIP32_HARDEN)
399 m.dump()
400
401 print("* [Chain m/0/2147483647h/1/2147483646h/2]")
402 m = m.ChildKey(2)
403 m.dump()