1 from __future__ import division
6 from p2pool.util import math, pack
9 return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
12 return pack.IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(data).digest()).digest())
14 class ChecksummedType(pack.Type):
15 def __init__(self, inner):
19 obj, file = self.inner.read(file)
20 data = self.inner.pack(obj)
22 checksum, file = pack.read(file, 4)
23 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
24 raise ValueError('invalid checksum')
28 def write(self, file, item):
29 data = self.inner.pack(item)
30 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
32 class FloatingInteger(object):
33 __slots__ = ['bits', '_target']
36 def from_target_upper_bound(cls, target):
37 n = math.natural_to_string(target)
38 if n and ord(n[0]) >= 128:
40 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
41 bits = pack.IntType(32).unpack(bits2)
44 def __init__(self, bits, target=None):
47 if target is not None and self.target != target:
48 raise ValueError('target does not match')
54 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
58 return hash(self.bits)
60 def __eq__(self, other):
61 return self.bits == other.bits
63 def __ne__(self, other):
64 return not (self == other)
66 def __cmp__(self, other):
70 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
72 class FloatingIntegerType(pack.Type):
73 _inner = pack.IntType(32)
76 bits, file = self._inner.read(file)
77 return FloatingInteger(bits), file
79 def write(self, file, item):
80 return self._inner.write(file, item.bits)
82 address_type = pack.ComposedType([
83 ('services', pack.IntType(64)),
84 ('address', pack.IPV6AddressType()),
85 ('port', pack.IntType(16, 'big')),
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)),
95 ('script', pack.VarStrType()),
96 ('sequence', pack.PossiblyNoneType(2**32 - 1, pack.IntType(32))),
98 ('tx_outs', pack.ListType(pack.ComposedType([
99 ('value', pack.IntType(64)),
100 ('script', pack.VarStrType()),
102 ('lock_time', pack.IntType(32)),
105 merkle_branch_type = pack.ListType(pack.IntType(256))
107 merkle_tx_type = pack.ComposedType([
109 ('block_hash', pack.IntType(256)),
110 ('merkle_branch', merkle_branch_type),
111 ('index', pack.IntType(32)),
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)),
123 block_type = pack.ComposedType([
124 ('header', block_header_type),
125 ('txs', pack.ListType(tx_type)),
130 aux_pow_type = pack.ComposedType([
131 ('merkle_tx', merkle_tx_type),
132 ('merkle_branch', merkle_branch_type),
133 ('index', pack.IntType(32)),
134 ('parent_block_header', block_header_type),
137 aux_pow_coinbase_type = pack.ComposedType([
138 ('merkle_root', pack.IntType(256, 'big')),
139 ('size', pack.IntType(32)),
140 ('nonce', pack.IntType(32)),
143 def make_auxpow_tree(chain_ids):
144 for size in (2**i for i in xrange(31)):
145 if size < len(chain_ids):
148 for chain_id in chain_ids:
149 pos = (1103515245 * chain_id + 1103515245 * 12345 + 12345) % size
155 raise AssertionError()
159 merkle_record_type = pack.ComposedType([
160 ('left', pack.IntType(256)),
161 ('right', pack.IntType(256)),
164 def merkle_hash(hashes):
167 hash_list = list(hashes)
168 while len(hash_list) > 1:
169 hash_list = [hash256(merkle_record_type.pack(dict(left=left, right=left if right is None else right)))
170 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
173 def calculate_merkle_branch(hashes, index):
176 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
178 while len(hash_list) > 1:
181 hash256(merkle_record_type.pack(dict(left=left, right=right))),
183 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
185 for (left, left_f, left_l), (right, right_f, right_l) in
186 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
189 res = [x['hash'] for x in hash_list[0][2]]
191 assert hash_list[0][1]
193 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
194 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
198 def check_merkle_branch(tip_hash, index, merkle_branch):
199 return reduce(lambda c, (i, h): hash256(merkle_record_type.pack(
200 dict(left=h, right=c) if 2**i & index else
201 dict(left=c, right=h)
202 )), enumerate(merkle_branch), tip_hash)
206 def target_to_average_attempts(target):
207 return 2**256//(target + 1)
209 def target_to_difficulty(target):
210 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
212 def difficulty_to_target(difficulty):
213 return (0xffff0000 * 2**(256-64) + 1)/difficulty - 1
217 def tx_get_sigop_count(tx):
218 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'])
222 base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
224 def base58_encode(bindata):
225 bindata2 = bindata.lstrip(chr(0))
226 return base58_alphabet[0]*(len(bindata) - len(bindata2)) + math.natural_to_string(math.string_to_natural(bindata2), base58_alphabet)
228 def base58_decode(b58data):
229 b58data2 = b58data.lstrip(base58_alphabet[0])
230 return chr(0)*(len(b58data) - len(b58data2)) + math.natural_to_string(math.string_to_natural(b58data2, base58_alphabet))
232 human_address_type = ChecksummedType(pack.ComposedType([
233 ('version', pack.IntType(8)),
234 ('pubkey_hash', pack.IntType(160)),
237 def pubkey_hash_to_address(pubkey_hash, net):
238 return base58_encode(human_address_type.pack(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash)))
240 def pubkey_to_address(pubkey, net):
241 return pubkey_hash_to_address(hash160(pubkey), net)
243 def address_to_pubkey_hash(address, net):
244 x = human_address_type.unpack(base58_decode(address))
245 if x['version'] != net.ADDRESS_VERSION:
246 raise ValueError('address not for this net!')
247 return x['pubkey_hash']
251 def pubkey_to_script2(pubkey):
252 assert len(pubkey) <= 75
253 return (chr(len(pubkey)) + pubkey) + '\xac'
255 def pubkey_hash_to_script2(pubkey_hash):
256 return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
258 def script2_to_address(script2, net):
260 pubkey = script2[1:-1]
261 script2_test = pubkey_to_script2(pubkey)
265 if script2_test == script2:
266 return pubkey_to_address(pubkey, net)
269 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
270 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
274 if script2_test2 == script2:
275 return pubkey_hash_to_address(pubkey_hash, net)
277 def script2_to_human(script2, net):
279 pubkey = script2[1:-1]
280 script2_test = pubkey_to_script2(pubkey)
284 if script2_test == script2:
285 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
288 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
289 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
293 if script2_test2 == script2:
294 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
296 return 'Unknown. Script: %s' % (script2.encode('hex'),)