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