3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 import hashlib, base64, ecdsa, re
24 return s.decode('hex')[::-1].encode('hex')
26 def int_to_hex(i, length=1):
27 s = hex(i)[2:].rstrip('L')
28 s = "0"*(2*length - len(s)) + s
32 # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
36 return "fd"+int_to_hex(i,2)
38 return "fe"+int_to_hex(i,4)
40 return "ff"+int_to_hex(i,8)
43 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
44 hash_encode = lambda x: x[::-1].encode('hex')
45 hash_decode = lambda x: x.decode('hex')[::-1]
48 # pywallet openssl private key implementation
50 def i2d_ECPrivateKey(pkey, compressed=False):
52 key = '3081d30201010420' + \
53 '%064x' % pkey.secret + \
54 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
56 '3006040100040107042102' + \
62 key = '308201130201010420' + \
63 '%064x' % pkey.secret + \
64 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
66 '3006040100040107044104' + \
73 return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
75 def i2o_ECPublicKey(pubkey, compressed=False):
76 # public keys are 65 bytes long (520 bits)
77 # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
78 # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
79 # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
81 if pubkey.point.y() & 1:
82 key = '03' + '%064x' % pubkey.point.x()
84 key = '02' + '%064x' % pubkey.point.x()
87 '%064x' % pubkey.point.x() + \
88 '%064x' % pubkey.point.y()
90 return key.decode('hex')
92 # end pywallet openssl private key implementation
96 ############ functions from pywallet #####################
98 def hash_160(public_key):
100 md = hashlib.new('ripemd160')
101 md.update(hashlib.sha256(public_key).digest())
105 md = ripemd.new(hashlib.sha256(public_key).digest())
109 def public_key_to_bc_address(public_key):
110 h160 = hash_160(public_key)
111 return hash_160_to_bc_address(h160)
113 def hash_160_to_bc_address(h160, addrtype = 0):
114 vh160 = chr(addrtype) + h160
116 addr = vh160 + h[0:4]
117 return b58encode(addr)
119 def bc_address_to_hash_160(addr):
120 bytes = b58decode(addr, 25)
121 return ord(bytes[0]), bytes[1:21]
123 def encode_point(pubkey, compressed=False):
124 order = generator_secp256k1.order()
125 p = pubkey.pubkey.point
126 x_str = ecdsa.util.number_to_string(p.x(), order)
127 y_str = ecdsa.util.number_to_string(p.y(), order)
129 return chr(2 + (p.y() & 1)) + x_str
131 return chr(4) + pubkey.to_string() #x_str + y_str
133 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
134 __b58base = len(__b58chars)
137 """ encode v, which is a string of bytes, to base58."""
140 for (i, c) in enumerate(v[::-1]):
141 long_value += (256**i) * ord(c)
144 while long_value >= __b58base:
145 div, mod = divmod(long_value, __b58base)
146 result = __b58chars[mod] + result
148 result = __b58chars[long_value] + result
150 # Bitcoin does a little leading-zero-compression:
151 # leading 0-bytes in the input become leading-1s
154 if c == '\0': nPad += 1
157 return (__b58chars[0]*nPad) + result
159 def b58decode(v, length):
160 """ decode v into a string of len bytes."""
162 for (i, c) in enumerate(v[::-1]):
163 long_value += __b58chars.find(c) * (__b58base**i)
166 while long_value >= 256:
167 div, mod = divmod(long_value, 256)
168 result = chr(mod) + result
170 result = chr(long_value) + result
174 if c == __b58chars[0]: nPad += 1
177 result = chr(0)*nPad + result
178 if length is not None and len(result) != length:
184 def EncodeBase58Check(vchIn):
186 return b58encode(vchIn + hash[0:4])
188 def DecodeBase58Check(psz):
189 vchRet = b58decode(psz, None)
199 def PrivKeyToSecret(privkey):
200 return privkey[9:9+32]
202 def SecretToASecret(secret, compressed=False, addrtype=0):
203 vchIn = chr((addrtype+128)&255) + secret
204 if compressed: vchIn += '\01'
205 return EncodeBase58Check(vchIn)
207 def ASecretToSecret(key, addrtype=0):
208 vch = DecodeBase58Check(key)
209 if vch and vch[0] == chr((addrtype+128)&255):
214 def regenerate_key(sec):
215 b = ASecretToSecret(sec)
219 secret = int('0x' + b.encode('hex'), 16)
220 return EC_KEY(secret)
222 def GetPubKey(pubkey, compressed=False):
223 return i2o_ECPublicKey(pubkey, compressed)
225 def GetPrivKey(pkey, compressed=False):
226 return i2d_ECPrivateKey(pkey, compressed)
229 return ('%064x' % pkey.secret).decode('hex')
231 def is_compressed(sec):
232 b = ASecretToSecret(sec)
235 ########### end pywallet functions #######################
237 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
238 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
239 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
240 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
241 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
242 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
243 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
244 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
245 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
246 oid_secp256k1 = (1,3,132,0,10)
247 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
249 class EC_KEY(object):
250 def __init__( self, secret ):
251 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
252 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
256 ###################################### BIP32 ##############################
258 def bip32_init(seed):
261 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
263 print "seed", seed.encode('hex')
264 master_secret = I[0:32]
265 master_chain = I[32:]
269 master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
270 master_public_key = master_private_key.get_verifying_key()
271 K = master_public_key.to_string()
272 K_compressed = GetPubKey(master_public_key.pubkey,True)
273 return master_secret, master_chain, K, K_compressed
278 from ecdsa.util import string_to_number, number_to_string
279 order = generator_secp256k1.order()
280 keypair = EC_KEY(string_to_number(k))
281 K = GetPubKey(keypair.pubkey,True)
282 I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
283 k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
288 def CKD_prime(K, c, n):
290 from ecdsa.util import string_to_number, number_to_string
291 order = generator_secp256k1.order()
293 K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
294 K_compressed = GetPubKey(K_public_key.pubkey,True)
296 I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
298 #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
299 public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
300 K_n = public_key.to_string()
301 K_n_compressed = GetPubKey(public_key.pubkey,True)
304 return K_n, K_n_compressed, c_n
310 ################################## transactions
314 out = re.sub('( [^\n]*|)\n','',s)
315 out = out.replace(' ','')
316 out = out.replace('\n','')
319 def raw_tx( inputs, outputs, for_sig = None ):
320 s = int_to_hex(1,4) # version
321 s += var_int( len(inputs) ) # number of inputs
322 for i in range(len(inputs)):
323 _, _, p_hash, p_index, p_script, pubkeysig = inputs[i]
324 s += p_hash.decode('hex')[::-1].encode('hex') # prev hash
325 s += int_to_hex(p_index,4) # prev index
328 if len(pubkeysig) == 1:
329 pubkey, sig = pubkeysig[0]
330 sig = sig + chr(1) # hashtype
331 script = int_to_hex( len(sig))
332 script += sig.encode('hex')
333 script += int_to_hex( len(pubkey))
334 script += pubkey.encode('hex')
336 pubkey0, sig0 = pubkeysig[0]
337 pubkey1, sig1 = pubkeysig[1]
340 inner_script = multisig_script([pubkey0, pubkey1])
342 script += int_to_hex(len(sig0))
343 script += sig0.encode('hex')
344 script += int_to_hex(len(sig1))
345 script += sig1.encode('hex')
346 script += var_int(len(inner_script)/2)
347 script += inner_script
350 if len(pubkeysig) > 1:
351 script = multisig_script(pubkeysig) # p2sh uses the inner script
353 script = p_script # scriptsig
356 s += var_int( len(tx_filter(script))/2 ) # script length
358 s += "ffffffff" # sequence
360 s += var_int( len(outputs) ) # number of outputs
361 for output in outputs:
362 addr, amount = output
363 s += int_to_hex( amount, 8) # amount
364 addrtype, hash_160 = bc_address_to_hash_160(addr)
366 script = '76a9' # op_dup, op_hash_160
367 script += '14' # push 0x14 bytes
368 script += hash_160.encode('hex')
369 script += '88ac' # op_equalverify, op_checksig
371 script = 'a9' # op_hash_160
372 script += '14' # push 0x14 bytes
373 script += hash_160.encode('hex')
374 script += '87' # op_equal
378 s += var_int( len(tx_filter(script))/2 ) # script length
380 s += int_to_hex(0,4) # lock time
381 if for_sig is not None: s += int_to_hex(1, 4) # hash type
385 def multisig_script(public_keys):
386 # supports only "2 of 2", and "2 of 3" transactions
389 for k in public_keys:
390 s += var_int(len(k)/2)
404 seed = "ff000000000000000000000000000000".decode('hex')
405 master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
407 print "secret key", master_secret.encode('hex')
408 print "chain code", master_chain.encode('hex')
410 key_id = hash_160(master_public_key_compressed)
411 print "keyid", key_id.encode('hex')
413 print "address", hash_160_to_bc_address(key_id)
414 print "secret key", SecretToASecret(master_secret, True)
417 k0, c0 = CKD(master_secret, master_chain, 0)
418 print "secret", k0.encode('hex')
419 print "chain", c0.encode('hex')
420 print "secret key", SecretToASecret(k0, True)
422 K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
423 print "address", hash_160_to_bc_address(hash_160(K0_compressed))
426 K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
427 print "address", hash_160_to_bc_address(hash_160(K01_compressed))
429 print "-- m/0/1/3 --"
430 K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
431 print "address", hash_160_to_bc_address(hash_160(K013_compressed))
433 print "-- m/0/1/3/7 --"
434 K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
435 print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
441 pubkeys = ["04e89a79651522201d756f14b1874ae49139cc984e5782afeca30ffe84e5e6b2cfadcfe9875c490c8a1a05a4debd715dd57471af8886ab5dfbb3959d97f087f77a",
442 "0455cf4a3ab68a011b18cb0a86aae2b8e9cad6c6355476de05247c57a9632d127084ac7630ad89893b43c486c5a9f7ec6158fb0feb708fa9255d5c4d44bc0858f8"]
443 s = multisig_script(pubkeys)
444 print "address", hash_160_to_bc_address(hash_160(s.decode('hex')), 5)
447 print "Gavin's tutorial: redeem p2sh: http://blockchain.info/tx-index/30888901"
448 pubkey1 = "0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"
449 pubkey2 = "04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"
450 pubkey3 = "048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"
451 pubkeys = [pubkey1, pubkey2, pubkey3]
453 tx_for_sig = raw_tx( [(None, None, '3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac', 0, 'a914f815b036d9bbbce5e9f2a00abd1bf3dc91e9551087', pubkeys)],
454 [('1GtpSrGhRGY5kkrNz4RykoqRQoJuG2L6DS',1000000)], for_sig = 0)
456 print "tx for sig", tx_for_sig
458 signature1 = "304502200187af928e9d155c4b1ac9c1c9118153239aba76774f775d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1bbdaaba4e50eb078f39e3d78"
459 signature2 = "30440220795f0f4f5941a77ae032ecb9e33753788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e27038e945bc9db59c732728a383a6f1ed2fb99da7a4"
461 for pubkey in pubkeys:
462 import traceback, sys
464 public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
467 public_key.verify_digest( signature1.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
469 except ecdsa.keys.BadSignatureError:
470 #traceback.print_exc(file=sys.stdout)
474 public_key.verify_digest( signature2.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
476 except ecdsa.keys.BadSignatureError:
477 #traceback.print_exc(file=sys.stdout)
480 if __name__ == '__main__':