1 from __future__ import division
5 from p2pool.util import bases, math, pack
7 class ChecksummedType(pack.Type):
8 def __init__(self, inner):
12 obj, file = self.inner.read(file)
13 data = self.inner.pack(obj)
15 checksum, file = pack.read(file, 4)
16 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
17 raise ValueError('invalid checksum')
21 def write(self, file, item):
22 data = self.inner.pack(item)
23 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
25 class FloatingInteger(object):
26 __slots__ = ['bits', '_target']
29 def from_target_upper_bound(cls, target):
30 n = bases.natural_to_string(target)
31 if n and ord(n[0]) >= 128:
33 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
34 bits = pack.IntType(32).unpack(bits2)
37 def __init__(self, bits, target=None):
40 if target is not None and self.target != target:
41 raise ValueError('target does not match')
47 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
51 return hash(self.bits)
53 def __eq__(self, other):
54 return self.bits == other.bits
56 def __ne__(self, other):
57 return not (self == other)
59 def __cmp__(self, other):
63 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
65 class FloatingIntegerType(pack.Type):
66 _inner = pack.IntType(32)
69 bits, file = self._inner.read(file)
70 return FloatingInteger(bits), file
72 def write(self, file, item):
73 return self._inner.write(file, item.bits)
75 address_type = pack.ComposedType([
76 ('services', pack.IntType(64)),
77 ('address', pack.IPV6AddressType()),
78 ('port', pack.IntType(16, 'big')),
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)),
88 ('script', pack.VarStrType()),
89 ('sequence', pack.PossiblyNoneType(2**32 - 1, pack.IntType(32))),
91 ('tx_outs', pack.ListType(pack.ComposedType([
92 ('value', pack.IntType(64)),
93 ('script', pack.VarStrType()),
95 ('lock_time', pack.IntType(32)),
98 merkle_branch_type = pack.ListType(pack.IntType(256))
100 merkle_tx_type = pack.ComposedType([
102 ('block_hash', pack.IntType(256)),
103 ('merkle_branch', merkle_branch_type),
104 ('index', pack.IntType(32)),
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)),
116 block_type = pack.ComposedType([
117 ('header', block_header_type),
118 ('txs', pack.ListType(tx_type)),
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),
129 merkle_record_type = pack.ComposedType([
130 ('left', pack.IntType(256)),
131 ('right', pack.IntType(256)),
134 def merkle_hash(hashes):
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])]
143 def calculate_merkle_branch(hashes, index):
146 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
148 while len(hash_list) > 1:
151 merkle_record_type.hash256(dict(left=left, right=right)),
153 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
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]])
159 res = [x['hash'] for x in hash_list[0][2]]
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]]))
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)
173 def target_to_average_attempts(target):
174 return 2**256//(target + 1)
176 def target_to_difficulty(target):
177 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
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'])
186 human_address_type = ChecksummedType(pack.ComposedType([
187 ('version', pack.IntType(8)),
188 ('pubkey_hash', pack.IntType(160)),
191 pubkey_type = pack.PassthruType()
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))
196 def pubkey_to_address(pubkey, net):
197 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
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']
207 def pubkey_to_script2(pubkey):
208 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
210 def pubkey_hash_to_script2(pubkey_hash):
211 return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
213 def script2_to_address(script2, net):
215 pubkey = script2[1:-1]
216 script2_test = pubkey_to_script2(pubkey)
220 if script2_test == script2:
221 return pubkey_to_address(pubkey, net)
224 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
225 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
229 if script2_test2 == script2:
230 return pubkey_hash_to_address(pubkey_hash, net)
232 def script2_to_human(script2, net):
234 pubkey = script2[1:-1]
235 script2_test = pubkey_to_script2(pubkey)
239 if script2_test == script2:
240 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
243 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
244 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
248 if script2_test2 == script2:
249 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
251 return 'Unknown. Script: %s' % (script2.encode('hex'),)