1 from __future__ import division
7 from . import base58, skiplists
8 from p2pool.util import bases, math, skiplist
11 class EarlyEnd(Exception):
14 class LateEnd(Exception):
17 def read((data, pos), length):
18 data2 = data[pos:pos + length]
19 if len(data2) != length:
21 return data2, (data, pos + length)
23 def size((data, pos)):
24 return len(data) - pos
27 # the same data can have only one unpacked representation, but multiple packed binary representations
30 # return hash(tuple(self.__dict__.items()))
32 #def __eq__(self, other):
33 # if not isinstance(other, Type):
34 # raise NotImplementedError()
35 # return self.__dict__ == other.__dict__
37 def _unpack(self, data):
38 obj, (data2, pos) = self.read((data, 0))
48 f = self.write(None, obj)
58 def unpack(self, data):
59 obj = self._unpack(data)
62 data2 = self._pack(obj)
64 if self._unpack(data2) != obj:
65 raise AssertionError()
70 data = self._pack(obj)
73 if self._unpack(data) != obj:
74 raise AssertionError()
79 def pack_base58(self, obj):
80 return base58.base58_encode(self.pack(obj))
82 def unpack_base58(self, base58_data):
83 return self.unpack(base58.base58_decode(base58_data))
86 def hash160(self, obj):
87 return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
89 def hash256(self, obj):
90 return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
92 class VarIntType(Type):
93 # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
95 data, file = read(file, 1)
100 desc, length = '<H', 2
102 desc, length = '<I', 4
104 desc, length = '<Q', 8
106 raise AssertionError()
107 data, file = read(file, length)
108 return struct.unpack(desc, data)[0], file
110 def write(self, file, item):
112 file = file, struct.pack('<B', item)
114 file = file, struct.pack('<BH', 0xfd, item)
115 elif item <= 0xffffffff:
116 file = file, struct.pack('<BI', 0xfe, item)
117 elif item <= 0xffffffffffffffff:
118 file = file, struct.pack('<BQ', 0xff, item)
120 raise ValueError('int too large for varint')
123 class VarStrType(Type):
124 _inner_size = VarIntType()
126 def read(self, file):
127 length, file = self._inner_size.read(file)
128 return read(file, length)
130 def write(self, file, item):
131 return self._inner_size.write(file, len(item)), item
133 class FixedStrType(Type):
134 def __init__(self, length):
137 def read(self, file):
138 return read(file, self.length)
140 def write(self, file, item):
141 if len(item) != self.length:
142 raise ValueError('incorrect length item!')
145 class EnumType(Type):
146 def __init__(self, inner, values):
151 for k, v in values.iteritems():
153 raise ValueError('duplicate value in values')
156 def read(self, file):
157 data, file = self.inner.read(file)
158 return self.keys[data], file
160 def write(self, file, item):
161 return self.inner.write(file, self.values[item])
163 class HashType(Type):
164 def read(self, file):
165 data, file = read(file, 256//8)
166 return int(data[::-1].encode('hex'), 16), file
168 def write(self, file, item):
169 if not 0 <= item < 2**256:
170 raise ValueError('invalid hash value - %r' % (item,))
171 if item != 0 and item < 2**160:
172 print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
173 return file, ('%064x' % (item,)).decode('hex')[::-1]
175 class ShortHashType(Type):
176 def read(self, file):
177 data, file = read(file, 160//8)
178 return int(data[::-1].encode('hex'), 16), file
180 def write(self, file, item):
181 if not 0 <= item < 2**160:
182 raise ValueError('invalid hash value - %r' % (item,))
183 return file, ('%040x' % (item,)).decode('hex')[::-1]
185 class ListType(Type):
186 _inner_size = VarIntType()
188 def __init__(self, type):
191 def read(self, file):
192 length, file = self._inner_size.read(file)
194 for i in xrange(length):
195 item, file = self.type.read(file)
199 def write(self, file, item):
200 file = self._inner_size.write(file, len(item))
202 file = self.type.write(file, subitem)
205 class StructType(Type):
206 def __init__(self, desc):
208 self.length = struct.calcsize(self.desc)
210 def read(self, file):
211 data, file = read(file, self.length)
212 res, = struct.unpack(self.desc, data)
215 def write(self, file, item):
216 data = struct.pack(self.desc, item)
217 if struct.unpack(self.desc, data)[0] != item:
218 # special test because struct doesn't error on some overflows
219 raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
222 class IPV6AddressType(Type):
223 def read(self, file):
224 data, file = read(file, 16)
225 if data[:12] != '00000000000000000000ffff'.decode('hex'):
226 raise ValueError('ipv6 addresses not supported yet')
227 return '.'.join(str(ord(x)) for x in data[12:]), file
229 def write(self, file, item):
230 bits = map(int, item.split('.'))
232 raise ValueError('invalid address: %r' % (bits,))
233 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
234 assert len(data) == 16, len(data)
239 def get_record(fields):
240 fields = tuple(sorted(fields))
243 if fields not in _record_types:
244 class _Record(object):
246 def __getitem__(self, key):
247 return getattr(self, key)
248 def __setitem__(self, key, value):
249 setattr(self, key, value)
251 # for field in self.__slots__:
252 # yield field, getattr(self, field)
254 return self.__slots__
255 def __eq__(self, other):
256 if isinstance(other, dict):
257 return dict(self) == other
258 elif isinstance(other, _Record):
259 return all(self[k] == other[k] for k in self.keys())
261 def __ne__(self, other):
262 return not (self == other)
263 _record_types[fields] = _Record
264 return _record_types[fields]()
266 class ComposedType(Type):
267 def __init__(self, fields):
270 def read(self, file):
271 item = get_record(k for k, v in self.fields)
272 for key, type_ in self.fields:
273 item[key], file = type_.read(file)
276 def write(self, file, item):
277 for key, type_ in self.fields:
278 file = type_.write(file, item[key])
281 class ChecksummedType(Type):
282 def __init__(self, inner):
285 def read(self, file):
286 obj, file = self.inner.read(file)
287 data = self.inner.pack(obj)
289 checksum, file = read(file, 4)
290 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
291 raise ValueError('invalid checksum')
295 def write(self, file, item):
296 data = self.inner.pack(item)
297 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
299 class FloatingIntegerType(Type):
300 # redundancy doesn't matter here because bitcoin checks binary bits against its own computed bits
301 # so it will always be encoded 'normally' in blocks (they way bitcoin does it)
302 _inner = StructType('<I')
304 def read(self, file):
305 bits, file = self._inner.read(file)
306 target = self._bits_to_target(bits)
308 if self._target_to_bits(target) != bits:
309 raise ValueError('bits in non-canonical form')
312 def write(self, file, item):
313 return self._inner.write(file, self._target_to_bits(item))
315 def truncate_to(self, x):
316 return self._bits_to_target(self._target_to_bits(x, _check=False))
318 def _bits_to_target(self, bits2):
319 target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
321 assert target == self._bits_to_target1(struct.pack('<I', bits2))
322 assert self._target_to_bits(target, _check=False) == bits2
325 def _bits_to_target1(self, bits):
327 length = ord(bits[0])
328 return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
330 def _target_to_bits(self, target, _check=True):
331 n = bases.natural_to_string(target)
332 if n and ord(n[0]) >= 128:
334 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
335 bits = struct.unpack('<I', bits2)[0]
337 if self._bits_to_target(bits) != target:
338 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
341 class PossiblyNone(Type):
342 def __init__(self, none_value, inner):
343 self.none_value = none_value
346 def read(self, file):
347 value, file = self.inner.read(file)
348 return None if value == self.none_value else value, file
350 def write(self, file, item):
351 if item == self.none_value:
352 raise ValueError('none_value used')
353 return self.inner.write(file, self.none_value if item is None else item)
355 address_type = ComposedType([
356 ('services', StructType('<Q')),
357 ('address', IPV6AddressType()),
358 ('port', StructType('>H')),
361 tx_type = ComposedType([
362 ('version', StructType('<I')),
363 ('tx_ins', ListType(ComposedType([
364 ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
365 ('hash', HashType()),
366 ('index', StructType('<I')),
368 ('script', VarStrType()),
369 ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
371 ('tx_outs', ListType(ComposedType([
372 ('value', StructType('<Q')),
373 ('script', VarStrType()),
375 ('lock_time', StructType('<I')),
378 block_header_type = ComposedType([
379 ('version', StructType('<I')),
380 ('previous_block', PossiblyNone(0, HashType())),
381 ('merkle_root', HashType()),
382 ('timestamp', StructType('<I')),
383 ('target', FloatingIntegerType()),
384 ('nonce', StructType('<I')),
387 block_type = ComposedType([
388 ('header', block_header_type),
389 ('txs', ListType(tx_type)),
393 merkle_record_type = ComposedType([
394 ('left', HashType()),
395 ('right', HashType()),
398 def merkle_hash(tx_list):
401 hash_list = map(tx_type.hash256, tx_list)
402 while len(hash_list) > 1:
403 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
404 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
407 def target_to_average_attempts(target):
408 return 2**256//(target + 1)
412 def tx_get_sigop_count(tx):
413 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'])
417 human_address_type = ChecksummedType(ComposedType([
418 ('version', StructType('<B')),
419 ('pubkey_hash', ShortHashType()),
422 pubkey_type = FixedStrType(65)
424 def pubkey_hash_to_address(pubkey_hash, net):
425 return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
427 def pubkey_to_address(pubkey, net):
428 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
430 def address_to_pubkey_hash(address, net):
431 x = human_address_type.unpack_base58(address)
432 if x['version'] != net.BITCOIN_ADDRESS_VERSION:
433 raise ValueError('address not for this net!')
434 return x['pubkey_hash']
438 def pubkey_to_script2(pubkey):
439 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
441 def pubkey_hash_to_script2(pubkey_hash):
442 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
444 # linked list tracker
446 class Tracker(object):
448 self.shares = {} # hash -> share
449 #self.ids = {} # hash -> (id, height)
450 self.reverse_shares = {} # previous_hash -> set of share_hashes
452 self.heads = {} # head hash -> tail_hash
453 self.tails = {} # tail hash -> set of head hashes
455 self.heights = {} # share_hash -> height_to, other_share_hash
458 self.id_generator = itertools.count()
459 self.tails_by_id = {}
462 self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
464 def add(self, share):
465 assert not isinstance(share, (int, long, type(None)))
466 if share.hash in self.shares:
467 return # XXX raise exception?
470 parent_id = self.ids.get(share.previous_hash, None)
471 children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
473 if parent_id is not None:
474 infos.add((parent_id[0], parent_id[1] + 1))
475 for child_id in children_ids:
476 infos.add((child_id[0], child_id[1] - 1))
478 infos.add((self.id_generator.next(), 0))
480 self.ids[share.hash] = chosen
483 self.shares[share.hash] = share
484 self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
486 if share.hash in self.tails:
487 heads = self.tails.pop(share.hash)
489 heads = set([share.hash])
491 if share.previous_hash in self.heads:
492 tail = self.heads.pop(share.previous_hash)
494 #dist, tail = self.get_height_and_last(share.previous_hash) # XXX this should be moved out of the critical area even though it shouldn't matter
495 tail = share.previous_hash
496 while tail in self.shares:
497 tail = self.shares[tail].previous_hash
499 self.tails.setdefault(tail, set()).update(heads)
500 if share.previous_hash in self.tails[tail]:
501 self.tails[tail].remove(share.previous_hash)
504 self.heads[head] = tail
508 for s in self.shares.itervalues():
511 assert self.shares == t.shares, (self.shares, t.shares)
512 assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
513 assert self.heads == t.heads, (self.heads, t.heads)
514 assert self.tails == t.tails, (self.tails, t.tails)
516 def remove(self, share_hash):
517 assert isinstance(share_hash, (int, long, type(None)))
518 if share_hash not in self.shares:
520 share = self.shares[share_hash]
523 if share.hash in self.heads and share.previous_hash in self.tails:
524 tail = self.heads.pop(share.hash)
525 self.tails[tail].remove(share.hash)
526 if not self.tails[share.previous_hash]:
527 self.tails.pop(share.previous_hash)
528 elif share.hash in self.heads:
529 tail = self.heads.pop(share.hash)
530 self.tails[tail].remove(share.hash)
531 if self.reverse_shares[share.previous_hash] != set([share.hash]):
534 self.tails[tail].add(share.previous_hash)
535 self.heads[share.previous_hash] = tail
536 elif share.previous_hash in self.tails:
537 raise NotImplementedError() # will break other things..
538 heads = self.tails[share.previous_hash]
539 if len(self.reverse_shares[share.previous_hash]) > 1:
540 raise NotImplementedError()
542 del self.tails[share.previous_hash]
544 self.heads[head] = share.hash
545 self.tails[share.hash] = set(heads)
547 raise NotImplementedError()
550 height, tail = self.get_height_and_last(share.hash)
552 if share.hash in self.heads:
553 my_heads = set([share.hash])
554 elif share.previous_hash in self.tails:
555 my_heads = self.tails[share.previous_hash]
557 some_heads = self.tails[tail]
558 some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
559 my_heads = set(that_head for that_head in some_heads
560 if some_heads_heights[that_head] > height and
561 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
563 if share.previous_hash != tail:
564 self.heads[share.previous_hash] = tail
566 for head in my_heads:
567 if head != share.hash:
568 self.heads[head] = share.hash
572 if share.hash in self.heads:
573 self.heads.pop(share.hash)
576 self.tails[tail].difference_update(my_heads)
577 if share.previous_hash != tail:
578 self.tails[tail].add(share.previous_hash)
579 if not self.tails[tail]:
581 if my_heads != set([share.hash]):
582 self.tails[share.hash] = set(my_heads) - set([share.hash])
585 self.shares.pop(share.hash)
586 self.reverse_shares[share.previous_hash].remove(share.hash)
587 if not self.reverse_shares[share.previous_hash]:
588 self.reverse_shares.pop(share.previous_hash)
590 #assert self.test() is None
592 def get_height(self, share_hash):
593 height, work, last = self.get_height_work_and_last(share_hash)
596 def get_work(self, share_hash):
597 height, work, last = self.get_height_work_and_last(share_hash)
600 def get_height_and_last(self, share_hash):
601 height, work, last = self.get_height_work_and_last(share_hash)
604 def get_height_work_and_last(self, share_hash):
605 assert isinstance(share_hash, (int, long, type(None)))
611 if share_hash is None or share_hash not in self.shares:
613 updates.append((share_hash, height, work))
614 if share_hash in self.heights:
615 height_inc, share_hash, work_inc = self.heights[share_hash]
617 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
620 for update_hash, height_then, work_then in updates:
621 self.heights[update_hash] = height - height_then, share_hash, work - work_then
622 return height, work, share_hash
624 def get_chain_known(self, start_hash):
625 assert isinstance(start_hash, (int, long, type(None)))
627 Chain starting with item of hash I{start_hash} of items that this Tracker contains
629 item_hash_to_get = start_hash
631 if item_hash_to_get not in self.shares:
633 share = self.shares[item_hash_to_get]
634 assert not isinstance(share, long)
636 item_hash_to_get = share.previous_hash
638 def get_chain_to_root(self, start_hash, root=None):
639 assert isinstance(start_hash, (int, long, type(None)))
640 assert isinstance(root, (int, long, type(None)))
642 Chain of hashes starting with share_hash of shares to the root (doesn't include root)
643 Raises an error if one is missing
645 share_hash_to_get = start_hash
646 while share_hash_to_get != root:
647 share = self.shares[share_hash_to_get]
649 share_hash_to_get = share.previous_hash
651 def get_best_hash(self):
653 Returns hash of item with the most items in its chain
657 return max(self.heads, key=self.get_height_and_last)
659 def get_highest_height(self):
660 return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
662 class FakeShare(object):
663 def __init__(self, **kwargs):
664 self.__dict__.update(kwargs)
666 if __name__ == '__main__':
670 for i in xrange(10000):
671 t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
675 print 'HEADS', t.heads
676 print 'TAILS', t.tails
685 for i in xrange(random.randrange(100)):
686 x = random.choice(list(t.shares) + [None])
688 t.add(FakeShare(i, x))
690 x = random.choice(list(t.shares))
691 print 'DEL', x, t.__dict__
694 except NotImplementedError:
695 print 'aborted; not implemented'
698 print 'HEADS', t.heads
699 print 'TAILS', t.tails
701 #for share_hash, share in sorted(t.shares.iteritems()):
702 # print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
704 #import sys;sys.exit()
706 print t.get_nth_parent_hash(9000, 5000)
707 print t.get_nth_parent_hash(9001, 412)
708 #print t.get_nth_parent_hash(90, 51)
710 for share_hash in sorted(t.shares):
711 print str(share_hash).rjust(4),
712 x = t.skips.get(share_hash, None)
714 print str(x[0]).rjust(4),
716 print str(a).rjust(10),
719 # network definitions
721 class Mainnet(object):
722 BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
723 BITCOIN_P2P_PORT = 8333
724 BITCOIN_ADDRESS_VERSION = 0
726 class Testnet(object):
727 BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
728 BITCOIN_P2P_PORT = 18333
729 BITCOIN_ADDRESS_VERSION = 111