fix: var_int encoding
[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 def var_int(i):
32     if i<0xfd:
33         return int_to_hex(i)
34     elif i<0xffff:
35         return "fd"+int_to_hex(i,2)
36     elif i<0xffffffff:
37         return "fe"+int_to_hex(i,4)
38     else:
39         return "ff"+int_to_hex(i,8)
40
41
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]
45
46 ############ functions from pywallet ##################### 
47
48 addrtype = 0
49
50 def hash_160(public_key):
51     try:
52         md = hashlib.new('ripemd160')
53         md.update(hashlib.sha256(public_key).digest())
54         return md.digest()
55     except:
56         import ripemd
57         md = ripemd.new(hashlib.sha256(public_key).digest())
58         return md.digest()
59
60
61 def public_key_to_bc_address(public_key):
62     h160 = hash_160(public_key)
63     return hash_160_to_bc_address(h160)
64
65 def hash_160_to_bc_address(h160):
66     vh160 = chr(addrtype) + h160
67     h = Hash(vh160)
68     addr = vh160 + h[0:4]
69     return b58encode(addr)
70
71 def bc_address_to_hash_160(addr):
72     bytes = b58decode(addr, 25)
73     return bytes[1:21]
74
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)
80     if compressed:
81         return chr(2 + (p.y() & 1)) + x_str
82     else:
83         return chr(4) + pubkey.to_string() #x_str + y_str
84
85 __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
86 __b58base = len(__b58chars)
87
88 def b58encode(v):
89     """ encode v, which is a string of bytes, to base58."""
90
91     long_value = 0L
92     for (i, c) in enumerate(v[::-1]):
93         long_value += (256**i) * ord(c)
94
95     result = ''
96     while long_value >= __b58base:
97         div, mod = divmod(long_value, __b58base)
98         result = __b58chars[mod] + result
99         long_value = div
100     result = __b58chars[long_value] + result
101
102     # Bitcoin does a little leading-zero-compression:
103     # leading 0-bytes in the input become leading-1s
104     nPad = 0
105     for c in v:
106         if c == '\0': nPad += 1
107         else: break
108
109     return (__b58chars[0]*nPad) + result
110
111 def b58decode(v, length):
112     """ decode v into a string of len bytes."""
113     long_value = 0L
114     for (i, c) in enumerate(v[::-1]):
115         long_value += __b58chars.find(c) * (__b58base**i)
116
117     result = ''
118     while long_value >= 256:
119         div, mod = divmod(long_value, 256)
120         result = chr(mod) + result
121         long_value = div
122     result = chr(long_value) + result
123
124     nPad = 0
125     for c in v:
126         if c == __b58chars[0]: nPad += 1
127         else: break
128
129     result = chr(0)*nPad + result
130     if length is not None and len(result) != length:
131         return None
132
133     return result
134
135
136 def EncodeBase58Check(vchIn):
137     hash = Hash(vchIn)
138     return b58encode(vchIn + hash[0:4])
139
140 def DecodeBase58Check(psz):
141     vchRet = b58decode(psz, None)
142     key = vchRet[0:-4]
143     csum = vchRet[-4:]
144     hash = Hash(key)
145     cs32 = hash[0:4]
146     if cs32 != csum:
147         return None
148     else:
149         return key
150
151 def PrivKeyToSecret(privkey):
152     return privkey[9:9+32]
153
154 def SecretToASecret(secret):
155     vchIn = chr(addrtype+128) + secret
156     return EncodeBase58Check(vchIn)
157
158 def ASecretToSecret(key):
159     vch = DecodeBase58Check(key)
160     if vch and vch[0] == chr(addrtype+128):
161         return vch[1:]
162     else:
163         return False
164
165 ########### end pywallet functions #######################
166
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 ) 
178
179
180 def filter(s): 
181     out = re.sub('( [^\n]*|)\n','',s)
182     out = out.replace(' ','')
183     out = out.replace('\n','')
184     return out
185
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'
194         if for_sig is None:
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'
201         elif for_sig==i:
202             script = p_script                                +  '     scriptsig \n'
203         else:
204             script=''
205         s += var_int( len(filter(script))/2 )                +  '     script length \n'
206         s += script
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
220     return s
221
222