1 from __future__ import division
9 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 assert self._unpack(data2) == obj
69 data = self._pack(obj)
71 assert self._unpack(data) == obj
76 def pack_base58(self, obj):
77 return base58.base58_encode(self.pack(obj))
79 def unpack_base58(self, base58_data):
80 return self.unpack(base58.base58_decode(base58_data))
83 def hash160(self, obj):
84 return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
86 def hash256(self, obj):
87 return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
89 class VarIntType(Type):
90 # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
92 data, file = read(file, 1)
97 desc, length = '<H', 2
99 desc, length = '<I', 4
101 desc, length = '<Q', 8
103 raise AssertionError()
104 data, file = read(file, length)
105 return struct.unpack(desc, data)[0], file
107 def write(self, file, item):
109 file = file, struct.pack('<B', item)
111 file = file, struct.pack('<BH', 0xfd, item)
112 elif item <= 0xffffffff:
113 file = file, struct.pack('<BI', 0xfe, item)
114 elif item <= 0xffffffffffffffff:
115 file = file, struct.pack('<BQ', 0xff, item)
117 raise ValueError('int too large for varint')
120 class VarStrType(Type):
121 _inner_size = VarIntType()
123 def read(self, file):
124 length, file = self._inner_size.read(file)
125 return read(file, length)
127 def write(self, file, item):
128 return self._inner_size.write(file, len(item)), item
130 class FixedStrType(Type):
131 def __init__(self, length):
134 def read(self, file):
135 return read(file, self.length)
137 def write(self, file, item):
138 if len(item) != self.length:
139 raise ValueError('incorrect length item!')
142 class EnumType(Type):
143 def __init__(self, inner, values):
148 for k, v in values.iteritems():
150 raise ValueError('duplicate value in values')
153 def read(self, file):
154 data, file = self.inner.read(file)
155 return self.keys[data], file
157 def write(self, file, item):
158 return self.inner.write(file, self.values[item])
160 class HashType(Type):
161 def read(self, file):
162 data, file = read(file, 256//8)
163 return int(data[::-1].encode('hex'), 16), file
165 def write(self, file, item):
166 if not 0 <= item < 2**256:
167 raise ValueError('invalid hash value - %r' % (item,))
168 if item != 0 and item < 2**160:
169 warnings.warn('very low hash value - maybe you meant to use ShortHashType? %x' % (item,))
170 return file, ('%064x' % (item,)).decode('hex')[::-1]
172 class ShortHashType(Type):
173 def read(self, file):
174 data, file = read(file, 160//8)
175 return int(data[::-1].encode('hex'), 16), file
177 def write(self, file, item):
178 if not 0 <= item < 2**160:
179 raise ValueError('invalid hash value - %r' % (item,))
180 return file, ('%040x' % (item,)).decode('hex')[::-1]
182 class ListType(Type):
183 _inner_size = VarIntType()
185 def __init__(self, type):
188 def read(self, file):
189 length, file = self._inner_size.read(file)
191 for i in xrange(length):
192 item, file = self.type.read(file)
196 def write(self, file, item):
197 file = self._inner_size.write(file, len(item))
199 file = self.type.write(file, subitem)
202 class StructType(Type):
203 def __init__(self, desc):
205 self.length = struct.calcsize(self.desc)
207 def read(self, file):
208 data, file = read(file, self.length)
209 res, = struct.unpack(self.desc, data)
212 def write(self, file, item):
213 data = struct.pack(self.desc, item)
214 if struct.unpack(self.desc, data)[0] != item:
215 # special test because struct doesn't error on some overflows
216 raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
219 class IPV6AddressType(Type):
220 def read(self, file):
221 data, file = read(file, 16)
222 if data[:12] != '00000000000000000000ffff'.decode('hex'):
223 raise ValueError('ipv6 addresses not supported yet')
224 return '.'.join(str(ord(x)) for x in data[12:]), file
226 def write(self, file, item):
227 bits = map(int, item.split('.'))
229 raise ValueError('invalid address: %r' % (bits,))
230 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
231 assert len(data) == 16, len(data)
234 class ComposedType(Type):
235 def __init__(self, fields):
238 def read(self, file):
240 for key, type_ in self.fields:
241 item[key], file = type_.read(file)
244 def write(self, file, item):
245 for key, type_ in self.fields:
246 file = type_.write(file, item[key])
249 class ChecksummedType(Type):
250 def __init__(self, inner):
253 def read(self, file):
254 obj, file = self.inner.read(file)
255 data = self.inner.pack(obj)
257 checksum, file = read(file, 4)
258 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
259 raise ValueError('invalid checksum')
263 def write(self, file, item):
264 data = self.inner.pack(item)
265 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
267 class FloatingIntegerType(Type):
268 # redundancy doesn't matter here because bitcoin checks binary bits against its own computed bits
269 # so it will always be encoded 'normally' in blocks (they way bitcoin does it)
270 _inner = StructType('<I')
272 def read(self, file):
273 bits, file = self._inner.read(file)
274 target = self._bits_to_target(bits)
276 if self._target_to_bits(target) != bits:
277 raise ValueError('bits in non-canonical form')
280 def write(self, file, item):
281 return self._inner.write(file, self._target_to_bits(item))
283 def truncate_to(self, x):
284 return self._bits_to_target(self._target_to_bits(x, _check=False))
286 def _bits_to_target(self, bits2):
287 target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
288 assert target == self._bits_to_target1(struct.pack('<I', bits2))
289 assert self._target_to_bits(target, _check=False) == bits2
292 def _bits_to_target1(self, bits):
294 length = ord(bits[0])
295 return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
297 def _target_to_bits(self, target, _check=True):
298 n = bases.natural_to_string(target)
299 if n and ord(n[0]) >= 128:
301 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
302 bits = struct.unpack('<I', bits2)[0]
304 if self._bits_to_target(bits) != target:
305 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
308 class PossiblyNone(Type):
309 def __init__(self, none_value, inner):
310 self.none_value = none_value
313 def read(self, file):
314 value, file = self.inner.read(file)
315 return None if value == self.none_value else value, file
317 def write(self, file, item):
318 if item == self.none_value:
319 raise ValueError('none_value used')
320 return self.inner.write(file, self.none_value if item is None else item)
322 address_type = ComposedType([
323 ('services', StructType('<Q')),
324 ('address', IPV6AddressType()),
325 ('port', StructType('>H')),
328 tx_type = ComposedType([
329 ('version', StructType('<I')),
330 ('tx_ins', ListType(ComposedType([
331 ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
332 ('hash', HashType()),
333 ('index', StructType('<I')),
335 ('script', VarStrType()),
336 ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
338 ('tx_outs', ListType(ComposedType([
339 ('value', StructType('<Q')),
340 ('script', VarStrType()),
342 ('lock_time', StructType('<I')),
345 block_header_type = ComposedType([
346 ('version', StructType('<I')),
347 ('previous_block', PossiblyNone(0, HashType())),
348 ('merkle_root', HashType()),
349 ('timestamp', StructType('<I')),
350 ('target', FloatingIntegerType()),
351 ('nonce', StructType('<I')),
354 block_type = ComposedType([
355 ('header', block_header_type),
356 ('txs', ListType(tx_type)),
360 merkle_record_type = ComposedType([
361 ('left', HashType()),
362 ('right', HashType()),
365 def merkle_hash(tx_list):
368 hash_list = map(tx_type.hash256, tx_list)
369 while len(hash_list) > 1:
370 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
371 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
374 def target_to_average_attempts(target):
375 return 2**256//(target + 1)
379 def tx_get_sigop_count(tx):
380 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'])
384 human_address_type = ChecksummedType(ComposedType([
385 ('version', StructType('<B')),
386 ('pubkey_hash', ShortHashType()),
389 pubkey_type = FixedStrType(65)
391 def pubkey_hash_to_address(pubkey_hash, net):
392 return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
394 def pubkey_to_address(pubkey, net):
395 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
397 def address_to_pubkey_hash(address, net):
398 x = human_address_type.unpack_base58(address)
399 if x['version'] != net.BITCOIN_ADDRESS_VERSION:
400 raise ValueError('address not for this net!')
401 return x['pubkey_hash']
405 def pubkey_to_script2(pubkey):
406 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
408 def pubkey_hash_to_script2(pubkey_hash):
409 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
411 # linked list tracker
413 class Tracker(object):
415 self.shares = {} # hash -> share
416 self.ids = {} # hash -> (id, height)
417 self.reverse_shares = {} # previous_hash -> set of share_hashes
419 self.heads = {} # head hash -> tail_hash
420 self.tails = {} # tail hash -> set of head hashes
422 self.heights = {} # share_hash -> height_to, other_share_hash
424 #self.id_generator = itertools.count()
425 #self.tails_by_id = {}
427 self.get_nth_parent_hash = skiplist.DistanceSkipList(self)
429 def add(self, share):
430 assert not isinstance(share, (int, long, type(None)))
431 if share.hash in self.shares:
432 return # XXX raise exception?
435 parent_id = self.ids.get(share.previous_hash, None)
436 children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
438 if parent_id is not None:
439 infos.add((parent_id[0], parent_id[1] + 1))
440 for child_id in children_ids:
441 infos.add((child_id[0], child_id[1] - 1))
443 infos.add((self.id_generator.next(), 0))
447 self.shares[share.hash] = share
448 self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
450 if share.hash in self.tails:
451 heads = self.tails.pop(share.hash)
453 heads = set([share.hash])
455 if share.previous_hash in self.heads:
456 tail = self.heads.pop(share.previous_hash)
458 #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
459 tail = share.previous_hash
460 while tail in self.shares:
461 tail = self.shares[tail].previous_hash
463 self.tails.setdefault(tail, set()).update(heads)
464 if share.previous_hash in self.tails[tail]:
465 self.tails[tail].remove(share.previous_hash)
468 self.heads[head] = tail
472 for s in self.shares.itervalues():
475 assert self.shares == t.shares, (self.shares, t.shares)
476 assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
477 assert self.heads == t.heads, (self.heads, t.heads)
478 assert self.tails == t.tails, (self.tails, t.tails)
480 def remove(self, share_hash):
481 assert isinstance(share_hash, (int, long, type(None)))
482 if share_hash not in self.shares:
484 share = self.shares[share_hash]
487 if share.hash in self.heads and share.previous_hash in self.tails:
488 tail = self.heads.pop(share.hash)
489 self.tails[tail].remove(share.hash)
490 if not self.tails[share.previous_hash]:
491 self.tails.pop(share.previous_hash)
492 elif share.hash in self.heads:
493 tail = self.heads.pop(share.hash)
494 self.tails[tail].remove(share.hash)
495 if self.reverse_shares[share.previous_hash] != set([share.hash]):
498 self.tails[tail].add(share.previous_hash)
499 self.heads[share.previous_hash] = tail
500 elif share.previous_hash in self.tails:
501 raise NotImplementedError() # will break other things..
502 heads = self.tails[share.previous_hash]
503 if len(self.reverse_shares[share.previous_hash]) > 1:
504 raise NotImplementedError()
506 del self.tails[share.previous_hash]
508 self.heads[head] = share.hash
509 self.tails[share.hash] = set(heads)
511 raise NotImplementedError()
514 height, tail = self.get_height_and_last(share.hash)
516 if share.hash in self.heads:
517 my_heads = set([share.hash])
518 elif share.previous_hash in self.tails:
519 my_heads = self.tails[share.previous_hash]
521 some_heads = self.tails[tail]
522 some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
523 my_heads = set(that_head for that_head in some_heads
524 if some_heads_heights[that_head] > height and
525 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
527 if share.previous_hash != tail:
528 self.heads[share.previous_hash] = tail
530 for head in my_heads:
531 if head != share.hash:
532 self.heads[head] = share.hash
536 if share.hash in self.heads:
537 self.heads.pop(share.hash)
540 self.tails[tail].difference_update(my_heads)
541 if share.previous_hash != tail:
542 self.tails[tail].add(share.previous_hash)
543 if not self.tails[tail]:
545 if my_heads != set([share.hash]):
546 self.tails[share.hash] = set(my_heads) - set([share.hash])
549 self.shares.pop(share.hash)
550 self.reverse_shares[share.previous_hash].remove(share.hash)
551 if not self.reverse_shares[share.previous_hash]:
552 self.reverse_shares.pop(share.previous_hash)
554 assert self.test() is None
556 def get_height(self, share_hash):
557 height, work, last = self.get_height_work_and_last(share_hash)
560 def get_work(self, share_hash):
561 height, work, last = self.get_height_work_and_last(share_hash)
564 def get_height_and_last(self, share_hash):
565 height, work, last = self.get_height_work_and_last(share_hash)
568 def get_height_work_and_last(self, share_hash):
569 assert isinstance(share_hash, (int, long, type(None)))
575 if share_hash is None or share_hash not in self.shares:
577 updates.append((share_hash, height, work))
578 if share_hash in self.heights:
579 height_inc, share_hash, work_inc = self.heights[share_hash]
581 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
584 for update_hash, height_then, work_then in updates:
585 self.heights[update_hash] = height - height_then, share_hash, work - work_then
586 return height, work, share_hash
588 def get_chain_known(self, start_hash):
589 assert isinstance(start_hash, (int, long, type(None)))
591 Chain starting with item of hash I{start_hash} of items that this Tracker contains
593 item_hash_to_get = start_hash
595 if item_hash_to_get not in self.shares:
597 share = self.shares[item_hash_to_get]
598 assert not isinstance(share, long)
600 item_hash_to_get = share.previous_hash
602 def get_chain_to_root(self, start_hash, root=None):
603 assert isinstance(start_hash, (int, long, type(None)))
604 assert isinstance(root, (int, long, type(None)))
606 Chain of hashes starting with share_hash of shares to the root (doesn't include root)
607 Raises an error if one is missing
609 share_hash_to_get = start_hash
610 while share_hash_to_get != root:
611 share = self.shares[share_hash_to_get]
613 share_hash_to_get = share.previous_hash
615 def get_best_hash(self):
617 Returns hash of item with the most items in its chain
621 return max(self.heads, key=self.get_height_and_last)
623 def get_highest_height(self):
624 return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
626 class FakeShare(object):
627 def __init__(self, **kwargs):
628 self.__dict__.update(kwargs)
630 if __name__ == '__main__':
634 for i in xrange(10000):
635 t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
639 print "HEADS", t.heads
640 print "TAILS", t.tails
649 for i in xrange(random.randrange(100)):
650 x = random.choice(list(t.shares) + [None])
652 t.add(FakeShare(i, x))
654 x = random.choice(list(t.shares))
655 print "DEL", x, t.__dict__
658 except NotImplementedError:
659 print "aborted; not implemented"
662 print "HEADS", t.heads
663 print "TAILS", t.tails
665 #for share_hash, share in sorted(t.shares.iteritems()):
666 # print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
668 #import sys;sys.exit()
670 print t.get_nth_parent_hash(9000, 5000)
671 print t.get_nth_parent_hash(9001, 412)
672 #print t.get_nth_parent_hash(90, 51)
674 for share_hash in sorted(t.shares):
675 print str(share_hash).rjust(4),
676 x = t.skips.get(share_hash, None)
678 print str(x[0]).rjust(4),
680 print str(a).rjust(10),
683 # network definitions
685 class Mainnet(object):
686 BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
687 BITCOIN_P2P_PORT = 8333
688 BITCOIN_ADDRESS_VERSION = 0
690 class Testnet(object):
691 BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
692 BITCOIN_P2P_PORT = 18333
693 BITCOIN_ADDRESS_VERSION = 111