9cdb25be1e8a23286df1b88eb8b867ea623da6d6
[electrum-nvc.git] / lib / bitcoin.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2011 thomasv@gitorious
5 #
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.
10 #
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.
15 #
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/>.
18
19
20 import hashlib, base64, ecdsa, re
21
22
23 def rev_hex(s):
24     return s.decode('hex')[::-1].encode('hex')
25
26 def int_to_hex(i, length=1):
27     s = hex(i)[2:].rstrip('L')
28     s = "0"*(2*length - len(s)) + s
29     return rev_hex(s)
30
31
32 def Hash(data):
33     return hashlib.sha256(hashlib.sha256(data).digest()).digest()
34
35
36 ############ functions from pywallet ##################### 
37
38 addrtype = 0
39
40 def hash_160(public_key):
41     try:
42         md = hashlib.new('ripemd160')
43         md.update(hashlib.sha256(public_key).digest())
44         return md.digest()
45     except:
46         import ripemd
47         md = ripemd.new(hashlib.sha256(public_key).digest())
48         return md.digest()
49
50
51 def public_key_to_bc_address(public_key):
52     h160 = hash_160(public_key)
53     return hash_160_to_bc_address(h160)
54
55 def hash_160_to_bc_address(h160):
56     vh160 = chr(addrtype) + h160
57     h = Hash(vh160)
58     addr = vh160 + h[0:4]
59     return b58encode(addr)
60
61 def bc_address_to_hash_160(addr):
62     bytes = b58decode(addr, 25)
63     return bytes[1:21]
64
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)
70     if compressed:
71         return chr(2 + (p.y() & 1)) + x_str
72     else:
73         return chr(4) + pubkey.to_string() #x_str + y_str
74
75 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
76 __b58base = len(__b58chars)
77
78 def b58encode(v):
79     """ encode v, which is a string of bytes, to base58."""
80
81     long_value = 0L
82     for (i, c) in enumerate(v[::-1]):
83         long_value += (256**i) * ord(c)
84
85     result = ''
86     while long_value >= __b58base:
87         div, mod = divmod(long_value, __b58base)
88         result = __b58chars[mod] + result
89         long_value = div
90     result = __b58chars[long_value] + result
91
92     # Bitcoin does a little leading-zero-compression:
93     # leading 0-bytes in the input become leading-1s
94     nPad = 0
95     for c in v:
96         if c == '\0': nPad += 1
97         else: break
98
99     return (__b58chars[0]*nPad) + result
100
101 def b58decode(v, length):
102     """ decode v into a string of len bytes."""
103     long_value = 0L
104     for (i, c) in enumerate(v[::-1]):
105         long_value += __b58chars.find(c) * (__b58base**i)
106
107     result = ''
108     while long_value >= 256:
109         div, mod = divmod(long_value, 256)
110         result = chr(mod) + result
111         long_value = div
112     result = chr(long_value) + result
113
114     nPad = 0
115     for c in v:
116         if c == __b58chars[0]: nPad += 1
117         else: break
118
119     result = chr(0)*nPad + result
120     if length is not None and len(result) != length:
121         return None
122
123     return result
124
125
126 def EncodeBase58Check(vchIn):
127     hash = Hash(vchIn)
128     return b58encode(vchIn + hash[0:4])
129
130 def DecodeBase58Check(psz):
131     vchRet = b58decode(psz, None)
132     key = vchRet[0:-4]
133     csum = vchRet[-4:]
134     hash = Hash(key)
135     cs32 = hash[0:4]
136     if cs32 != csum:
137         return None
138     else:
139         return key
140
141 def PrivKeyToSecret(privkey):
142     return privkey[9:9+32]
143
144 def SecretToASecret(secret):
145     vchIn = chr(addrtype+128) + secret
146     return EncodeBase58Check(vchIn)
147
148 def ASecretToSecret(key):
149     vch = DecodeBase58Check(key)
150     if vch and vch[0] == chr(addrtype+128):
151         return vch[1:]
152     else:
153         return False
154
155 ########### end pywallet functions #######################
156
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 ) 
168
169
170 def filter(s): 
171     out = re.sub('( [^\n]*|)\n','',s)
172     out = out.replace(' ','')
173     out = out.replace('\n','')
174     return out
175
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'
183         if for_sig is None:
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'
190         elif for_sig==i:
191             script = p_script                                +  '     scriptsig \n'
192         else:
193             script=''
194         s += int_to_hex( len(filter(script))/2 )             +  '     script length \n'
195         s += script
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
209     return s
210
211