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