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
33 return hashlib.sha256(hashlib.sha256(data).digest()).digest()
36 ############ functions from pywallet #####################
40 def hash_160(public_key):
42 md = hashlib.new('ripemd160')
43 md.update(hashlib.sha256(public_key).digest())
47 md = ripemd.new(hashlib.sha256(public_key).digest())
51 def public_key_to_bc_address(public_key):
52 h160 = hash_160(public_key)
53 return hash_160_to_bc_address(h160)
55 def hash_160_to_bc_address(h160):
56 vh160 = chr(addrtype) + h160
59 return b58encode(addr)
61 def bc_address_to_hash_160(addr):
62 bytes = b58decode(addr, 25)
65 def encode_point(pubkey, compressed=False):
66 order = generator_secp256k1.order()
67 p = pubkey.pubkey.point
68 x_str = ecdsa.util.number_to_string(p.x(), order)
69 y_str = ecdsa.util.number_to_string(p.y(), order)
71 return chr(2 + (p.y() & 1)) + x_str
73 return chr(4) + pubkey.to_string() #x_str + y_str
75 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
76 __b58base = len(__b58chars)
79 """ encode v, which is a string of bytes, to base58."""
82 for (i, c) in enumerate(v[::-1]):
83 long_value += (256**i) * ord(c)
86 while long_value >= __b58base:
87 div, mod = divmod(long_value, __b58base)
88 result = __b58chars[mod] + result
90 result = __b58chars[long_value] + result
92 # Bitcoin does a little leading-zero-compression:
93 # leading 0-bytes in the input become leading-1s
96 if c == '\0': nPad += 1
99 return (__b58chars[0]*nPad) + result
101 def b58decode(v, length):
102 """ decode v into a string of len bytes."""
104 for (i, c) in enumerate(v[::-1]):
105 long_value += __b58chars.find(c) * (__b58base**i)
108 while long_value >= 256:
109 div, mod = divmod(long_value, 256)
110 result = chr(mod) + result
112 result = chr(long_value) + result
116 if c == __b58chars[0]: nPad += 1
119 result = chr(0)*nPad + result
120 if length is not None and len(result) != length:
126 def EncodeBase58Check(vchIn):
128 return b58encode(vchIn + hash[0:4])
130 def DecodeBase58Check(psz):
131 vchRet = b58decode(psz, None)
141 def PrivKeyToSecret(privkey):
142 return privkey[9:9+32]
144 def SecretToASecret(secret):
145 vchIn = chr(addrtype+128) + secret
146 return EncodeBase58Check(vchIn)
148 def ASecretToSecret(key):
149 vch = DecodeBase58Check(key)
150 if vch and vch[0] == chr(addrtype+128):
155 ########### end pywallet functions #######################
157 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
158 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
159 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
160 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
161 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
162 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
163 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
164 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
165 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
166 oid_secp256k1 = (1,3,132,0,10)
167 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
171 out = re.sub('( [^\n]*|)\n','',s)
172 out = out.replace(' ','')
173 out = out.replace('\n','')
176 def raw_tx( inputs, outputs, for_sig = None ):
177 s = int_to_hex(1,4) + ' version\n'
178 s += int_to_hex( len(inputs) ) + ' number of inputs\n'
179 for i in range(len(inputs)):
180 _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
181 s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n'
182 s += int_to_hex(p_index,4) + ' prev index\n'
184 sig = sig + chr(1) # hashtype
185 script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig)
186 script += sig.encode('hex') + ' sig\n'
187 pubkey = chr(4) + pubkey
188 script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey)
189 script += pubkey.encode('hex') + ' pubkey\n'
191 script = p_script + ' scriptsig \n'
194 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
196 s += "ffffffff" + ' sequence\n'
197 s += int_to_hex( len(outputs) ) + ' number of outputs\n'
198 for output in outputs:
199 addr, amount = output
200 s += int_to_hex( amount, 8) + ' amount: %d\n'%amount
201 script = '76a9' # op_dup, op_hash_160
202 script += '14' # push 0x14 bytes
203 script += bc_address_to_hash_160(addr).encode('hex')
204 script += '88ac' # op_equalverify, op_checksig
205 s += int_to_hex( len(filter(script))/2 ) + ' script length \n'
206 s += script + ' script \n'
207 s += int_to_hex(0,4) # lock time
208 if for_sig is not None: s += int_to_hex(1, 4) # hash type