1 from __future__ import division
7 from p2pool.util import bases, math, expiring_dict, memoize, slush
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(slush.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 = slush.frozendict(values)
169 for k, v in values.iteritems():
171 raise ValueError('duplicate value in values')
173 self.keys = slush.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', '_target']
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, target=None):
339 if target is not None and self.target != target:
340 raise ValueError('target does not match')
346 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
350 return hash(self.bits)
352 def __eq__(self, other):
353 return self.bits == other.bits
355 def __ne__(self, other):
356 return not (self == other)
358 def __cmp__(self, other):
362 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
364 class FloatingIntegerType(Type):
365 _inner = StructType('<I')
367 def read(self, file):
368 bits, file = self._inner.read(file)
369 return FloatingInteger(bits), file
371 def write(self, file, item):
372 return self._inner.write(file, item.bits)
374 class PossiblyNoneType(Type):
375 def __init__(self, none_value, inner):
376 self.none_value = none_value
379 def read(self, file):
380 value, file = self.inner.read(file)
381 return None if value == self.none_value else value, file
383 def write(self, file, item):
384 if item == self.none_value:
385 raise ValueError('none_value used')
386 return self.inner.write(file, self.none_value if item is None else item)
388 address_type = ComposedType([
389 ('services', StructType('<Q')),
390 ('address', IPV6AddressType()),
391 ('port', StructType('>H')),
394 tx_type = ComposedType([
395 ('version', StructType('<I')),
396 ('tx_ins', ListType(ComposedType([
397 ('previous_output', PossiblyNoneType(slush.frozendict(hash=0, index=2**32 - 1), ComposedType([
398 ('hash', HashType()),
399 ('index', StructType('<I')),
401 ('script', VarStrType()),
402 ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
404 ('tx_outs', ListType(ComposedType([
405 ('value', StructType('<Q')),
406 ('script', VarStrType()),
408 ('lock_time', StructType('<I')),
411 merkle_branch_type = ListType(HashType())
413 merkle_tx_type = ComposedType([
415 ('block_hash', HashType()),
416 ('merkle_branch', merkle_branch_type),
417 ('index', StructType('<i')),
420 block_header_type = ComposedType([
421 ('version', StructType('<I')),
422 ('previous_block', PossiblyNoneType(0, HashType())),
423 ('merkle_root', HashType()),
424 ('timestamp', StructType('<I')),
425 ('bits', FloatingIntegerType()),
426 ('nonce', StructType('<I')),
429 block_type = ComposedType([
430 ('header', block_header_type),
431 ('txs', ListType(tx_type)),
434 aux_pow_type = ComposedType([
435 ('merkle_tx', merkle_tx_type),
436 ('merkle_branch', merkle_branch_type),
437 ('index', StructType('<i')),
438 ('parent_block_header', block_header_type),
442 merkle_record_type = ComposedType([
443 ('left', HashType()),
444 ('right', HashType()),
447 def merkle_hash(hashes):
450 hash_list = list(hashes)
451 while len(hash_list) > 1:
452 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
453 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
456 def calculate_merkle_branch(hashes, index):
459 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
461 while len(hash_list) > 1:
464 merkle_record_type.hash256(dict(left=left, right=right)),
466 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
468 for (left, left_f, left_l), (right, right_f, right_l) in
469 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
472 res = [x['hash'] for x in hash_list[0][2]]
474 assert hash_list[0][1]
475 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
476 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
480 def check_merkle_branch(tip_hash, index, merkle_branch):
481 return reduce(lambda c, (i, h): merkle_record_type.hash256(
482 dict(left=h, right=c) if 2**i & index else
483 dict(left=c, right=h)
484 ), enumerate(merkle_branch), tip_hash)
486 def target_to_average_attempts(target):
487 return 2**256//(target + 1)
489 def target_to_difficulty(target):
490 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
494 def tx_get_sigop_count(tx):
495 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'])
499 human_address_type = ChecksummedType(ComposedType([
500 ('version', StructType('<B')),
501 ('pubkey_hash', ShortHashType()),
504 pubkey_type = FixedStrType(65)
506 def pubkey_hash_to_address(pubkey_hash, net):
507 return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
509 def pubkey_to_address(pubkey, net):
510 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
512 def address_to_pubkey_hash(address, net):
513 x = human_address_type.unpack_base58(address)
514 if x['version'] != net.ADDRESS_VERSION:
515 raise ValueError('address not for this net!')
516 return x['pubkey_hash']
520 def pubkey_to_script2(pubkey):
521 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
523 def pubkey_hash_to_script2(pubkey_hash):
524 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
526 def script2_to_human(script2, net):
528 pubkey = script2[1:-1]
529 script2_test = pubkey_to_script2(pubkey)
533 if script2_test == script2:
534 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
537 pubkey_hash = ShortHashType().unpack(script2[3:-2])
538 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
542 if script2_test2 == script2:
543 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
545 return 'Unknown. Script: %s' % (script2.encode('hex'),)