fixed compressed pubkey handling
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4 import itertools
5 import random
6
7 import p2pool
8 from p2pool.util import math, pack
9
10 def hash256(data):
11     return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
12
13 def hash160(data):
14     return pack.IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(data).digest()).digest())
15
16 class ChecksummedType(pack.Type):
17     def __init__(self, inner):
18         self.inner = inner
19     
20     def read(self, file):
21         obj, file = self.inner.read(file)
22         data = self.inner.pack(obj)
23         
24         checksum, file = pack.read(file, 4)
25         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
26             raise ValueError('invalid checksum')
27         
28         return obj, file
29     
30     def write(self, file, item):
31         data = self.inner.pack(item)
32         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
33
34 class FloatingInteger(object):
35     __slots__ = ['bits', '_target']
36     
37     @classmethod
38     def from_target_upper_bound(cls, target):
39         n = math.natural_to_string(target)
40         if n and ord(n[0]) >= 128:
41             n = '\x00' + n
42         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
43         bits = pack.IntType(32).unpack(bits2)
44         return cls(bits)
45     
46     def __init__(self, bits, target=None):
47         self.bits = bits
48         self._target = None
49         if target is not None and self.target != target:
50             raise ValueError('target does not match')
51     
52     @property
53     def target(self):
54         res = self._target
55         if res is None:
56             res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
57         return res
58     
59     def __hash__(self):
60         return hash(self.bits)
61     
62     def __eq__(self, other):
63         return self.bits == other.bits
64     
65     def __ne__(self, other):
66         return not (self == other)
67     
68     def __cmp__(self, other):
69         assert False
70     
71     def __repr__(self):
72         return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
73
74 class FloatingIntegerType(pack.Type):
75     _inner = pack.IntType(32)
76     
77     def read(self, file):
78         bits, file = self._inner.read(file)
79         return FloatingInteger(bits), file
80     
81     def write(self, file, item):
82         return self._inner.write(file, item.bits)
83
84 address_type = pack.ComposedType([
85     ('services', pack.IntType(64)),
86     ('address', pack.IPV6AddressType()),
87     ('port', pack.IntType(16, 'big')),
88 ])
89
90 tx_type = pack.ComposedType([
91     ('version', pack.IntType(32)),
92     ('tx_ins', pack.ListType(pack.ComposedType([
93         ('previous_output', pack.PossiblyNoneType(dict(hash=0, index=2**32 - 1), pack.ComposedType([
94             ('hash', pack.IntType(256)),
95             ('index', pack.IntType(32)),
96         ]))),
97         ('script', pack.VarStrType()),
98         ('sequence', pack.PossiblyNoneType(2**32 - 1, pack.IntType(32))),
99     ]))),
100     ('tx_outs', pack.ListType(pack.ComposedType([
101         ('value', pack.IntType(64)),
102         ('script', pack.VarStrType()),
103     ]))),
104     ('lock_time', pack.IntType(32)),
105 ])
106
107 merkle_branch_type = pack.ListType(pack.IntType(256))
108
109 merkle_tx_type = pack.ComposedType([
110     ('tx', tx_type),
111     ('block_hash', pack.IntType(256)),
112     ('merkle_branch', merkle_branch_type),
113     ('index', pack.IntType(32)),
114 ])
115
116 block_header_type = pack.ComposedType([
117     ('version', pack.IntType(32)),
118     ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
119     ('merkle_root', pack.IntType(256)),
120     ('timestamp', pack.IntType(32)),
121     ('bits', FloatingIntegerType()),
122     ('nonce', pack.IntType(32)),
123 ])
124
125 block_type = pack.ComposedType([
126     ('header', block_header_type),
127     ('txs', pack.ListType(tx_type)),
128 ])
129
130 # merged mining
131
132 aux_pow_type = pack.ComposedType([
133     ('merkle_tx', merkle_tx_type),
134     ('merkle_branch', merkle_branch_type),
135     ('index', pack.IntType(32)),
136     ('parent_block_header', block_header_type),
137 ])
138
139 aux_pow_coinbase_type = pack.ComposedType([
140     ('merkle_root', pack.IntType(256, 'big')),
141     ('size', pack.IntType(32)),
142     ('nonce', pack.IntType(32)),
143 ])
144
145 def make_auxpow_tree(chain_ids):
146     for size in (2**i for i in xrange(31)):
147         if size < len(chain_ids):
148             continue
149         res = {}
150         for chain_id in chain_ids:
151             pos = (1103515245 * chain_id + 1103515245 * 12345 + 12345) % size
152             if pos in res:
153                 break
154             res[pos] = chain_id
155         else:
156             return res, size
157     raise AssertionError()
158
159 # merkle trees
160
161 merkle_record_type = pack.ComposedType([
162     ('left', pack.IntType(256)),
163     ('right', pack.IntType(256)),
164 ])
165
166 def merkle_hash(hashes):
167     if not hashes:
168         return 0
169     hash_list = list(hashes)
170     while len(hash_list) > 1:
171         hash_list = [hash256(merkle_record_type.pack(dict(left=left, right=left if right is None else right)))
172             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
173     return hash_list[0]
174
175 def calculate_merkle_branch(hashes, index):
176     # XXX optimize this
177     
178     hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
179     
180     while len(hash_list) > 1:
181         hash_list = [
182             (
183                 hash256(merkle_record_type.pack(dict(left=left, right=right))),
184                 left_f or right_f,
185                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
186             )
187             for (left, left_f, left_l), (right, right_f, right_l) in
188                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
189         ]
190     
191     res = [x['hash'] for x in hash_list[0][2]]
192     
193     assert hash_list[0][1]
194     if p2pool.DEBUG:
195         assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
196     assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
197     
198     return res
199
200 def check_merkle_branch(tip_hash, index, merkle_branch):
201     return reduce(lambda c, (i, h): hash256(merkle_record_type.pack(
202         dict(left=h, right=c) if 2**i & index else
203         dict(left=c, right=h)
204     )), enumerate(merkle_branch), tip_hash)
205
206 # targets
207
208 def target_to_average_attempts(target):
209     return 2**256//(target + 1)
210
211 def target_to_difficulty(target):
212     return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
213
214 # tx
215
216 def tx_get_sigop_count(tx):
217     return sum(script.get_sigop_count(txin['script']) for txin in tx['tx_ins']) + sum(script.get_sigop_count(txout['script']) for txout in tx['tx_outs'])
218
219 # human addresses
220
221 base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
222
223 def base58_encode(bindata):
224     bindata2 = bindata.lstrip(chr(0))
225     return base58_alphabet[0]*(len(bindata) - len(bindata2)) + math.natural_to_string(math.string_to_natural(bindata2), base58_alphabet)
226
227 def base58_decode(b58data):
228     b58data2 = b58data.lstrip(base58_alphabet[0])
229     return chr(0)*(len(b58data) - len(b58data2)) + math.natural_to_string(math.string_to_natural(b58data2, base58_alphabet))
230
231 human_address_type = ChecksummedType(pack.ComposedType([
232     ('version', pack.IntType(8)),
233     ('pubkey_hash', pack.IntType(160)),
234 ]))
235
236 def pubkey_hash_to_address(pubkey_hash, net):
237     return base58_encode(human_address_type.pack(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash)))
238
239 def pubkey_to_address(pubkey, net):
240     return pubkey_hash_to_address(hash160(pubkey), net)
241
242 def address_to_pubkey_hash(address, net):
243     x = human_address_type.unpack(base58_decode(address))
244     if x['version'] != net.ADDRESS_VERSION:
245         raise ValueError('address not for this net!')
246     return x['pubkey_hash']
247
248 # transactions
249
250 def pubkey_to_script2(pubkey):
251     assert len(pubkey) <= 75
252     return (chr(len(pubkey)) + pubkey) + '\xac'
253
254 def pubkey_hash_to_script2(pubkey_hash):
255     return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
256
257 def script2_to_address(script2, net):
258     try:
259         pubkey = script2[1:-1]
260         script2_test = pubkey_to_script2(pubkey)
261     except:
262         pass
263     else:
264         if script2_test == script2:
265             return pubkey_to_address(pubkey, net)
266     
267     try:
268         pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
269         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
270     except:
271         pass
272     else:
273         if script2_test2 == script2:
274             return pubkey_hash_to_address(pubkey_hash, net)
275
276 def script2_to_human(script2, net):
277     try:
278         pubkey = script2[1:-1]
279         script2_test = pubkey_to_script2(pubkey)
280     except:
281         pass
282     else:
283         if script2_test == script2:
284             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
285     
286     try:
287         pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
288         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
289     except:
290         pass
291     else:
292         if script2_test2 == script2:
293             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
294     
295     return 'Unknown. Script: %s'  % (script2.encode('hex'),)