defer removing items from heights so iteration can be done directly on the dict
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4 import itertools
5 import struct
6
7 from . import base58, skiplists
8 from p2pool.util import bases, math, skiplist, variable
9 import p2pool
10
11 class EarlyEnd(Exception):
12     pass
13
14 class LateEnd(Exception):
15     pass
16
17 def read((data, pos), length):
18     data2 = data[pos:pos + length]
19     if len(data2) != length:
20         raise EarlyEnd()
21     return data2, (data, pos + length)
22
23 def size((data, pos)):
24     return len(data) - pos
25
26 class Type(object):
27     # the same data can have only one unpacked representation, but multiple packed binary representations
28     
29     #def __hash__(self):
30     #    return hash(tuple(self.__dict__.items()))
31     
32     #def __eq__(self, other):
33     #    if not isinstance(other, Type):
34     #        raise NotImplementedError()
35     #    return self.__dict__ == other.__dict__
36     
37     def _unpack(self, data):
38         obj, (data2, pos) = self.read((data, 0))
39         
40         assert data2 is data
41         
42         if pos != len(data):
43             raise LateEnd()
44         
45         return obj
46     
47     def _pack(self, obj):
48         f = self.write(None, obj)
49         
50         res = []
51         while f is not None:
52             res.append(f[1])
53             f = f[0]
54         res.reverse()
55         return ''.join(res)
56     
57     
58     def unpack(self, data):
59         obj = self._unpack(data)
60         
61         if p2pool.DEBUG:
62             data2 = self._pack(obj)
63             if data2 != data:
64                 if self._unpack(data2) != obj:
65                     raise AssertionError()
66         
67         return obj
68     
69     def pack(self, obj):
70         data = self._pack(obj)
71         
72         if p2pool.DEBUG:
73             if self._unpack(data) != obj:
74                 raise AssertionError()
75         
76         return data
77     
78     
79     def pack_base58(self, obj):
80         return base58.base58_encode(self.pack(obj))
81     
82     def unpack_base58(self, base58_data):
83         return self.unpack(base58.base58_decode(base58_data))
84     
85     
86     def hash160(self, obj):
87         return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
88     
89     def hash256(self, obj):
90         return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
91
92 class VarIntType(Type):
93     # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
94     def read(self, file):
95         data, file = read(file, 1)
96         first = ord(data)
97         if first < 0xfd:
98             return first, file
99         elif first == 0xfd:
100             desc, length = '<H', 2
101         elif first == 0xfe:
102             desc, length = '<I', 4
103         elif first == 0xff:
104             desc, length = '<Q', 8
105         else:
106             raise AssertionError()
107         data, file = read(file, length)
108         return struct.unpack(desc, data)[0], file
109     
110     def write(self, file, item):
111         if item < 0xfd:
112             file = file, struct.pack('<B', item)
113         elif item <= 0xffff:
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)
119         else:
120             raise ValueError('int too large for varint')
121         return file
122
123 class VarStrType(Type):
124     _inner_size = VarIntType()
125     
126     def read(self, file):
127         length, file = self._inner_size.read(file)
128         return read(file, length)
129     
130     def write(self, file, item):
131         return self._inner_size.write(file, len(item)), item
132
133 class FixedStrType(Type):
134     def __init__(self, length):
135         self.length = length
136     
137     def read(self, file):
138         return read(file, self.length)
139     
140     def write(self, file, item):
141         if len(item) != self.length:
142             raise ValueError('incorrect length item!')
143         return file, item
144
145 class EnumType(Type):
146     def __init__(self, inner, values):
147         self.inner = inner
148         self.values = values
149         
150         self.keys = {}
151         for k, v in values.iteritems():
152             if v in self.keys:
153                 raise ValueError('duplicate value in values')
154             self.keys[v] = k
155     
156     def read(self, file):
157         data, file = self.inner.read(file)
158         return self.keys[data], file
159     
160     def write(self, file, item):
161         return self.inner.write(file, self.values[item])
162
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
167     
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]
174
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
179     
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]
184
185 class ListType(Type):
186     _inner_size = VarIntType()
187     
188     def __init__(self, type):
189         self.type = type
190     
191     def read(self, file):
192         length, file = self._inner_size.read(file)
193         res = []
194         for i in xrange(length):
195             item, file = self.type.read(file)
196             res.append(item)
197         return res, file
198     
199     def write(self, file, item):
200         file = self._inner_size.write(file, len(item))
201         for subitem in item:
202             file = self.type.write(file, subitem)
203         return file
204
205 class StructType(Type):
206     def __init__(self, desc):
207         self.desc = desc
208         self.length = struct.calcsize(self.desc)
209     
210     def read(self, file):
211         data, file = read(file, self.length)
212         res, = struct.unpack(self.desc, data)
213         return res, file
214     
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,))
220         return file, data
221
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
228     
229     def write(self, file, item):
230         bits = map(int, item.split('.'))
231         if len(bits) != 4:
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)
235         return file, data
236
237 _record_types = {}
238
239 def get_record(fields):
240     fields = tuple(sorted(fields))
241     if 'keys' in fields:
242         raise ValueError()
243     if fields not in _record_types:
244         class _Record(object):
245             __slots__ = fields
246             def __getitem__(self, key):
247                 return getattr(self, key)
248             def __setitem__(self, key, value):
249                 setattr(self, key, value)
250             #def __iter__(self):
251             #    for field in self.__slots__:
252             #        yield field, getattr(self, field)
253             def keys(self):
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())
260                 raise TypeError()
261             def __ne__(self, other):
262                 return not (self == other)
263         _record_types[fields] = _Record
264     return _record_types[fields]()
265
266 class ComposedType(Type):
267     def __init__(self, fields):
268         self.fields = fields
269     
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)
274         return item, file
275     
276     def write(self, file, item):
277         for key, type_ in self.fields:
278             file = type_.write(file, item[key])
279         return file
280
281 class ChecksummedType(Type):
282     def __init__(self, inner):
283         self.inner = inner
284     
285     def read(self, file):
286         obj, file = self.inner.read(file)
287         data = self.inner.pack(obj)
288         
289         checksum, file = read(file, 4)
290         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
291             raise ValueError('invalid checksum')
292         
293         return obj, file
294     
295     def write(self, file, item):
296         data = self.inner.pack(item)
297         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
298
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')
303     
304     def read(self, file):
305         bits, file = self._inner.read(file)
306         target = self._bits_to_target(bits)
307         if p2pool.DEBUG:
308             if self._target_to_bits(target) != bits:
309                 raise ValueError('bits in non-canonical form')
310         return target, file
311     
312     def write(self, file, item):
313         return self._inner.write(file, self._target_to_bits(item))
314     
315     def truncate_to(self, x):
316         return self._bits_to_target(self._target_to_bits(x, _check=False))
317     
318     def _bits_to_target(self, bits2):
319         target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
320         if p2pool.DEBUG:
321             assert target == self._bits_to_target1(struct.pack('<I', bits2))
322             assert self._target_to_bits(target, _check=False) == bits2
323         return target
324     
325     def _bits_to_target1(self, bits):
326         bits = bits[::-1]
327         length = ord(bits[0])
328         return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
329     
330     def _target_to_bits(self, target, _check=True):
331         n = bases.natural_to_string(target)
332         if n and ord(n[0]) >= 128:
333             n = '\x00' + n
334         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
335         bits = struct.unpack('<I', bits2)[0]
336         if _check:
337             if self._bits_to_target(bits) != target:
338                 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
339         return bits
340
341 class PossiblyNone(Type):
342     def __init__(self, none_value, inner):
343         self.none_value = none_value
344         self.inner = inner
345     
346     def read(self, file):
347         value, file = self.inner.read(file)
348         return None if value == self.none_value else value, file
349     
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)
354
355 address_type = ComposedType([
356     ('services', StructType('<Q')),
357     ('address', IPV6AddressType()),
358     ('port', StructType('>H')),
359 ])
360
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')),
367         ]))),
368         ('script', VarStrType()),
369         ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
370     ]))),
371     ('tx_outs', ListType(ComposedType([
372         ('value', StructType('<Q')),
373         ('script', VarStrType()),
374     ]))),
375     ('lock_time', StructType('<I')),
376 ])
377
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')),
385 ])
386
387 block_type = ComposedType([
388     ('header', block_header_type),
389     ('txs', ListType(tx_type)),
390 ])
391
392
393 merkle_record_type = ComposedType([
394     ('left', HashType()),
395     ('right', HashType()),
396 ])
397
398 def merkle_hash(tx_list):
399     if not tx_list:
400         return 0
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])]
405     return hash_list[0]
406
407 def target_to_average_attempts(target):
408     return 2**256//(target + 1)
409
410 # tx
411
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'])
414
415 # human addresses
416
417 human_address_type = ChecksummedType(ComposedType([
418     ('version', StructType('<B')),
419     ('pubkey_hash', ShortHashType()),
420 ]))
421
422 pubkey_type = FixedStrType(65)
423
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))
426
427 def pubkey_to_address(pubkey, net):
428     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
429
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']
435
436 # transactions
437
438 def pubkey_to_script2(pubkey):
439     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
440
441 def pubkey_hash_to_script2(pubkey_hash):
442     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
443
444 def script2_to_human(script2, net):
445     try:
446         pubkey = script2[1:-1]
447         script2_test = pubkey_to_script2(pubkey)
448     except:
449         pass
450     else:
451         if script2_test == script2:
452             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
453     
454     try:
455         pubkey_hash = ShortHashType().unpack(script2[3:-2])
456         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
457     except:
458         pass
459     else:
460         if script2_test2 == script2:
461             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
462     
463     return 'Unknown. Script: %s'  % (script2.encode('hex'),)
464
465 # linked list tracker
466
467 class Tracker(object):
468     def __init__(self):
469         self.shares = {} # hash -> share
470         #self.ids = {} # hash -> (id, height)
471         self.reverse_shares = {} # previous_hash -> set of share_hashes
472         
473         self.heads = {} # head hash -> tail_hash
474         self.tails = {} # tail hash -> set of head hashes
475         
476         self.heights = {} # share_hash -> height_to, other_share_hash
477         
478         '''
479         self.id_generator = itertools.count()
480         self.tails_by_id = {}
481         '''
482         
483         self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
484         
485         self.added = variable.Event()
486         self.removed = variable.Event()
487     
488     def add(self, share):
489         assert not isinstance(share, (int, long, type(None)))
490         if share.hash in self.shares:
491             raise ValueError('share already present')
492         
493         '''
494         parent_id = self.ids.get(share.previous_hash, None)
495         children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
496         infos = set()
497         if parent_id is not None:
498             infos.add((parent_id[0], parent_id[1] + 1))
499         for child_id in children_ids:
500             infos.add((child_id[0], child_id[1] - 1))
501         if not infos:
502             infos.add((self.id_generator.next(), 0))
503         chosen = min(infos)
504         self.ids[share.hash] = chosen
505         '''
506         
507         self.shares[share.hash] = share
508         self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
509         
510         if share.hash in self.tails:
511             heads = self.tails.pop(share.hash)
512         else:
513             heads = set([share.hash])
514         
515         if share.previous_hash in self.heads:
516             tail = self.heads.pop(share.previous_hash)
517         else:
518             #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
519             tail = share.previous_hash
520             while tail in self.shares:
521                 tail = self.shares[tail].previous_hash
522         
523         self.tails.setdefault(tail, set()).update(heads)
524         if share.previous_hash in self.tails[tail]:
525             self.tails[tail].remove(share.previous_hash)
526         
527         for head in heads:
528             self.heads[head] = tail
529         
530         self.added.happened(share)
531     
532     def test(self):
533         t = Tracker()
534         for s in self.shares.itervalues():
535             t.add(s)
536         
537         assert self.shares == t.shares, (self.shares, t.shares)
538         assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
539         assert self.heads == t.heads, (self.heads, t.heads)
540         assert self.tails == t.tails, (self.tails, t.tails)
541     
542     def remove(self, share_hash):
543         assert isinstance(share_hash, (int, long, type(None)))
544         if share_hash not in self.shares:
545             raise KeyError()
546         share = self.shares[share_hash]
547         children = self.reverse_shares.get(share_hash, set())
548         del share_hash
549         
550         if share.hash in self.heads and share.previous_hash in self.tails:
551             tail = self.heads.pop(share.hash)
552             self.tails[tail].remove(share.hash)
553             if not self.tails[share.previous_hash]:
554                 self.tails.pop(share.previous_hash)
555         elif share.hash in self.heads:
556             tail = self.heads.pop(share.hash)
557             self.tails[tail].remove(share.hash)
558             if self.reverse_shares[share.previous_hash] != set([share.hash]):
559                 pass # has sibling
560             else:
561                 self.tails[tail].add(share.previous_hash)
562                 self.heads[share.previous_hash] = tail
563         elif share.previous_hash in self.tails:
564             #raise NotImplementedError() # will break other things..
565             heads = self.tails[share.previous_hash]
566             if len(self.reverse_shares[share.previous_hash]) > 1:
567                 raise NotImplementedError()
568             else:
569                 del self.tails[share.previous_hash]
570                 for head in heads:
571                     self.heads[head] = share.hash
572                 self.tails[share.hash] = set(heads)
573         else:
574             raise NotImplementedError()
575         
576         to_remove = set()
577         for share_hash2 in self.heights:
578             height_to, other_share_hash, work_inc = self.heights[share_hash2]
579             if other_share_hash != share.previous_hash:
580                 continue
581             assert children
582             if len(children) == 1:
583                 height_to -= 1
584                 other_share_hash = share.hash
585                 work_inc -= target_to_average_attempts(share.target)
586                 self.heights[share_hash2] = height_to, other_share_hash, work_inc
587             else:
588                 to_remove.add(share_hash2)
589         for share_hash2 in to_remove:
590             del self.heights[share_hash2]
591         if share.hash in self.heights:
592             del self.heights[share.hash]
593         
594         '''
595         height, tail = self.get_height_and_last(share.hash)
596         
597         if share.hash in self.heads:
598             my_heads = set([share.hash])
599         elif share.previous_hash in self.tails:
600             my_heads = self.tails[share.previous_hash]
601         else:
602             some_heads = self.tails[tail]
603             some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
604             my_heads = set(that_head for that_head in some_heads
605                 if some_heads_heights[that_head] > height and
606                 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
607         
608         if share.previous_hash != tail:
609             self.heads[share.previous_hash] = tail
610         
611         for head in my_heads:
612             if head != share.hash:
613                 self.heads[head] = share.hash
614             else:
615                 self.heads.pop(head)
616         
617         if share.hash in self.heads:
618             self.heads.pop(share.hash)
619         
620         
621         self.tails[tail].difference_update(my_heads)
622         if share.previous_hash != tail:
623             self.tails[tail].add(share.previous_hash)
624         if not self.tails[tail]:
625             self.tails.pop(tail)
626         if my_heads != set([share.hash]):
627             self.tails[share.hash] = set(my_heads) - set([share.hash])
628         '''
629         
630         self.shares.pop(share.hash)
631         self.reverse_shares[share.previous_hash].remove(share.hash)
632         if not self.reverse_shares[share.previous_hash]:
633             self.reverse_shares.pop(share.previous_hash)
634         
635         #assert self.test() is None
636         self.removed.happened(share)
637     
638     def get_height(self, share_hash):
639         height, work, last = self.get_height_work_and_last(share_hash)
640         return height
641     
642     def get_work(self, share_hash):
643         height, work, last = self.get_height_work_and_last(share_hash)
644         return work
645     
646     def get_height_and_last(self, share_hash):
647         height, work, last = self.get_height_work_and_last(share_hash)
648         return height, last
649     
650     def get_height_work_and_last(self, share_hash):
651         assert isinstance(share_hash, (int, long, type(None)))
652         orig = share_hash
653         height = 0
654         work = 0
655         updates = []
656         while True:
657             if share_hash is None or share_hash not in self.shares:
658                 break
659             updates.append((share_hash, height, work))
660             if share_hash in self.heights:
661                 height_inc, share_hash, work_inc = self.heights[share_hash]
662             else:
663                 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
664             height += height_inc
665             work += work_inc
666         for update_hash, height_then, work_then in updates:
667             self.heights[update_hash] = height - height_then, share_hash, work - work_then
668         return height, work, share_hash
669     
670     def get_chain_known(self, start_hash):
671         assert isinstance(start_hash, (int, long, type(None)))
672         '''
673         Chain starting with item of hash I{start_hash} of items that this Tracker contains
674         '''
675         item_hash_to_get = start_hash
676         while True:
677             if item_hash_to_get not in self.shares:
678                 break
679             share = self.shares[item_hash_to_get]
680             assert not isinstance(share, long)
681             yield share
682             item_hash_to_get = share.previous_hash
683     
684     def get_chain_to_root(self, start_hash, root=None):
685         assert isinstance(start_hash, (int, long, type(None)))
686         assert isinstance(root, (int, long, type(None)))
687         '''
688         Chain of hashes starting with share_hash of shares to the root (doesn't include root)
689         Raises an error if one is missing
690         '''
691         share_hash_to_get = start_hash
692         while share_hash_to_get != root:
693             share = self.shares[share_hash_to_get]
694             yield share
695             share_hash_to_get = share.previous_hash
696     
697     def get_best_hash(self):
698         '''
699         Returns hash of item with the most items in its chain
700         '''
701         if not self.heads:
702             return None
703         return max(self.heads, key=self.get_height_and_last)
704     
705     def get_highest_height(self):
706         return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
707
708 class FakeShare(object):
709     def __init__(self, **kwargs):
710         self.__dict__.update(kwargs)
711
712 if __name__ == '__main__':
713     
714     t = Tracker()
715     
716     for i in xrange(10000):
717         t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
718     
719     #t.remove(99)
720     
721     print 'HEADS', t.heads
722     print 'TAILS', t.tails
723     
724     import random
725     
726     while False:
727         print
728         print '-'*30
729         print
730         t = Tracker()
731         for i in xrange(random.randrange(100)):
732             x = random.choice(list(t.shares) + [None])
733             print i, '->', x
734             t.add(FakeShare(i, x))
735         while t.shares:
736             x = random.choice(list(t.shares))
737             print 'DEL', x, t.__dict__
738             try:
739                 t.remove(x)
740             except NotImplementedError:
741                 print 'aborted; not implemented'
742         import time
743         time.sleep(.1)
744         print 'HEADS', t.heads
745         print 'TAILS', t.tails
746     
747     #for share_hash, share in sorted(t.shares.iteritems()):
748     #    print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
749     
750     #import sys;sys.exit()
751     
752     print t.get_nth_parent_hash(9000, 5000)
753     print t.get_nth_parent_hash(9001, 412)
754     #print t.get_nth_parent_hash(90, 51)
755     
756     for share_hash in sorted(t.shares):
757         print str(share_hash).rjust(4),
758         x = t.skips.get(share_hash, None)
759         if x is not None:
760             print str(x[0]).rjust(4),
761             for a in x[1]:
762                 print str(a).rjust(10),
763         print
764
765 # network definitions
766
767 class Mainnet(object):
768     BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
769     BITCOIN_P2P_PORT = 8333
770     BITCOIN_ADDRESS_VERSION = 0
771
772 class Testnet(object):
773     BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
774     BITCOIN_P2P_PORT = 18333
775     BITCOIN_ADDRESS_VERSION = 111