added merkle_link structure that combines branch and index
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4
5 import p2pool
6 from p2pool.util import math, pack
7
8 def hash256(data):
9     return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
10
11 def hash160(data):
12     return pack.IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(data).digest()).digest())
13
14 class ChecksummedType(pack.Type):
15     def __init__(self, inner, checksum_func=lambda data: hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]):
16         self.inner = inner
17         self.checksum_func = checksum_func
18     
19     def read(self, file):
20         obj, file = self.inner.read(file)
21         data = self.inner.pack(obj)
22         
23         calculated_checksum = self.checksum_func(data)
24         checksum, file = pack.read(file, len(calculated_checksum))
25         if checksum != calculated_checksum:
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), self.checksum_func(data)
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_link_type = pack.ComposedType([
108     ('branch', pack.ListType(pack.IntType(256))),
109     ('index', pack.IntType(32)),
110 ])
111
112 merkle_tx_type = pack.ComposedType([
113     ('tx', tx_type),
114     ('block_hash', pack.IntType(256)),
115     ('merkle_link', merkle_link_type),
116 ])
117
118 block_header_type = pack.ComposedType([
119     ('version', pack.IntType(32)),
120     ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
121     ('merkle_root', pack.IntType(256)),
122     ('timestamp', pack.IntType(32)),
123     ('bits', FloatingIntegerType()),
124     ('nonce', pack.IntType(32)),
125 ])
126
127 block_type = pack.ComposedType([
128     ('header', block_header_type),
129     ('txs', pack.ListType(tx_type)),
130 ])
131
132 # merged mining
133
134 aux_pow_type = pack.ComposedType([
135     ('merkle_tx', merkle_tx_type),
136     ('merkle_link', merkle_link_type),
137     ('parent_block_header', block_header_type),
138 ])
139
140 aux_pow_coinbase_type = pack.ComposedType([
141     ('merkle_root', pack.IntType(256, 'big')),
142     ('size', pack.IntType(32)),
143     ('nonce', pack.IntType(32)),
144 ])
145
146 def make_auxpow_tree(chain_ids):
147     for size in (2**i for i in xrange(31)):
148         if size < len(chain_ids):
149             continue
150         res = {}
151         for chain_id in chain_ids:
152             pos = (1103515245 * chain_id + 1103515245 * 12345 + 12345) % size
153             if pos in res:
154                 break
155             res[pos] = chain_id
156         else:
157             return res, size
158     raise AssertionError()
159
160 # merkle trees
161
162 merkle_record_type = pack.ComposedType([
163     ('left', pack.IntType(256)),
164     ('right', pack.IntType(256)),
165 ])
166
167 def merkle_hash(hashes):
168     if not hashes:
169         return 0
170     hash_list = list(hashes)
171     while len(hash_list) > 1:
172         hash_list = [hash256(merkle_record_type.pack(dict(left=left, right=right)))
173             for left, right in zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])]
174     return hash_list[0]
175
176 def calculate_merkle_link(hashes, index):
177     # XXX optimize this
178     
179     hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
180     
181     while len(hash_list) > 1:
182         hash_list = [
183             (
184                 hash256(merkle_record_type.pack(dict(left=left, right=right))),
185                 left_f or right_f,
186                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
187             )
188             for (left, left_f, left_l), (right, right_f, right_l) in
189                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
190         ]
191     
192     res = [x['hash'] for x in hash_list[0][2]]
193     
194     assert hash_list[0][1]
195     if p2pool.DEBUG:
196         assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
197     assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
198     
199     return dict(branch=res, index=index)
200
201 def check_merkle_link(tip_hash, link):
202     if link['index'] >= 2**len(link['branch']):
203         raise ValueError('index too large')
204     return reduce(lambda c, (i, h): hash256(merkle_record_type.pack(
205         dict(left=h, right=c) if (link['index'] >> i) & 1 else
206         dict(left=c, right=h)
207     )), enumerate(link['branch']), tip_hash)
208
209 # targets
210
211 def target_to_average_attempts(target):
212     return 2**256//(target + 1)
213
214 def target_to_difficulty(target):
215     return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
216
217 def difficulty_to_target(difficulty):
218     return (0xffff0000 * 2**(256-64) + 1)/difficulty - 1
219
220 # tx
221
222 def tx_get_sigop_count(tx):
223     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'])
224
225 # human addresses
226
227 base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
228
229 def base58_encode(bindata):
230     bindata2 = bindata.lstrip(chr(0))
231     return base58_alphabet[0]*(len(bindata) - len(bindata2)) + math.natural_to_string(math.string_to_natural(bindata2), base58_alphabet)
232
233 def base58_decode(b58data):
234     b58data2 = b58data.lstrip(base58_alphabet[0])
235     return chr(0)*(len(b58data) - len(b58data2)) + math.natural_to_string(math.string_to_natural(b58data2, base58_alphabet))
236
237 human_address_type = ChecksummedType(pack.ComposedType([
238     ('version', pack.IntType(8)),
239     ('pubkey_hash', pack.IntType(160)),
240 ]))
241
242 def pubkey_hash_to_address(pubkey_hash, net):
243     return base58_encode(human_address_type.pack(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash)))
244
245 def pubkey_to_address(pubkey, net):
246     return pubkey_hash_to_address(hash160(pubkey), net)
247
248 def address_to_pubkey_hash(address, net):
249     x = human_address_type.unpack(base58_decode(address))
250     if x['version'] != net.ADDRESS_VERSION:
251         raise ValueError('address not for this net!')
252     return x['pubkey_hash']
253
254 # transactions
255
256 def pubkey_to_script2(pubkey):
257     assert len(pubkey) <= 75
258     return (chr(len(pubkey)) + pubkey) + '\xac'
259
260 def pubkey_hash_to_script2(pubkey_hash):
261     return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
262
263 def script2_to_address(script2, net):
264     try:
265         pubkey = script2[1:-1]
266         script2_test = pubkey_to_script2(pubkey)
267     except:
268         pass
269     else:
270         if script2_test == script2:
271             return pubkey_to_address(pubkey, net)
272     
273     try:
274         pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
275         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
276     except:
277         pass
278     else:
279         if script2_test2 == script2:
280             return pubkey_hash_to_address(pubkey_hash, net)
281
282 def script2_to_human(script2, net):
283     try:
284         pubkey = script2[1:-1]
285         script2_test = pubkey_to_script2(pubkey)
286     except:
287         pass
288     else:
289         if script2_test == script2:
290             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
291     
292     try:
293         pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
294         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
295     except:
296         pass
297     else:
298         if script2_test2 == script2:
299             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
300     
301     return 'Unknown. Script: %s'  % (script2.encode('hex'),)