1 from __future__ import division
7 from p2pool.util import math, pack
10 return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
13 if data == '04ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664b'.decode('hex'):
14 return 0x384f570ccc88ac2e7e00b026d1690a3fca63dd0 # hack for people who don't have openssl - this is the only value that p2pool ever hashes
15 return pack.IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(data).digest()).digest())
17 class ChecksummedType(pack.Type):
18 def __init__(self, inner, checksum_func=lambda data: hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]):
20 self.checksum_func = checksum_func
23 obj, file = self.inner.read(file)
24 data = self.inner.pack(obj)
26 calculated_checksum = self.checksum_func(data)
27 checksum, file = pack.read(file, len(calculated_checksum))
28 if checksum != calculated_checksum:
29 raise ValueError('invalid checksum')
33 def write(self, file, item):
34 data = self.inner.pack(item)
35 return (file, data), self.checksum_func(data)
37 class FloatingInteger(object):
38 __slots__ = ['bits', '_target']
41 def from_target_upper_bound(cls, target):
42 n = math.natural_to_string(target)
43 if n and ord(n[0]) >= 128:
45 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
46 bits = pack.IntType(32).unpack(bits2)
49 def __init__(self, bits, target=None):
52 if target is not None and self.target != target:
53 raise ValueError('target does not match')
59 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
63 return hash(self.bits)
65 def __eq__(self, other):
66 return self.bits == other.bits
68 def __ne__(self, other):
69 return not (self == other)
71 def __cmp__(self, other):
75 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
77 class FloatingIntegerType(pack.Type):
78 _inner = pack.IntType(32)
81 bits, file = self._inner.read(file)
82 return FloatingInteger(bits), file
84 def write(self, file, item):
85 return self._inner.write(file, item.bits)
87 address_type = pack.ComposedType([
88 ('services', pack.IntType(64)),
89 ('address', pack.IPV6AddressType()),
90 ('port', pack.IntType(16, 'big')),
93 tx_type = pack.ComposedType([
94 ('version', pack.IntType(32)),
95 ('timestamp', pack.IntType(32)),
96 ('tx_ins', pack.ListType(pack.ComposedType([
97 ('previous_output', pack.PossiblyNoneType(dict(hash=0, index=2**32 - 1), pack.ComposedType([
98 ('hash', pack.IntType(256)),
99 ('index', pack.IntType(32)),
101 ('script', pack.VarStrType()),
102 ('sequence', pack.PossiblyNoneType(2**32 - 1, pack.IntType(32))),
104 ('tx_outs', pack.ListType(pack.ComposedType([
105 ('value', pack.IntType(64)),
106 ('script', pack.VarStrType()),
108 ('lock_time', pack.IntType(32)),
111 merkle_link_type = pack.ComposedType([
112 ('branch', pack.ListType(pack.IntType(256))),
113 ('index', pack.IntType(32)),
116 merkle_tx_type = pack.ComposedType([
118 ('block_hash', pack.IntType(256)),
119 ('merkle_link', merkle_link_type),
122 block_header_type = pack.ComposedType([
123 ('version', pack.IntType(32)),
124 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
125 ('merkle_root', pack.IntType(256)),
126 ('timestamp', pack.IntType(32)),
127 ('bits', FloatingIntegerType()),
128 ('nonce', pack.IntType(32)),
131 block_type = pack.ComposedType([
132 ('header', block_header_type),
133 ('txs', pack.ListType(tx_type)),
134 ('signature', pack.VarStrType()),
139 aux_pow_type = pack.ComposedType([
140 ('merkle_tx', merkle_tx_type),
141 ('merkle_link', merkle_link_type),
142 ('parent_block_header', block_header_type),
145 aux_pow_coinbase_type = pack.ComposedType([
146 ('merkle_root', pack.IntType(256, 'big')),
147 ('size', pack.IntType(32)),
148 ('nonce', pack.IntType(32)),
151 def make_auxpow_tree(chain_ids):
152 for size in (2**i for i in xrange(31)):
153 if size < len(chain_ids):
156 for chain_id in chain_ids:
157 pos = (1103515245 * chain_id + 1103515245 * 12345 + 12345) % size
163 raise AssertionError()
167 merkle_record_type = pack.ComposedType([
168 ('left', pack.IntType(256)),
169 ('right', pack.IntType(256)),
172 def merkle_hash(hashes):
175 hash_list = list(hashes)
176 while len(hash_list) > 1:
177 hash_list = [hash256(merkle_record_type.pack(dict(left=left, right=right)))
178 for left, right in zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])]
181 def calculate_merkle_link(hashes, index):
184 hash_list = [(lambda _h=h: _h, i == index, []) for i, h in enumerate(hashes)]
186 while len(hash_list) > 1:
189 lambda _left=left, _right=right: hash256(merkle_record_type.pack(dict(left=_left(), right=_right()))),
191 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
193 for (left, left_f, left_l), (right, right_f, right_l) in
194 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
197 res = [x['hash']() for x in hash_list[0][2]]
199 assert hash_list[0][1]
201 new_hashes = [random.randrange(2**256) if x is None else x
203 assert check_merkle_link(new_hashes[index], dict(branch=res, index=index)) == merkle_hash(new_hashes)
204 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
206 return dict(branch=res, index=index)
208 def check_merkle_link(tip_hash, link):
209 if link['index'] >= 2**len(link['branch']):
210 raise ValueError('index too large')
211 return reduce(lambda c, (i, h): hash256(merkle_record_type.pack(
212 dict(left=h, right=c) if (link['index'] >> i) & 1 else
213 dict(left=c, right=h)
214 )), enumerate(link['branch']), tip_hash)
218 def target_to_average_attempts(target):
219 return 2**256//(target + 1)
221 def target_to_difficulty(target):
222 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
224 def difficulty_to_target(difficulty):
225 return (0xffff0000 * 2**(256-64) + 1)/difficulty - 1
229 base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
231 def base58_encode(bindata):
232 bindata2 = bindata.lstrip(chr(0))
233 return base58_alphabet[0]*(len(bindata) - len(bindata2)) + math.natural_to_string(math.string_to_natural(bindata2), base58_alphabet)
235 def base58_decode(b58data):
236 b58data2 = b58data.lstrip(base58_alphabet[0])
237 return chr(0)*(len(b58data) - len(b58data2)) + math.natural_to_string(math.string_to_natural(b58data2, base58_alphabet))
239 human_address_type = ChecksummedType(pack.ComposedType([
240 ('version', pack.IntType(8)),
241 ('pubkey_hash', pack.IntType(160)),
244 def pubkey_hash_to_address(pubkey_hash, net):
245 return base58_encode(human_address_type.pack(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash)))
247 def pubkey_to_address(pubkey, net):
248 return pubkey_hash_to_address(hash160(pubkey), net)
250 def address_to_pubkey_hash(address, net):
251 x = human_address_type.unpack(base58_decode(address))
252 if x['version'] != net.ADDRESS_VERSION:
253 raise ValueError('address not for this net!')
254 return x['pubkey_hash']
258 def pubkey_to_script2(pubkey):
259 assert len(pubkey) <= 75
260 return (chr(len(pubkey)) + pubkey) + '\xac'
262 def pubkey_hash_to_script2(pubkey_hash):
263 return '\x76\xa9' + ('\x14' + pack.IntType(160).pack(pubkey_hash)) + '\x88\xac'
265 def script2_to_address(script2, net):
267 pubkey = script2[1:-1]
268 script2_test = pubkey_to_script2(pubkey)
272 if script2_test == script2:
273 return pubkey_to_address(pubkey, net)
276 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
277 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
281 if script2_test2 == script2:
282 return pubkey_hash_to_address(pubkey_hash, net)
284 def script2_to_human(script2, net):
286 pubkey = script2[1:-1]
287 script2_test = pubkey_to_script2(pubkey)
291 if script2_test == script2:
292 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
295 pubkey_hash = pack.IntType(160).unpack(script2[3:-2])
296 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
300 if script2_test2 == script2:
301 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
303 return 'Unknown. Script: %s' % (script2.encode('hex'),)