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)
236 def address_from_private_key(sec):
237 # rebuild public key from private key, compressed or uncompressed
238 pkey = regenerate_key(sec)
241 # figure out if private key is compressed
242 compressed = is_compressed(sec)
244 # rebuild private and public key from regenerated secret
245 private_key = GetPrivKey(pkey, compressed)
246 public_key = GetPubKey(pkey.pubkey, compressed)
247 address = public_key_to_bc_address(public_key)
251 ########### end pywallet functions #######################
253 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
254 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
255 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
256 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
257 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
258 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
259 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
260 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
261 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
262 oid_secp256k1 = (1,3,132,0,10)
263 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
265 class EC_KEY(object):
266 def __init__( self, secret ):
267 self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
268 self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
272 ###################################### BIP32 ##############################
274 def bip32_init(seed):
277 I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
279 print "seed", seed.encode('hex')
280 master_secret = I[0:32]
281 master_chain = I[32:]
285 master_private_key = ecdsa.SigningKey.from_string( master_secret, curve = SECP256k1 )
286 master_public_key = master_private_key.get_verifying_key()
287 K = master_public_key.to_string()
288 K_compressed = GetPubKey(master_public_key.pubkey,True)
289 return master_secret, master_chain, K, K_compressed
294 from ecdsa.util import string_to_number, number_to_string
295 order = generator_secp256k1.order()
296 keypair = EC_KEY(string_to_number(k))
297 K = GetPubKey(keypair.pubkey,True)
298 I = hmac.new(c, K + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
299 k_n = number_to_string( (string_to_number(I[0:32]) * string_to_number(k)) % order , order )
304 def CKD_prime(K, c, n):
306 from ecdsa.util import string_to_number, number_to_string
307 order = generator_secp256k1.order()
309 K_public_key = ecdsa.VerifyingKey.from_string( K, curve = SECP256k1 )
310 K_compressed = GetPubKey(K_public_key.pubkey,True)
312 I = hmac.new(c, K_compressed + rev_hex(int_to_hex(n,4)).decode('hex'), hashlib.sha512).digest()
314 #pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, string_to_number(I[0:32]) * K_public_key.pubkey.point )
315 public_key = ecdsa.VerifyingKey.from_public_point( string_to_number(I[0:32]) * K_public_key.pubkey.point, curve = SECP256k1 )
316 K_n = public_key.to_string()
317 K_n_compressed = GetPubKey(public_key.pubkey,True)
320 return K_n, K_n_compressed, c_n
326 ################################## transactions
330 out = re.sub('( [^\n]*|)\n','',s)
331 out = out.replace(' ','')
332 out = out.replace('\n','')
335 def raw_tx( inputs, outputs, for_sig = None ):
337 s = int_to_hex(1,4) # version
338 s += var_int( len(inputs) ) # number of inputs
339 for i in range(len(inputs)):
341 s += txin['tx_hash'].decode('hex')[::-1].encode('hex') # prev hash
342 s += int_to_hex(txin['index'],4) # prev index
345 pubkeysig = txin['pubkeysig']
346 if len(pubkeysig) == 1:
347 pubkey, sig = pubkeysig[0]
348 sig = sig + chr(1) # hashtype
349 script = int_to_hex( len(sig))
350 script += sig.encode('hex')
351 script += int_to_hex( len(pubkey))
352 script += pubkey.encode('hex')
354 n = txin['multisig_num']
355 pubkeys = map(lambda x:x[0], pubkeysig)
357 for item in pubkeysig:
360 script += int_to_hex(len(sig))
361 script += sig.encode('hex')
362 inner_script = multisig_script(pubkeys)
363 script += var_int(len(inner_script)/2)
364 script += inner_script
367 pubkeys = txin.get('pubkeys')
369 num = txin['p2sh_num']
370 script = multisig_script(pubkeys, num) # p2sh uses the inner script
372 script = txin['raw_output_script'] # scriptsig
375 s += var_int( len(tx_filter(script))/2 ) # script length
377 s += "ffffffff" # sequence
379 s += var_int( len(outputs) ) # number of outputs
380 for output in outputs:
381 addr, amount = output
382 s += int_to_hex( amount, 8) # amount
383 addrtype, hash_160 = bc_address_to_hash_160(addr)
385 script = '76a9' # op_dup, op_hash_160
386 script += '14' # push 0x14 bytes
387 script += hash_160.encode('hex')
388 script += '88ac' # op_equalverify, op_checksig
390 script = 'a9' # op_hash_160
391 script += '14' # push 0x14 bytes
392 script += hash_160.encode('hex')
393 script += '87' # op_equal
397 s += var_int( len(tx_filter(script))/2 ) # script length
399 s += int_to_hex(0,4) # lock time
400 if for_sig is not None and for_sig != 1: s += int_to_hex(1, 4) # hash type
406 def multisig_script(public_keys, num=None):
407 # supports only "2 of 2", and "2 of 3" transactions
413 assert num <= n and n <= 3 and n >= 2
422 for k in public_keys:
423 s += var_int(len(k)/2)
438 def __init__(self, raw):
441 self.inputs = self.d['inputs']
442 self.outputs = self.d['outputs']
443 self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
446 def from_io(klass, inputs, outputs):
447 raw = raw_tx(inputs, outputs, for_sig = -1) # for_sig=-1 means do not sign
450 self.outputs = outputs
457 return raw_tx(self.inputs, self.outputs, for_sig = i)
460 return Hash(self.raw.decode('hex') )[::-1].encode('hex')
462 def sign(self, private_keys):
464 for i in range(len(self.inputs)):
465 txin = self.inputs[i]
466 sec = private_keys[txin['address']]
467 compressed = is_compressed(sec)
468 pkey = regenerate_key(sec)
471 private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
472 public_key = private_key.get_verifying_key()
473 pkey = EC_KEY(secexp)
474 pubkey = GetPubKey(pkey.pubkey, compressed)
475 tx = raw_tx( self.inputs, self.outputs, for_sig = i )
476 sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der )
477 assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
478 self.inputs[i]["pubkeysig"] = [(pubkey, sig)]
480 self.raw = raw_tx( self.inputs, self.outputs )
483 def deserialize(self):
485 vds = deserialize.BCDataStream()
486 vds.write(self.raw.decode('hex'))
487 self.d = deserialize.parse_Transaction(vds)
494 seed = "ff000000000000000000000000000000".decode('hex')
495 master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed)
497 print "secret key", master_secret.encode('hex')
498 print "chain code", master_chain.encode('hex')
500 key_id = hash_160(master_public_key_compressed)
501 print "keyid", key_id.encode('hex')
503 print "address", hash_160_to_bc_address(key_id)
504 print "secret key", SecretToASecret(master_secret, True)
507 k0, c0 = CKD(master_secret, master_chain, 0)
508 print "secret", k0.encode('hex')
509 print "chain", c0.encode('hex')
510 print "secret key", SecretToASecret(k0, True)
512 K0, K0_compressed, c0 = CKD_prime(master_public_key, master_chain, 0)
513 print "address", hash_160_to_bc_address(hash_160(K0_compressed))
516 K01, K01_compressed, c01 = CKD_prime(K0, c0, 1)
517 print "address", hash_160_to_bc_address(hash_160(K01_compressed))
519 print "-- m/0/1/3 --"
520 K013, K013_compressed, c013 = CKD_prime(K01, c01, 3)
521 print "address", hash_160_to_bc_address(hash_160(K013_compressed))
523 print "-- m/0/1/3/7 --"
524 K0137, K0137_compressed, c0137 = CKD_prime(K013, c013, 7)
525 print "address", hash_160_to_bc_address(hash_160(K0137_compressed))
531 pubkeys = ["04e89a79651522201d756f14b1874ae49139cc984e5782afeca30ffe84e5e6b2cfadcfe9875c490c8a1a05a4debd715dd57471af8886ab5dfbb3959d97f087f77a",
532 "0455cf4a3ab68a011b18cb0a86aae2b8e9cad6c6355476de05247c57a9632d127084ac7630ad89893b43c486c5a9f7ec6158fb0feb708fa9255d5c4d44bc0858f8"]
533 s = multisig_script(pubkeys)
534 print "address", hash_160_to_bc_address(hash_160(s.decode('hex')), 5)
537 print "Gavin's tutorial: redeem p2sh: http://blockchain.info/tx-index/30888901"
538 pubkey1 = "0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"
539 pubkey2 = "04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"
540 pubkey3 = "048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"
541 pubkeys = [pubkey1, pubkey2, pubkey3]
543 tx = Transaction.from_io(
544 [{'tx_hash':'3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac', 'index':0,
545 'raw_output_script':'a914f815b036d9bbbce5e9f2a00abd1bf3dc91e9551087', 'pubkeys':pubkeys, 'p2sh_num':2}],
546 [('1GtpSrGhRGY5kkrNz4RykoqRQoJuG2L6DS',1000000)])
548 tx_for_sig = tx.for_sig(0)
549 print "tx for sig", tx_for_sig
551 signature1 = "304502200187af928e9d155c4b1ac9c1c9118153239aba76774f775d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1bbdaaba4e50eb078f39e3d78"
552 signature2 = "30440220795f0f4f5941a77ae032ecb9e33753788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e27038e945bc9db59c732728a383a6f1ed2fb99da7a4"
554 for pubkey in pubkeys:
555 import traceback, sys
557 public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1)
560 public_key.verify_digest( signature1.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
562 except ecdsa.keys.BadSignatureError:
563 #traceback.print_exc(file=sys.stdout)
567 public_key.verify_digest( signature2.decode('hex'), Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der)
569 except ecdsa.keys.BadSignatureError:
570 #traceback.print_exc(file=sys.stdout)
573 if __name__ == '__main__':