1 from __future__ import division
7 from p2pool.util import bases, math
10 class EarlyEnd(Exception):
13 class LateEnd(Exception):
16 def read((data, pos), length):
17 data2 = data[pos:pos + length]
18 if len(data2) != length:
20 return data2, (data, pos + length)
22 def size((data, pos)):
23 return len(data) - pos
26 # the same data can have only one unpacked representation, but multiple packed binary representations
29 rval = getattr(self, '_hash', None)
32 rval = self._hash = hash((type(self), frozenset(self.__dict__.items())))
38 def __eq__(self, other):
39 return type(other) is type(self) and other.__dict__ == self.__dict__
41 def __ne__(self, other):
42 return not (self == other)
44 def _unpack(self, data):
45 obj, (data2, pos) = self.read((data, 0))
55 f = self.write(None, obj)
65 def unpack(self, data):
66 obj = self._unpack(data)
69 data2 = self._pack(obj)
71 if self._unpack(data2) != obj:
72 raise AssertionError()
77 data = self._pack(obj)
80 if self._unpack(data) != obj:
81 raise AssertionError((self._unpack(data), obj))
86 def pack_base58(self, obj):
87 return base58.encode(self.pack(obj))
89 def unpack_base58(self, base58_data):
90 return self.unpack(base58.decode(base58_data))
93 def hash160(self, obj):
94 return IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
96 def hash256(self, obj):
97 return IntType(256).unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
99 def scrypt(self, obj):
101 return IntType(256).unpack(ltc_scrypt.getPoWHash(self.pack(obj)))
103 class VarIntType(Type):
104 # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
105 def read(self, file):
106 data, file = read(file, 1)
111 desc, length = '<H', 2
113 desc, length = '<I', 4
115 desc, length = '<Q', 8
117 raise AssertionError()
118 data, file = read(file, length)
119 return struct.unpack(desc, data)[0], file
121 def write(self, file, item):
123 file = file, struct.pack('<B', item)
125 file = file, struct.pack('<BH', 0xfd, item)
126 elif item <= 0xffffffff:
127 file = file, struct.pack('<BI', 0xfe, item)
128 elif item <= 0xffffffffffffffff:
129 file = file, struct.pack('<BQ', 0xff, item)
131 raise ValueError('int too large for varint')
134 class VarStrType(Type):
135 _inner_size = VarIntType()
137 def read(self, file):
138 length, file = self._inner_size.read(file)
139 return read(file, length)
141 def write(self, file, item):
142 return self._inner_size.write(file, len(item)), item
144 class PassthruType(Type):
145 def read(self, file):
146 return read(file, size(file))
148 def write(self, file, item):
151 class EnumType(Type):
152 def __init__(self, inner, values):
157 for k, v in values.iteritems():
159 raise ValueError('duplicate value in values')
163 def read(self, file):
164 data, file = self.inner.read(file)
165 if data not in self.keys:
166 raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
167 return self.keys[data], file
169 def write(self, file, item):
170 if item not in self.values:
171 raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
172 return self.inner.write(file, self.values[item])
174 class ListType(Type):
175 _inner_size = VarIntType()
177 def __init__(self, type):
180 def read(self, file):
181 length, file = self._inner_size.read(file)
183 for i in xrange(length):
184 item, file = self.type.read(file)
188 def write(self, file, item):
189 file = self._inner_size.write(file, len(item))
191 file = self.type.write(file, subitem)
194 class StructType(Type):
195 def __init__(self, desc):
197 self.length = struct.calcsize(self.desc)
199 def read(self, file):
200 data, file = read(file, self.length)
201 return struct.unpack(self.desc, data)[0], file
203 def write(self, file, item):
204 return file, struct.pack(self.desc, item)
207 def __new__(cls, bits, endianness='little'):
209 assert endianness in ['little', 'big']
210 if bits in [8, 16, 32, 64]:
211 return StructType(('<' if endianness == 'little' else '>') + {8: 'B', 16: 'H', 32: 'I', 64: 'Q'}[bits])
213 return object.__new__(cls, bits, endianness)
215 def __init__(self, bits, endianness='little'):
217 assert endianness in ['little', 'big']
219 self.step = -1 if endianness == 'little' else 1
221 def read(self, file):
222 data, file = read(file, self.bytes)
223 return int(data[::self.step].encode('hex'), 16), file
225 def write(self, file, item):
226 if not 0 <= item < 2**(8*self.bytes):
227 raise ValueError('invalid int value - %r' % (item,))
228 return file, ('%x' % (item,)).zfill(2*self.bytes).decode('hex')[::self.step]
230 class IPV6AddressType(Type):
231 def read(self, file):
232 data, file = read(file, 16)
233 if data[:12] != '00000000000000000000ffff'.decode('hex'):
234 raise ValueError('ipv6 addresses not supported yet')
235 return '.'.join(str(ord(x)) for x in data[12:]), file
237 def write(self, file, item):
238 bits = map(int, item.split('.'))
240 raise ValueError('invalid address: %r' % (bits,))
241 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
242 assert len(data) == 16, len(data)
247 def get_record(fields):
248 fields = tuple(sorted(fields))
251 if fields not in _record_types:
252 class _Record(object):
255 return repr(dict(self))
256 def __getitem__(self, key):
257 return getattr(self, key)
258 def __setitem__(self, key, value):
259 setattr(self, key, value)
261 # for field in self.__slots__:
262 # yield field, getattr(self, field)
264 return self.__slots__
265 def __eq__(self, other):
266 if isinstance(other, dict):
267 return dict(self) == other
268 elif isinstance(other, _Record):
269 return all(self[k] == other[k] for k in self.keys())
271 def __ne__(self, other):
272 return not (self == other)
273 _record_types[fields] = _Record
274 return _record_types[fields]()
276 class ComposedType(Type):
277 def __init__(self, fields):
278 self.fields = tuple(fields)
280 def read(self, file):
281 item = get_record(k for k, v in self.fields)
282 for key, type_ in self.fields:
283 item[key], file = type_.read(file)
286 def write(self, file, item):
287 for key, type_ in self.fields:
288 file = type_.write(file, item[key])
291 class ChecksummedType(Type):
292 def __init__(self, inner):
295 def read(self, file):
296 obj, file = self.inner.read(file)
297 data = self.inner.pack(obj)
299 checksum, file = read(file, 4)
300 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
301 raise ValueError('invalid checksum')
305 def write(self, file, item):
306 data = self.inner.pack(item)
307 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
309 class FloatingInteger(object):
310 __slots__ = ['bits', '_target']
313 def from_target_upper_bound(cls, target):
314 n = bases.natural_to_string(target)
315 if n and ord(n[0]) >= 128:
317 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
318 bits = struct.unpack('<I', bits2)[0]
321 def __init__(self, bits, target=None):
324 if target is not None and self.target != target:
325 raise ValueError('target does not match')
331 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
335 return hash(self.bits)
337 def __eq__(self, other):
338 return self.bits == other.bits
340 def __ne__(self, other):
341 return not (self == other)
343 def __cmp__(self, other):
347 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
349 class FloatingIntegerType(Type):
352 def read(self, file):
353 bits, file = self._inner.read(file)
354 return FloatingInteger(bits), file
356 def write(self, file, item):
357 return self._inner.write(file, item.bits)
359 class PossiblyNoneType(Type):
360 def __init__(self, none_value, inner):
361 self.none_value = none_value
364 def read(self, file):
365 value, file = self.inner.read(file)
366 return None if value == self.none_value else value, file
368 def write(self, file, item):
369 if item == self.none_value:
370 raise ValueError('none_value used')
371 return self.inner.write(file, self.none_value if item is None else item)
373 address_type = ComposedType([
374 ('services', IntType(64)),
375 ('address', IPV6AddressType()),
376 ('port', IntType(16, 'big')),
379 tx_type = ComposedType([
380 ('version', IntType(32)),
381 ('tx_ins', ListType(ComposedType([
382 ('previous_output', PossiblyNoneType(dict(hash=0, index=2**32 - 1), ComposedType([
383 ('hash', IntType(256)),
384 ('index', IntType(32)),
386 ('script', VarStrType()),
387 ('sequence', PossiblyNoneType(2**32 - 1, IntType(32))),
389 ('tx_outs', ListType(ComposedType([
390 ('value', IntType(64)),
391 ('script', VarStrType()),
393 ('lock_time', IntType(32)),
396 merkle_branch_type = ListType(IntType(256))
398 merkle_tx_type = ComposedType([
400 ('block_hash', IntType(256)),
401 ('merkle_branch', merkle_branch_type),
402 ('index', IntType(32)),
405 block_header_type = ComposedType([
406 ('version', IntType(32)),
407 ('previous_block', PossiblyNoneType(0, IntType(256))),
408 ('merkle_root', IntType(256)),
409 ('timestamp', IntType(32)),
410 ('bits', FloatingIntegerType()),
411 ('nonce', IntType(32)),
414 block_type = ComposedType([
415 ('header', block_header_type),
416 ('txs', ListType(tx_type)),
419 aux_pow_type = ComposedType([
420 ('merkle_tx', merkle_tx_type),
421 ('merkle_branch', merkle_branch_type),
422 ('index', IntType(32)),
423 ('parent_block_header', block_header_type),
427 merkle_record_type = ComposedType([
428 ('left', IntType(256)),
429 ('right', IntType(256)),
432 def merkle_hash(hashes):
435 hash_list = list(hashes)
436 while len(hash_list) > 1:
437 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
438 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
441 def calculate_merkle_branch(hashes, index):
444 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
446 while len(hash_list) > 1:
449 merkle_record_type.hash256(dict(left=left, right=right)),
451 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
453 for (left, left_f, left_l), (right, right_f, right_l) in
454 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
457 res = [x['hash'] for x in hash_list[0][2]]
459 assert hash_list[0][1]
460 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
461 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
465 def check_merkle_branch(tip_hash, index, merkle_branch):
466 return reduce(lambda c, (i, h): merkle_record_type.hash256(
467 dict(left=h, right=c) if 2**i & index else
468 dict(left=c, right=h)
469 ), enumerate(merkle_branch), tip_hash)
471 def target_to_average_attempts(target):
472 return 2**256//(target + 1)
474 def target_to_difficulty(target):
475 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
479 def tx_get_sigop_count(tx):
480 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'])
484 human_address_type = ChecksummedType(ComposedType([
485 ('version', IntType(8)),
486 ('pubkey_hash', IntType(160)),
489 pubkey_type = PassthruType()
491 def pubkey_hash_to_address(pubkey_hash, net):
492 return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
494 def pubkey_to_address(pubkey, net):
495 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
497 def address_to_pubkey_hash(address, net):
498 x = human_address_type.unpack_base58(address)
499 if x['version'] != net.ADDRESS_VERSION:
500 raise ValueError('address not for this net!')
501 return x['pubkey_hash']
505 def pubkey_to_script2(pubkey):
506 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
508 def pubkey_hash_to_script2(pubkey_hash):
509 return '\x76\xa9' + ('\x14' + IntType(160).pack(pubkey_hash)) + '\x88\xac'
511 def script2_to_address(script2, net):
513 pubkey = script2[1:-1]
514 script2_test = pubkey_to_script2(pubkey)
518 if script2_test == script2:
519 return pubkey_to_address(pubkey, net)
522 pubkey_hash = IntType(160).unpack(script2[3:-2])
523 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
527 if script2_test2 == script2:
528 return pubkey_hash_to_address(pubkey_hash, net)
530 def script2_to_human(script2, net):
532 pubkey = script2[1:-1]
533 script2_test = pubkey_to_script2(pubkey)
537 if script2_test == script2:
538 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
541 pubkey_hash = IntType(160).unpack(script2[3:-2])
542 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
546 if script2_test2 == script2:
547 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
549 return 'Unknown. Script: %s' % (script2.encode('hex'),)