1 from __future__ import division
5 from p2pool.util import bases, math, pack
8 class ChecksummedType(pack.Type):
9 def __init__(self, inner):
13 obj, file = self.inner.read(file)
14 data = self.inner.pack(obj)
16 checksum, file = pack.read(file, 4)
17 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
18 raise ValueError('invalid checksum')
22 def write(self, file, item):
23 data = self.inner.pack(item)
24 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
26 class FloatingInteger(object):
27 __slots__ = ['bits', '_target']
30 def from_target_upper_bound(cls, target):
31 n = bases.natural_to_string(target)
32 if n and ord(n[0]) >= 128:
34 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
35 bits = pack.IntType(32).unpack(bits2)
38 def __init__(self, bits, target=None):
41 if target is not None and self.target != target:
42 raise ValueError('target does not match')
48 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
52 return hash(self.bits)
54 def __eq__(self, other):
55 return self.bits == other.bits
57 def __ne__(self, other):
58 return not (self == other)
60 def __cmp__(self, other):
64 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
66 class FloatingIntegerType(pack.Type):
67 _inner = pack.IntType(32)
70 bits, file = self._inner.read(file)
71 return FloatingInteger(bits), file
73 def write(self, file, item):
74 return self._inner.write(file, item.bits)
76 address_type = pack.ComposedType([
77 ('services', pack.IntType(64)),
78 ('address', pack.IPV6AddressType()),
79 ('port', pack.IntType(16, 'big')),
82 tx_type = pack.ComposedType([
83 ('version', pack.IntType(32)),
84 ('tx_ins', pack.ListType(pack.ComposedType([
85 ('previous_output', pack.PossiblyNoneType(dict(hash=0, index=2**32 - 1), pack.ComposedType([
86 ('hash', pack.IntType(256)),
87 ('index', pack.IntType(32)),
89 ('script', pack.VarStrType()),
90 ('sequence', pack.PossiblyNoneType(2**32 - 1, pack.IntType(32))),
92 ('tx_outs', pack.ListType(pack.ComposedType([
93 ('value', pack.IntType(64)),
94 ('script', pack.VarStrType()),
96 ('lock_time', pack.IntType(32)),
99 merkle_branch_type = pack.ListType(pack.IntType(256))
101 merkle_tx_type = pack.ComposedType([
103 ('block_hash', pack.IntType(256)),
104 ('merkle_branch', merkle_branch_type),
105 ('index', pack.IntType(32)),
108 block_header_type = pack.ComposedType([
109 ('version', pack.IntType(32)),
110 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
111 ('merkle_root', pack.IntType(256)),
112 ('timestamp', pack.IntType(32)),
113 ('bits', FloatingIntegerType()),
114 ('nonce', pack.IntType(32)),
117 block_type = pack.ComposedType([
118 ('header', block_header_type),
119 ('txs', pack.ListType(tx_type)),
122 aux_pow_type = pack.ComposedType([
123 ('merkle_tx', merkle_tx_type),
124 ('merkle_branch', merkle_branch_type),
125 ('index', pack.IntType(32)),
126 ('parent_block_header', block_header_type),
130 merkle_record_type = pack.ComposedType([
131 ('left', pack.IntType(256)),
132 ('right', pack.IntType(256)),
135 def merkle_hash(hashes):
138 hash_list = list(hashes)
139 while len(hash_list) > 1:
140 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
141 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
144 def calculate_merkle_branch(hashes, index):
147 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
149 while len(hash_list) > 1:
152 merkle_record_type.hash256(dict(left=left, right=right)),
154 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
156 for (left, left_f, left_l), (right, right_f, right_l) in
157 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
160 res = [x['hash'] for x in hash_list[0][2]]
162 assert hash_list[0][1]
163 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
164 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
168 def check_merkle_branch(tip_hash, index, merkle_branch):
169 return reduce(lambda c, (i, h): merkle_record_type.hash256(
170 dict(left=h, right=c) if 2**i & index else
171 dict(left=c, right=h)
172 ), enumerate(merkle_branch), tip_hash)
174 def target_to_average_attempts(target):
175 return 2**256//(target + 1)
177 def target_to_difficulty(target):
178 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
182 def tx_get_sigop_count(tx):
183 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'])
187 human_address_type = ChecksummedType(pack.ComposedType([
188 ('version', pack.IntType(8)),
189 ('pubkey_hash', pack.IntType(160)),
192 pubkey_type = pack.PassthruType()
194 def pubkey_hash_to_address(pubkey_hash, net):
195 return base58.encode(human_address_type.pack(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash)))
197 def pubkey_to_address(pubkey, net):
198 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
200 def address_to_pubkey_hash(address, net):
201 x = human_address_type.unpack(base58.decode(address))
202 if x['version'] != net.ADDRESS_VERSION:
203 raise ValueError('address not for this net!')
204 return x['pubkey_hash']
208 def pubkey_to_script2(pubkey):
209 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
211 def pubkey_hash_to_script2(pubkey_hash):
212 return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
214 def script2_to_address(script2, net):
216 pubkey = script2[1:-1]
217 script2_test = pubkey_to_script2(pubkey)
221 if script2_test == script2:
222 return pubkey_to_address(pubkey, net)
225 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
226 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
230 if script2_test2 == script2:
231 return pubkey_hash_to_address(pubkey_hash, net)
233 def script2_to_human(script2, net):
235 pubkey = script2[1:-1]
236 script2_test = pubkey_to_script2(pubkey)
240 if script2_test == script2:
241 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
244 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
245 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
249 if script2_test2 == script2:
250 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
252 return 'Unknown. Script: %s' % (script2.encode('hex'),)