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
35 return "fd"+int_to_hex(i,2)
37 return "fe"+int_to_hex(i,4)
39 return "ff"+int_to_hex(i,8)
42 Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()
43 hash_encode = lambda x: x[::-1].encode('hex')
44 hash_decode = lambda x: x.decode('hex')[::-1]
46 ############ functions from pywallet #####################
50 def hash_160(public_key):
52 md = hashlib.new('ripemd160')
53 md.update(hashlib.sha256(public_key).digest())
57 md = ripemd.new(hashlib.sha256(public_key).digest())
61 def public_key_to_bc_address(public_key):
62 h160 = hash_160(public_key)
63 return hash_160_to_bc_address(h160)
65 def hash_160_to_bc_address(h160):
66 vh160 = chr(addrtype) + h160
69 return b58encode(addr)
71 def bc_address_to_hash_160(addr):
72 bytes = b58decode(addr, 25)
75 def encode_point(pubkey, compressed=False):
76 order = generator_secp256k1.order()
77 p = pubkey.pubkey.point
78 x_str = ecdsa.util.number_to_string(p.x(), order)
79 y_str = ecdsa.util.number_to_string(p.y(), order)
81 return chr(2 + (p.y() & 1)) + x_str
83 return chr(4) + pubkey.to_string() #x_str + y_str
85 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
86 __b58base = len(__b58chars)
89 """ encode v, which is a string of bytes, to base58."""
92 for (i, c) in enumerate(v[::-1]):
93 long_value += (256**i) * ord(c)
96 while long_value >= __b58base:
97 div, mod = divmod(long_value, __b58base)
98 result = __b58chars[mod] + result
100 result = __b58chars[long_value] + result
102 # Bitcoin does a little leading-zero-compression:
103 # leading 0-bytes in the input become leading-1s
106 if c == '\0': nPad += 1
109 return (__b58chars[0]*nPad) + result
111 def b58decode(v, length):
112 """ decode v into a string of len bytes."""
114 for (i, c) in enumerate(v[::-1]):
115 long_value += __b58chars.find(c) * (__b58base**i)
118 while long_value >= 256:
119 div, mod = divmod(long_value, 256)
120 result = chr(mod) + result
122 result = chr(long_value) + result
126 if c == __b58chars[0]: nPad += 1
129 result = chr(0)*nPad + result
130 if length is not None and len(result) != length:
136 def EncodeBase58Check(vchIn):
138 return b58encode(vchIn + hash[0:4])
140 def DecodeBase58Check(psz):
141 vchRet = b58decode(psz, None)
151 def PrivKeyToSecret(privkey):
152 return privkey[9:9+32]
154 def SecretToASecret(secret):
155 vchIn = chr(addrtype+128) + secret
156 return EncodeBase58Check(vchIn)
158 def ASecretToSecret(key):
159 vch = DecodeBase58Check(key)
160 if vch and vch[0] == chr(addrtype+128):
165 ########### end pywallet functions #######################
167 # secp256k1, http://www.oid-info.com/get/1.3.132.0.10
168 _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
169 _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
170 _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
171 _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
172 _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
173 _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
174 curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
175 generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
176 oid_secp256k1 = (1,3,132,0,10)
177 SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 )
181 out = re.sub('( [^\n]*|)\n','',s)
182 out = out.replace(' ','')
183 out = out.replace('\n','')
186 # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
187 def raw_tx( inputs, outputs, for_sig = None ):
188 s = int_to_hex(1,4) + ' version\n'
189 s += var_int( len(inputs) ) + ' number of inputs\n'
190 for i in range(len(inputs)):
191 _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i]
192 s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n'
193 s += int_to_hex(p_index,4) + ' prev index\n'
195 sig = sig + chr(1) # hashtype
196 script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig)
197 script += sig.encode('hex') + ' sig\n'
198 pubkey = chr(4) + pubkey
199 script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey)
200 script += pubkey.encode('hex') + ' pubkey\n'
202 script = p_script + ' scriptsig \n'
205 s += var_int( len(filter(script))/2 ) + ' script length \n'
207 s += "ffffffff" + ' sequence\n'
208 s += var_int( len(outputs) ) + ' number of outputs\n'
209 for output in outputs:
210 addr, amount = output
211 s += int_to_hex( amount, 8) + ' amount: %d\n'%amount
212 script = '76a9' # op_dup, op_hash_160
213 script += '14' # push 0x14 bytes
214 script += bc_address_to_hash_160(addr).encode('hex')
215 script += '88ac' # op_equalverify, op_checksig
216 s += var_int( len(filter(script))/2 ) + ' script length \n'
217 s += script + ' script \n'
218 s += int_to_hex(0,4) # lock time
219 if for_sig is not None: s += int_to_hex(1, 4) # hash type