1 from __future__ import division
7 from . import base58, skiplists
8 from p2pool.util import bases, math, variable
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 if data not in self.keys:
159 raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
160 return self.keys[data], file
162 def write(self, file, item):
163 if item not in self.values:
164 raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
165 return self.inner.write(file, self.values[item])
167 class HashType(Type):
168 def read(self, file):
169 data, file = read(file, 256//8)
170 return int(data[::-1].encode('hex'), 16), file
172 def write(self, file, item):
173 if not 0 <= item < 2**256:
174 raise ValueError('invalid hash value - %r' % (item,))
175 if item != 0 and item < 2**160:
176 print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
177 return file, ('%064x' % (item,)).decode('hex')[::-1]
179 class ShortHashType(Type):
180 def read(self, file):
181 data, file = read(file, 160//8)
182 return int(data[::-1].encode('hex'), 16), file
184 def write(self, file, item):
185 if not 0 <= item < 2**160:
186 raise ValueError('invalid hash value - %r' % (item,))
187 return file, ('%040x' % (item,)).decode('hex')[::-1]
189 class ListType(Type):
190 _inner_size = VarIntType()
192 def __init__(self, type):
195 def read(self, file):
196 length, file = self._inner_size.read(file)
198 for i in xrange(length):
199 item, file = self.type.read(file)
203 def write(self, file, item):
204 file = self._inner_size.write(file, len(item))
206 file = self.type.write(file, subitem)
209 class StructType(Type):
210 def __init__(self, desc):
212 self.length = struct.calcsize(self.desc)
214 def read(self, file):
215 data, file = read(file, self.length)
216 res, = struct.unpack(self.desc, data)
219 def write(self, file, item):
220 data = struct.pack(self.desc, item)
221 if struct.unpack(self.desc, data)[0] != item:
222 # special test because struct doesn't error on some overflows
223 raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
226 class IPV6AddressType(Type):
227 def read(self, file):
228 data, file = read(file, 16)
229 if data[:12] != '00000000000000000000ffff'.decode('hex'):
230 raise ValueError('ipv6 addresses not supported yet')
231 return '.'.join(str(ord(x)) for x in data[12:]), file
233 def write(self, file, item):
234 bits = map(int, item.split('.'))
236 raise ValueError('invalid address: %r' % (bits,))
237 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
238 assert len(data) == 16, len(data)
243 def get_record(fields):
244 fields = tuple(sorted(fields))
247 if fields not in _record_types:
248 class _Record(object):
251 return repr(dict(self))
252 def __getitem__(self, key):
253 return getattr(self, key)
254 def __setitem__(self, key, value):
255 setattr(self, key, value)
257 # for field in self.__slots__:
258 # yield field, getattr(self, field)
260 return self.__slots__
261 def __eq__(self, other):
262 if isinstance(other, dict):
263 return dict(self) == other
264 elif isinstance(other, _Record):
265 return all(self[k] == other[k] for k in self.keys())
267 def __ne__(self, other):
268 return not (self == other)
269 _record_types[fields] = _Record
270 return _record_types[fields]()
272 class ComposedType(Type):
273 def __init__(self, fields):
276 def read(self, file):
277 item = get_record(k for k, v in self.fields)
278 for key, type_ in self.fields:
279 item[key], file = type_.read(file)
282 def write(self, file, item):
283 for key, type_ in self.fields:
284 file = type_.write(file, item[key])
287 class ChecksummedType(Type):
288 def __init__(self, inner):
291 def read(self, file):
292 obj, file = self.inner.read(file)
293 data = self.inner.pack(obj)
295 checksum, file = read(file, 4)
296 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
297 raise ValueError('invalid checksum')
301 def write(self, file, item):
302 data = self.inner.pack(item)
303 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
305 class FloatingInteger(object):
306 __slots__ = ['_bits']
309 def from_target_upper_bound(cls, target):
310 n = bases.natural_to_string(target)
311 if n and ord(n[0]) >= 128:
313 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
314 bits = struct.unpack('<I', bits2)[0]
317 def __init__(self, bits):
322 return math.shift_left(self._bits & 0x00ffffff, 8 * ((self._bits >> 24) - 3))
325 return hash(self._value)
327 def __cmp__(self, other):
328 if isinstance(other, FloatingInteger):
329 return cmp(self._value, other._value)
330 elif isinstance(other, (int, long)):
331 return cmp(self._value, other)
333 raise NotImplementedError()
339 return 'FloatingInteger(bits=%s (%x))' % (hex(self._bits), self)
341 def __add__(self, other):
342 if isinstance(other, (int, long)):
343 return self._value + other
344 raise NotImplementedError()
346 def __mul__(self, other):
347 if isinstance(other, (int, long)):
348 return self._value * other
349 raise NotImplementedError()
351 def __truediv__(self, other):
352 if isinstance(other, (int, long)):
353 return self._value / other
354 raise NotImplementedError()
355 def __floordiv__(self, other):
356 if isinstance(other, (int, long)):
357 return self._value // other
358 raise NotImplementedError()
359 __div__ = __truediv__
360 def __rtruediv__(self, other):
361 if isinstance(other, (int, long)):
362 return other / self._value
363 raise NotImplementedError()
364 def __rfloordiv__(self, other):
365 if isinstance(other, (int, long)):
366 return other // self._value
367 raise NotImplementedError()
368 __rdiv__ = __rtruediv__
370 class FloatingIntegerType(Type):
371 _inner = StructType('<I')
373 def read(self, file):
374 bits, file = self._inner.read(file)
375 return FloatingInteger(bits), file
377 def write(self, file, item):
378 return self._inner.write(file, item._bits)
380 class PossiblyNone(Type):
381 def __init__(self, none_value, inner):
382 self.none_value = none_value
385 def read(self, file):
386 value, file = self.inner.read(file)
387 return None if value == self.none_value else value, file
389 def write(self, file, item):
390 if item == self.none_value:
391 raise ValueError('none_value used')
392 return self.inner.write(file, self.none_value if item is None else item)
394 address_type = ComposedType([
395 ('services', StructType('<Q')),
396 ('address', IPV6AddressType()),
397 ('port', StructType('>H')),
400 tx_type = ComposedType([
401 ('version', StructType('<I')),
402 ('tx_ins', ListType(ComposedType([
403 ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
404 ('hash', HashType()),
405 ('index', StructType('<I')),
407 ('script', VarStrType()),
408 ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
410 ('tx_outs', ListType(ComposedType([
411 ('value', StructType('<Q')),
412 ('script', VarStrType()),
414 ('lock_time', StructType('<I')),
417 block_header_type = ComposedType([
418 ('version', StructType('<I')),
419 ('previous_block', PossiblyNone(0, HashType())),
420 ('merkle_root', HashType()),
421 ('timestamp', StructType('<I')),
422 ('target', FloatingIntegerType()),
423 ('nonce', StructType('<I')),
426 block_type = ComposedType([
427 ('header', block_header_type),
428 ('txs', ListType(tx_type)),
432 merkle_record_type = ComposedType([
433 ('left', HashType()),
434 ('right', HashType()),
437 def merkle_hash(tx_list):
440 hash_list = map(tx_type.hash256, tx_list)
441 while len(hash_list) > 1:
442 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
443 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
446 def target_to_average_attempts(target):
447 return 2**256//(target + 1)
451 def tx_get_sigop_count(tx):
452 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'])
456 human_address_type = ChecksummedType(ComposedType([
457 ('version', StructType('<B')),
458 ('pubkey_hash', ShortHashType()),
461 pubkey_type = FixedStrType(65)
463 def pubkey_hash_to_address(pubkey_hash, net):
464 return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
466 def pubkey_to_address(pubkey, net):
467 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
469 def address_to_pubkey_hash(address, net):
470 x = human_address_type.unpack_base58(address)
471 if x['version'] != net.BITCOIN_ADDRESS_VERSION:
472 raise ValueError('address not for this net!')
473 return x['pubkey_hash']
477 def pubkey_to_script2(pubkey):
478 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
480 def pubkey_hash_to_script2(pubkey_hash):
481 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
483 def script2_to_human(script2, net):
485 pubkey = script2[1:-1]
486 script2_test = pubkey_to_script2(pubkey)
490 if script2_test == script2:
491 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
494 pubkey_hash = ShortHashType().unpack(script2[3:-2])
495 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
499 if script2_test2 == script2:
500 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
502 return 'Unknown. Script: %s' % (script2.encode('hex'),)
504 # linked list tracker
506 class Tracker(object):
508 self.shares = {} # hash -> share
509 #self.ids = {} # hash -> (id, height)
510 self.reverse_shares = {} # previous_hash -> set of share_hashes
512 self.heads = {} # head hash -> tail_hash
513 self.tails = {} # tail hash -> set of head hashes
515 self.heights = {} # share_hash -> height_to, ref, work_inc
516 self.reverse_heights = {} # ref -> set of share_hashes
518 self.ref_generator = itertools.count()
519 self.height_refs = {} # ref -> height, share_hash, work_inc
520 self.reverse_height_refs = {} # share_hash -> ref
522 self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
524 self.added = variable.Event()
525 self.removed = variable.Event()
527 def add(self, share):
528 assert not isinstance(share, (int, long, type(None)))
529 if share.hash in self.shares:
530 raise ValueError('share already present')
532 if share.hash in self.tails:
533 heads = self.tails.pop(share.hash)
535 heads = set([share.hash])
537 if share.previous_hash in self.heads:
538 tail = self.heads.pop(share.previous_hash)
540 tail = self.get_last(share.previous_hash)
541 #tail2 = share.previous_hash
542 #while tail2 in self.shares:
543 # tail2 = self.shares[tail2].previous_hash
544 #assert tail == tail2
546 self.shares[share.hash] = share
547 self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
549 self.tails.setdefault(tail, set()).update(heads)
550 if share.previous_hash in self.tails[tail]:
551 self.tails[tail].remove(share.previous_hash)
554 self.heads[head] = tail
556 self.added.happened(share)
560 for s in self.shares.itervalues():
563 assert self.shares == t.shares, (self.shares, t.shares)
564 assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
565 assert self.heads == t.heads, (self.heads, t.heads)
566 assert self.tails == t.tails, (self.tails, t.tails)
568 def remove(self, share_hash):
569 assert isinstance(share_hash, (int, long, type(None)))
570 if share_hash not in self.shares:
573 share = self.shares[share_hash]
576 children = self.reverse_shares.get(share.hash, set())
578 # move height refs referencing children down to this, so they can be moved up in one step
579 if share.previous_hash in self.reverse_height_refs:
580 for x in list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set())):
582 assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, None), set()))
584 if share.hash in self.heads and share.previous_hash in self.tails:
585 tail = self.heads.pop(share.hash)
586 self.tails[tail].remove(share.hash)
587 if not self.tails[share.previous_hash]:
588 self.tails.pop(share.previous_hash)
589 elif share.hash in self.heads:
590 tail = self.heads.pop(share.hash)
591 self.tails[tail].remove(share.hash)
592 if self.reverse_shares[share.previous_hash] != set([share.hash]):
595 self.tails[tail].add(share.previous_hash)
596 self.heads[share.previous_hash] = tail
597 elif share.previous_hash in self.tails:
598 heads = self.tails[share.previous_hash]
599 if len(self.reverse_shares[share.previous_hash]) > 1:
600 raise NotImplementedError()
602 del self.tails[share.previous_hash]
604 self.heads[head] = share.hash
605 self.tails[share.hash] = set(heads)
607 raise NotImplementedError()
609 # move ref pointing to this up
610 if share.previous_hash in self.reverse_height_refs:
611 assert share.hash not in self.reverse_height_refs, list(self.reverse_heights.get(self.reverse_height_refs.get(share.hash, object()), set()))
613 ref = self.reverse_height_refs[share.previous_hash]
614 cur_height, cur_hash, cur_work = self.height_refs[ref]
615 assert cur_hash == share.previous_hash
616 self.height_refs[ref] = cur_height - 1, share.hash, cur_work - target_to_average_attempts(share.target)
617 del self.reverse_height_refs[share.previous_hash]
618 self.reverse_height_refs[share.hash] = ref
620 # delete height entry, and ref if it is empty
621 if share.hash in self.heights:
622 _, ref, _ = self.heights.pop(share.hash)
623 self.reverse_heights[ref].remove(share.hash)
624 if not self.reverse_heights[ref]:
625 del self.reverse_heights[ref]
626 _, ref_hash, _ = self.height_refs.pop(ref)
627 del self.reverse_height_refs[ref_hash]
629 self.shares.pop(share.hash)
630 self.reverse_shares[share.previous_hash].remove(share.hash)
631 if not self.reverse_shares[share.previous_hash]:
632 self.reverse_shares.pop(share.previous_hash)
634 #assert self.test() is None
635 self.removed.happened(share)
637 def get_height(self, share_hash):
638 height, work, last = self.get_height_work_and_last(share_hash)
641 def get_work(self, share_hash):
642 height, work, last = self.get_height_work_and_last(share_hash)
645 def get_last(self, share_hash):
646 height, work, last = self.get_height_work_and_last(share_hash)
649 def get_height_and_last(self, share_hash):
650 height, work, last = self.get_height_work_and_last(share_hash)
653 def _get_height_jump(self, share_hash):
654 if share_hash in self.heights:
655 height_to1, ref, work_inc1 = self.heights[share_hash]
656 height_to2, share_hash, work_inc2 = self.height_refs[ref]
657 height_inc = height_to1 + height_to2
658 work_inc = work_inc1 + work_inc2
660 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
661 return height_inc, share_hash, work_inc
663 def _set_height_jump(self, share_hash, height_inc, other_share_hash, work_inc):
664 if other_share_hash not in self.reverse_height_refs:
665 ref = self.ref_generator.next()
666 assert ref not in self.height_refs
667 self.height_refs[ref] = 0, other_share_hash, 0
668 self.reverse_height_refs[other_share_hash] = ref
671 ref = self.reverse_height_refs[other_share_hash]
672 ref_height_to, ref_share_hash, ref_work_inc = self.height_refs[ref]
673 assert ref_share_hash == other_share_hash
675 if share_hash in self.heights:
676 prev_ref = self.heights[share_hash][1]
677 self.reverse_heights[prev_ref].remove(share_hash)
678 if not self.reverse_heights[prev_ref] and prev_ref != ref:
679 self.reverse_heights.pop(prev_ref)
680 _, x, _ = self.height_refs.pop(prev_ref)
681 self.reverse_height_refs.pop(x)
682 self.heights[share_hash] = height_inc - ref_height_to, ref, work_inc - ref_work_inc
683 self.reverse_heights.setdefault(ref, set()).add(share_hash)
685 def get_height_work_and_last(self, share_hash):
686 assert isinstance(share_hash, (int, long, type(None)))
691 while share_hash in self.shares:
692 updates.append((share_hash, height, work))
693 height_inc, share_hash, work_inc = self._get_height_jump(share_hash)
696 for update_hash, height_then, work_then in updates:
697 self._set_height_jump(update_hash, height - height_then, share_hash, work - work_then)
698 return height, work, share_hash
700 def get_chain_known(self, start_hash):
701 assert isinstance(start_hash, (int, long, type(None)))
703 Chain starting with item of hash I{start_hash} of items that this Tracker contains
705 item_hash_to_get = start_hash
707 if item_hash_to_get not in self.shares:
709 share = self.shares[item_hash_to_get]
710 assert not isinstance(share, long)
712 item_hash_to_get = share.previous_hash
714 def get_chain_to_root(self, start_hash, root=None):
715 assert isinstance(start_hash, (int, long, type(None)))
716 assert isinstance(root, (int, long, type(None)))
718 Chain of hashes starting with share_hash of shares to the root (doesn't include root)
719 Raises an error if one is missing
721 share_hash_to_get = start_hash
722 while share_hash_to_get != root:
723 share = self.shares[share_hash_to_get]
725 share_hash_to_get = share.previous_hash
727 def get_best_hash(self):
729 Returns hash of item with the most items in its chain
733 return max(self.heads, key=self.get_height_and_last)
735 def get_highest_height(self):
736 return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
738 class FakeShare(object):
739 def __init__(self, **kwargs):
740 self.__dict__.update(kwargs)
742 if __name__ == '__main__':
746 for i in xrange(10000):
747 t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
751 print 'HEADS', t.heads
752 print 'TAILS', t.tails
761 for i in xrange(random.randrange(100)):
762 x = random.choice(list(t.shares) + [None])
764 t.add(FakeShare(i, x))
766 x = random.choice(list(t.shares))
767 print 'DEL', x, t.__dict__
770 except NotImplementedError:
771 print 'aborted; not implemented'
774 print 'HEADS', t.heads
775 print 'TAILS', t.tails
777 #for share_hash, share in sorted(t.shares.iteritems()):
778 # print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
780 #import sys;sys.exit()
782 print t.get_nth_parent_hash(9000, 5000)
783 print t.get_nth_parent_hash(9001, 412)
784 #print t.get_nth_parent_hash(90, 51)
786 for share_hash in sorted(t.shares):
787 print str(share_hash).rjust(4),
788 x = t.skips.get(share_hash, None)
790 print str(x[0]).rjust(4),
792 print str(a).rjust(10),
795 # network definitions
797 class Mainnet(object):
798 BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
799 BITCOIN_P2P_PORT = 8333
800 BITCOIN_ADDRESS_VERSION = 0
802 class Testnet(object):
803 BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
804 BITCOIN_P2P_PORT = 18333
805 BITCOIN_ADDRESS_VERSION = 111