1 from __future__ import division
7 from p2pool.util import bases, math, expiring_dict, memoize, dicts
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))
85 _backing = expiring_dict.ExpiringDict(100)
86 pack2 = memoize.memoize_with_backing(_backing, [unpack])(pack2)
87 unpack = memoize.memoize_with_backing(_backing)(unpack) # doesn't have an inverse
90 return self.pack2(dicts.immutify(obj))
93 def pack_base58(self, obj):
94 return base58.base58_encode(self.pack(obj))
96 def unpack_base58(self, base58_data):
97 return self.unpack(base58.base58_decode(base58_data))
100 def hash160(self, obj):
101 return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
103 def hash256(self, obj):
104 return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
106 def scrypt(self, obj):
108 return HashType().unpack(ltc_scrypt.getPoWHash(self.pack(obj)))
110 class VarIntType(Type):
111 # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
112 def read(self, file):
113 data, file = read(file, 1)
118 desc, length = '<H', 2
120 desc, length = '<I', 4
122 desc, length = '<Q', 8
124 raise AssertionError()
125 data, file = read(file, length)
126 return struct.unpack(desc, data)[0], file
128 def write(self, file, item):
130 file = file, struct.pack('<B', item)
132 file = file, struct.pack('<BH', 0xfd, item)
133 elif item <= 0xffffffff:
134 file = file, struct.pack('<BI', 0xfe, item)
135 elif item <= 0xffffffffffffffff:
136 file = file, struct.pack('<BQ', 0xff, item)
138 raise ValueError('int too large for varint')
141 class VarStrType(Type):
142 _inner_size = VarIntType()
144 def read(self, file):
145 length, file = self._inner_size.read(file)
146 return read(file, length)
148 def write(self, file, item):
149 return self._inner_size.write(file, len(item)), item
151 class FixedStrType(Type):
152 def __init__(self, length):
155 def read(self, file):
156 return read(file, self.length)
158 def write(self, file, item):
159 if len(item) != self.length:
160 raise ValueError('incorrect length item!')
163 class EnumType(Type):
164 def __init__(self, inner, values):
166 self.values = dicts.frozendict(values)
169 for k, v in values.iteritems():
171 raise ValueError('duplicate value in values')
173 self.keys = dicts.frozendict(keys)
175 def read(self, file):
176 data, file = self.inner.read(file)
177 if data not in self.keys:
178 raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
179 return self.keys[data], file
181 def write(self, file, item):
182 if item not in self.values:
183 raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
184 return self.inner.write(file, self.values[item])
186 class HashType(Type):
187 def read(self, file):
188 data, file = read(file, 256//8)
189 return int(data[::-1].encode('hex'), 16), file
191 def write(self, file, item):
192 if not 0 <= item < 2**256:
193 raise ValueError('invalid hash value - %r' % (item,))
194 if item != 0 and item < 2**160:
195 print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
196 return file, ('%064x' % (item,)).decode('hex')[::-1]
198 class ShortHashType(Type):
199 def read(self, file):
200 data, file = read(file, 160//8)
201 return int(data[::-1].encode('hex'), 16), file
203 def write(self, file, item):
204 if not 0 <= item < 2**160:
205 raise ValueError('invalid hash value - %r' % (item,))
206 return file, ('%040x' % (item,)).decode('hex')[::-1]
208 class ListType(Type):
209 _inner_size = VarIntType()
211 def __init__(self, type):
214 def read(self, file):
215 length, file = self._inner_size.read(file)
217 for i in xrange(length):
218 item, file = self.type.read(file)
222 def write(self, file, item):
223 file = self._inner_size.write(file, len(item))
225 file = self.type.write(file, subitem)
228 class StructType(Type):
229 def __init__(self, desc):
231 self.length = struct.calcsize(self.desc)
233 def read(self, file):
234 data, file = read(file, self.length)
235 res, = struct.unpack(self.desc, data)
238 def write(self, file, item):
239 data = struct.pack(self.desc, item)
240 if struct.unpack(self.desc, data)[0] != item:
241 # special test because struct doesn't error on some overflows
242 raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
245 class IPV6AddressType(Type):
246 def read(self, file):
247 data, file = read(file, 16)
248 if data[:12] != '00000000000000000000ffff'.decode('hex'):
249 raise ValueError('ipv6 addresses not supported yet')
250 return '.'.join(str(ord(x)) for x in data[12:]), file
252 def write(self, file, item):
253 bits = map(int, item.split('.'))
255 raise ValueError('invalid address: %r' % (bits,))
256 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
257 assert len(data) == 16, len(data)
262 def get_record(fields):
263 fields = tuple(sorted(fields))
266 if fields not in _record_types:
267 class _Record(object):
270 return repr(dict(self))
271 def __getitem__(self, key):
272 return getattr(self, key)
273 def __setitem__(self, key, value):
274 setattr(self, key, value)
276 # for field in self.__slots__:
277 # yield field, getattr(self, field)
279 return self.__slots__
280 def __eq__(self, other):
281 if isinstance(other, dict):
282 return dict(self) == other
283 elif isinstance(other, _Record):
284 return all(self[k] == other[k] for k in self.keys())
286 def __ne__(self, other):
287 return not (self == other)
288 _record_types[fields] = _Record
289 return _record_types[fields]()
291 class ComposedType(Type):
292 def __init__(self, fields):
293 self.fields = tuple(fields)
295 def read(self, file):
296 item = get_record(k for k, v in self.fields)
297 for key, type_ in self.fields:
298 item[key], file = type_.read(file)
301 def write(self, file, item):
302 for key, type_ in self.fields:
303 file = type_.write(file, item[key])
306 class ChecksummedType(Type):
307 def __init__(self, inner):
310 def read(self, file):
311 obj, file = self.inner.read(file)
312 data = self.inner.pack(obj)
314 checksum, file = read(file, 4)
315 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
316 raise ValueError('invalid checksum')
320 def write(self, file, item):
321 data = self.inner.pack(item)
322 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
324 class FloatingInteger(object):
325 __slots__ = ['_bits']
328 def from_target_upper_bound(cls, target):
329 n = bases.natural_to_string(target)
330 if n and ord(n[0]) >= 128:
332 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
333 bits = struct.unpack('<I', bits2)[0]
336 def __init__(self, bits):
341 return math.shift_left(self._bits & 0x00ffffff, 8 * ((self._bits >> 24) - 3))
344 return hash(self._value)
346 def __cmp__(self, other):
347 if isinstance(other, FloatingInteger):
348 return cmp(self._value, other._value)
349 elif isinstance(other, (int, long)):
350 return cmp(self._value, other)
352 raise NotImplementedError(other)
358 return 'FloatingInteger(bits=%s (%x))' % (hex(self._bits), self)
360 def __add__(self, other):
361 if isinstance(other, (int, long)):
362 return self._value + other
363 raise NotImplementedError()
365 def __mul__(self, other):
366 if isinstance(other, (int, long)):
367 return self._value * other
368 raise NotImplementedError()
370 def __truediv__(self, other):
371 if isinstance(other, (int, long)):
372 return self._value / other
373 raise NotImplementedError()
374 def __floordiv__(self, other):
375 if isinstance(other, (int, long)):
376 return self._value // other
377 raise NotImplementedError()
378 __div__ = __truediv__
379 def __rtruediv__(self, other):
380 if isinstance(other, (int, long)):
381 return other / self._value
382 raise NotImplementedError()
383 def __rfloordiv__(self, other):
384 if isinstance(other, (int, long)):
385 return other // self._value
386 raise NotImplementedError()
387 __rdiv__ = __rtruediv__
389 class FloatingIntegerType(Type):
390 _inner = StructType('<I')
392 def read(self, file):
393 bits, file = self._inner.read(file)
394 return FloatingInteger(bits), file
396 def write(self, file, item):
397 return self._inner.write(file, item._bits)
399 class PossiblyNoneType(Type):
400 def __init__(self, none_value, inner):
401 self.none_value = none_value
404 def read(self, file):
405 value, file = self.inner.read(file)
406 return None if value == self.none_value else value, file
408 def write(self, file, item):
409 if item == self.none_value:
410 raise ValueError('none_value used')
411 return self.inner.write(file, self.none_value if item is None else item)
413 address_type = ComposedType([
414 ('services', StructType('<Q')),
415 ('address', IPV6AddressType()),
416 ('port', StructType('>H')),
419 tx_type = ComposedType([
420 ('version', StructType('<I')),
421 ('tx_ins', ListType(ComposedType([
422 ('previous_output', PossiblyNoneType(dicts.frozendict(hash=0, index=2**32 - 1), ComposedType([
423 ('hash', HashType()),
424 ('index', StructType('<I')),
426 ('script', VarStrType()),
427 ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
429 ('tx_outs', ListType(ComposedType([
430 ('value', StructType('<Q')),
431 ('script', VarStrType()),
433 ('lock_time', StructType('<I')),
436 merkle_branch_type = ListType(HashType())
438 merkle_tx_type = ComposedType([
440 ('block_hash', HashType()),
441 ('merkle_branch', merkle_branch_type),
442 ('index', StructType('<i')),
445 block_header_type = ComposedType([
446 ('version', StructType('<I')),
447 ('previous_block', PossiblyNoneType(0, HashType())),
448 ('merkle_root', HashType()),
449 ('timestamp', StructType('<I')),
450 ('target', FloatingIntegerType()),
451 ('nonce', StructType('<I')),
454 block_type = ComposedType([
455 ('header', block_header_type),
456 ('txs', ListType(tx_type)),
459 aux_pow_type = ComposedType([
460 ('merkle_tx', merkle_tx_type),
461 ('merkle_branch', merkle_branch_type),
462 ('index', StructType('<i')),
463 ('parent_block_header', block_header_type),
467 merkle_record_type = ComposedType([
468 ('left', HashType()),
469 ('right', HashType()),
472 def merkle_hash(tx_list):
475 hash_list = map(tx_type.hash256, tx_list)
476 while len(hash_list) > 1:
477 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
478 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
481 def calculate_merkle_branch(txs, index):
484 hash_list = [(tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
486 while len(hash_list) > 1:
489 merkle_record_type.hash256(dict(left=left, right=right)),
491 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
493 for (left, left_f, left_l), (right, right_f, right_l) in
494 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
497 res = [x['hash'] for x in hash_list[0][2]]
499 assert hash_list[0][1]
500 assert check_merkle_branch(txs[index], index, res) == hash_list[0][0]
501 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
505 def check_merkle_branch(tx, index, merkle_branch):
506 return reduce(lambda c, (i, h): merkle_record_type.hash256(
507 dict(left=h, right=c) if 2**i & index else
508 dict(left=c, right=h)
509 ), enumerate(merkle_branch), tx_type.hash256(tx))
511 def target_to_average_attempts(target):
512 return 2**256//(target + 1)
514 def target_to_difficulty(target):
515 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
519 def tx_get_sigop_count(tx):
520 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'])
524 human_address_type = ChecksummedType(ComposedType([
525 ('version', StructType('<B')),
526 ('pubkey_hash', ShortHashType()),
529 pubkey_type = FixedStrType(65)
531 def pubkey_hash_to_address(pubkey_hash, net):
532 return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
534 def pubkey_to_address(pubkey, net):
535 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
537 def address_to_pubkey_hash(address, net):
538 x = human_address_type.unpack_base58(address)
539 if x['version'] != net.BITCOIN_ADDRESS_VERSION:
540 raise ValueError('address not for this net!')
541 return x['pubkey_hash']
545 def pubkey_to_script2(pubkey):
546 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
548 def pubkey_hash_to_script2(pubkey_hash):
549 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
551 def script2_to_human(script2, net):
553 pubkey = script2[1:-1]
554 script2_test = pubkey_to_script2(pubkey)
558 if script2_test == script2:
559 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
562 pubkey_hash = ShortHashType().unpack(script2[3:-2])
563 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
567 if script2_test2 == script2:
568 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
570 return 'Unknown. Script: %s' % (script2.encode('hex'),)