1 from __future__ import division
8 from p2pool.util import bases, math, skiplist, intern2
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 warnings.warn('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')
310 target = intern2.intern2(target)
313 def write(self, file, item):
314 return self._inner.write(file, self._target_to_bits(item))
316 def truncate_to(self, x):
317 return self._bits_to_target(self._target_to_bits(x, _check=False))
319 def _bits_to_target(self, bits2):
320 target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
322 assert target == self._bits_to_target1(struct.pack('<I', bits2))
323 assert self._target_to_bits(target, _check=False) == bits2
326 def _bits_to_target1(self, bits):
328 length = ord(bits[0])
329 return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
331 def _target_to_bits(self, target, _check=True):
332 n = bases.natural_to_string(target)
333 if n and ord(n[0]) >= 128:
335 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
336 bits = struct.unpack('<I', bits2)[0]
338 if self._bits_to_target(bits) != target:
339 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
342 class PossiblyNone(Type):
343 def __init__(self, none_value, inner):
344 self.none_value = none_value
347 def read(self, file):
348 value, file = self.inner.read(file)
349 return None if value == self.none_value else value, file
351 def write(self, file, item):
352 if item == self.none_value:
353 raise ValueError('none_value used')
354 return self.inner.write(file, self.none_value if item is None else item)
356 address_type = ComposedType([
357 ('services', StructType('<Q')),
358 ('address', IPV6AddressType()),
359 ('port', StructType('>H')),
362 tx_type = ComposedType([
363 ('version', StructType('<I')),
364 ('tx_ins', ListType(ComposedType([
365 ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
366 ('hash', HashType()),
367 ('index', StructType('<I')),
369 ('script', VarStrType()),
370 ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
372 ('tx_outs', ListType(ComposedType([
373 ('value', StructType('<Q')),
374 ('script', VarStrType()),
376 ('lock_time', StructType('<I')),
379 block_header_type = ComposedType([
380 ('version', StructType('<I')),
381 ('previous_block', PossiblyNone(0, HashType())),
382 ('merkle_root', HashType()),
383 ('timestamp', StructType('<I')),
384 ('target', FloatingIntegerType()),
385 ('nonce', StructType('<I')),
388 block_type = ComposedType([
389 ('header', block_header_type),
390 ('txs', ListType(tx_type)),
394 merkle_record_type = ComposedType([
395 ('left', HashType()),
396 ('right', HashType()),
399 def merkle_hash(tx_list):
402 hash_list = map(tx_type.hash256, tx_list)
403 while len(hash_list) > 1:
404 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
405 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
408 def target_to_average_attempts(target):
409 return 2**256//(target + 1)
413 def tx_get_sigop_count(tx):
414 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'])
418 human_address_type = ChecksummedType(ComposedType([
419 ('version', StructType('<B')),
420 ('pubkey_hash', ShortHashType()),
423 pubkey_type = FixedStrType(65)
425 def pubkey_hash_to_address(pubkey_hash, net):
426 return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
428 def pubkey_to_address(pubkey, net):
429 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
431 def address_to_pubkey_hash(address, net):
432 x = human_address_type.unpack_base58(address)
433 if x['version'] != net.BITCOIN_ADDRESS_VERSION:
434 raise ValueError('address not for this net!')
435 return x['pubkey_hash']
439 def pubkey_to_script2(pubkey):
440 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
442 def pubkey_hash_to_script2(pubkey_hash):
443 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
445 # linked list tracker
447 class Tracker(object):
449 self.shares = {} # hash -> share
450 #self.ids = {} # hash -> (id, height)
451 self.reverse_shares = {} # previous_hash -> set of share_hashes
453 self.heads = {} # head hash -> tail_hash
454 self.tails = {} # tail hash -> set of head hashes
456 self.heights = {} # share_hash -> height_to, other_share_hash
459 self.id_generator = itertools.count()
460 self.tails_by_id = {}
463 self.get_nth_parent_hash = skiplist.DistanceSkipList(self)
465 def add(self, share):
466 assert not isinstance(share, (int, long, type(None)))
467 if share.hash in self.shares:
468 return # XXX raise exception?
471 parent_id = self.ids.get(share.previous_hash, None)
472 children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
474 if parent_id is not None:
475 infos.add((parent_id[0], parent_id[1] + 1))
476 for child_id in children_ids:
477 infos.add((child_id[0], child_id[1] - 1))
479 infos.add((self.id_generator.next(), 0))
481 self.ids[share.hash] = chosen
484 self.shares[share.hash] = share
485 self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
487 if share.hash in self.tails:
488 heads = self.tails.pop(share.hash)
490 heads = set([share.hash])
492 if share.previous_hash in self.heads:
493 tail = self.heads.pop(share.previous_hash)
495 #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
496 tail = share.previous_hash
497 while tail in self.shares:
498 tail = self.shares[tail].previous_hash
500 self.tails.setdefault(tail, set()).update(heads)
501 if share.previous_hash in self.tails[tail]:
502 self.tails[tail].remove(share.previous_hash)
505 self.heads[head] = tail
509 for s in self.shares.itervalues():
512 assert self.shares == t.shares, (self.shares, t.shares)
513 assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
514 assert self.heads == t.heads, (self.heads, t.heads)
515 assert self.tails == t.tails, (self.tails, t.tails)
517 def remove(self, share_hash):
518 assert isinstance(share_hash, (int, long, type(None)))
519 if share_hash not in self.shares:
521 share = self.shares[share_hash]
524 if share.hash in self.heads and share.previous_hash in self.tails:
525 tail = self.heads.pop(share.hash)
526 self.tails[tail].remove(share.hash)
527 if not self.tails[share.previous_hash]:
528 self.tails.pop(share.previous_hash)
529 elif share.hash in self.heads:
530 tail = self.heads.pop(share.hash)
531 self.tails[tail].remove(share.hash)
532 if self.reverse_shares[share.previous_hash] != set([share.hash]):
535 self.tails[tail].add(share.previous_hash)
536 self.heads[share.previous_hash] = tail
537 elif share.previous_hash in self.tails:
538 raise NotImplementedError() # will break other things..
539 heads = self.tails[share.previous_hash]
540 if len(self.reverse_shares[share.previous_hash]) > 1:
541 raise NotImplementedError()
543 del self.tails[share.previous_hash]
545 self.heads[head] = share.hash
546 self.tails[share.hash] = set(heads)
548 raise NotImplementedError()
551 height, tail = self.get_height_and_last(share.hash)
553 if share.hash in self.heads:
554 my_heads = set([share.hash])
555 elif share.previous_hash in self.tails:
556 my_heads = self.tails[share.previous_hash]
558 some_heads = self.tails[tail]
559 some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
560 my_heads = set(that_head for that_head in some_heads
561 if some_heads_heights[that_head] > height and
562 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
564 if share.previous_hash != tail:
565 self.heads[share.previous_hash] = tail
567 for head in my_heads:
568 if head != share.hash:
569 self.heads[head] = share.hash
573 if share.hash in self.heads:
574 self.heads.pop(share.hash)
577 self.tails[tail].difference_update(my_heads)
578 if share.previous_hash != tail:
579 self.tails[tail].add(share.previous_hash)
580 if not self.tails[tail]:
582 if my_heads != set([share.hash]):
583 self.tails[share.hash] = set(my_heads) - set([share.hash])
586 self.shares.pop(share.hash)
587 self.reverse_shares[share.previous_hash].remove(share.hash)
588 if not self.reverse_shares[share.previous_hash]:
589 self.reverse_shares.pop(share.previous_hash)
591 #assert self.test() is None
593 def get_height(self, share_hash):
594 height, work, last = self.get_height_work_and_last(share_hash)
597 def get_work(self, share_hash):
598 height, work, last = self.get_height_work_and_last(share_hash)
601 def get_height_and_last(self, share_hash):
602 height, work, last = self.get_height_work_and_last(share_hash)
605 def get_height_work_and_last(self, share_hash):
606 assert isinstance(share_hash, (int, long, type(None)))
612 if share_hash is None or share_hash not in self.shares:
614 updates.append((share_hash, height, work))
615 if share_hash in self.heights:
616 height_inc, share_hash, work_inc = self.heights[share_hash]
618 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
621 for update_hash, height_then, work_then in updates:
622 self.heights[update_hash] = height - height_then, share_hash, work - work_then
623 return height, work, share_hash
625 def get_chain_known(self, start_hash):
626 assert isinstance(start_hash, (int, long, type(None)))
628 Chain starting with item of hash I{start_hash} of items that this Tracker contains
630 item_hash_to_get = start_hash
632 if item_hash_to_get not in self.shares:
634 share = self.shares[item_hash_to_get]
635 assert not isinstance(share, long)
637 item_hash_to_get = share.previous_hash
639 def get_chain_to_root(self, start_hash, root=None):
640 assert isinstance(start_hash, (int, long, type(None)))
641 assert isinstance(root, (int, long, type(None)))
643 Chain of hashes starting with share_hash of shares to the root (doesn't include root)
644 Raises an error if one is missing
646 share_hash_to_get = start_hash
647 while share_hash_to_get != root:
648 share = self.shares[share_hash_to_get]
650 share_hash_to_get = share.previous_hash
652 def get_best_hash(self):
654 Returns hash of item with the most items in its chain
658 return max(self.heads, key=self.get_height_and_last)
660 def get_highest_height(self):
661 return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
663 class FakeShare(object):
664 def __init__(self, **kwargs):
665 self.__dict__.update(kwargs)
667 if __name__ == '__main__':
671 for i in xrange(10000):
672 t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
676 print "HEADS", t.heads
677 print "TAILS", t.tails
686 for i in xrange(random.randrange(100)):
687 x = random.choice(list(t.shares) + [None])
689 t.add(FakeShare(i, x))
691 x = random.choice(list(t.shares))
692 print "DEL", x, t.__dict__
695 except NotImplementedError:
696 print "aborted; not implemented"
699 print "HEADS", t.heads
700 print "TAILS", t.tails
702 #for share_hash, share in sorted(t.shares.iteritems()):
703 # print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
705 #import sys;sys.exit()
707 print t.get_nth_parent_hash(9000, 5000)
708 print t.get_nth_parent_hash(9001, 412)
709 #print t.get_nth_parent_hash(90, 51)
711 for share_hash in sorted(t.shares):
712 print str(share_hash).rjust(4),
713 x = t.skips.get(share_hash, None)
715 print str(x[0]).rjust(4),
717 print str(a).rjust(10),
720 # network definitions
722 class Mainnet(object):
723 BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
724 BITCOIN_P2P_PORT = 8333
725 BITCOIN_ADDRESS_VERSION = 0
727 class Testnet(object):
728 BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
729 BITCOIN_P2P_PORT = 18333
730 BITCOIN_ADDRESS_VERSION = 111