Added BITCOIN_POW_FUNC to network definitions
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import itertools
4 import random
5 import time
6 import os
7
8 from twisted.python import log
9
10 import p2pool
11 from p2pool import skiplists
12 from p2pool.bitcoin import data as bitcoin_data, script, networks
13 from p2pool.util import memoize, expiring_dict, math
14
15
16 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
17     ('side', bitcoin_data.StructType('<B')), # enum?
18     ('hash', bitcoin_data.HashType()),
19 ]))
20
21
22 share_data_type = bitcoin_data.ComposedType([
23     ('previous_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
24     ('target', bitcoin_data.FloatingIntegerType()),
25     ('nonce', bitcoin_data.VarStrType()),
26 ])
27
28
29 coinbase_type = bitcoin_data.ComposedType([
30     ('identifier', bitcoin_data.FixedStrType(8)),
31     ('share_data', share_data_type),
32 ])
33
34 share_info_type = bitcoin_data.ComposedType([
35     ('share_data', share_data_type),
36     ('new_script', bitcoin_data.VarStrType()),
37     ('subsidy', bitcoin_data.StructType('<Q')),
38 ])
39
40
41 share1a_type = bitcoin_data.ComposedType([
42     ('header', bitcoin_data.block_header_type),
43     ('share_info', share_info_type),
44     ('merkle_branch', merkle_branch_type),
45 ])
46
47 share1b_type = bitcoin_data.ComposedType([
48     ('header', bitcoin_data.block_header_type),
49     ('share_info', share_info_type),
50     ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
51 ])
52
53 def calculate_merkle_branch(txs, index):
54     hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
55     
56     while len(hash_list) > 1:
57         hash_list = [
58             (
59                 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
60                 left_f or right_f,
61                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
62             )
63             for (left, left_f, left_l), (right, right_f, right_l) in
64                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
65         ]
66     
67     assert hash_list[0][1]
68     assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
69     
70     return hash_list[0][2]
71
72 def check_merkle_branch(tx, branch):
73     hash_ = bitcoin_data.tx_type.hash256(tx)
74     for step in branch:
75         if not step['side']:
76             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
77         else:
78             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
79     return hash_
80
81 def gentx_to_share_info(gentx):
82     return dict(
83         share_data=coinbase_type.unpack(gentx['tx_ins'][0]['script'])['share_data'],
84         subsidy=sum(tx_out['value'] for tx_out in gentx['tx_outs']),
85         new_script=gentx['tx_outs'][-1]['script'],
86     )
87
88 def share_info_to_gentx(share_info, block_target, tracker, net):
89     return generate_transaction(
90         tracker=tracker,
91         previous_share_hash=share_info['share_data']['previous_share_hash'],
92         new_script=share_info['new_script'],
93         subsidy=share_info['subsidy'],
94         nonce=share_info['share_data']['nonce'],
95         block_target=block_target,
96         net=net,
97     )
98
99 class Share(object):
100     @classmethod
101     def from_block(cls, block, net):
102         return cls(net, block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
103     
104     @classmethod
105     def from_share1a(cls, share1a, net):
106         return cls(net, **share1a)
107     
108     @classmethod
109     def from_share1b(cls, share1b, net):
110         return cls(net, **share1b)
111     
112     __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce bitcoin_hash hash time_seen shared stored peer'.split(' ')
113     
114     def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
115         if merkle_branch is None and other_txs is None:
116             raise ValueError('need either merkle_branch or other_txs')
117         if other_txs is not None:
118             new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
119             if merkle_branch is not None:
120                 if merke_branch != new_merkle_branch:
121                     raise ValueError('invalid merkle_branch and other_txs')
122             merkle_branch = new_merkle_branch
123         
124         if len(merkle_branch) > 16:
125             raise ValueError('merkle_branch too long!')
126         
127         self.header = header
128         self.previous_block = header['previous_block']
129         self.share_info = share_info
130         self.merkle_branch = merkle_branch
131         self.other_txs = other_txs
132         
133         self.timestamp = self.header['timestamp']
134         
135         self.share_data = self.share_info['share_data']
136         self.new_script = self.share_info['new_script']
137         self.subsidy = self.share_info['subsidy']
138         
139         if len(self.new_script) > 100:
140             raise ValueError('new_script too long!')
141         
142         self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
143         self.target = self.share_data['target']
144         self.nonce = self.share_data['nonce']
145         
146         if len(self.nonce) > 100:
147             raise ValueError('nonce too long!')
148         
149         self.bitcoin_hash = net.BITCOIN_POW_FUNC(header)
150         self.hash = net.BITCOIN_POW_FUNC(header) # XXX was a bug in litecoin pull
151         
152         if self.bitcoin_hash > self.target:
153             print 'hash %x' % self.bitcoin_hash
154             print 'targ %x' % self.target
155             raise ValueError('not enough work!')
156         
157         if script.get_sigop_count(self.new_script) > 1:
158             raise ValueError('too many sigops!')
159         
160         # XXX eww
161         self.time_seen = time.time()
162         self.shared = False
163         self.stored = False
164         self.peer = None
165     
166     def as_block(self, tracker, net):
167         if self.other_txs is None:
168             raise ValueError('share does not contain all txs')
169         
170         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
171         
172         return dict(header=self.header, txs=[gentx] + self.other_txs)
173     
174     def as_share1a(self):
175         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
176     
177     def as_share1b(self):
178         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
179     
180     def check(self, tracker, now, net):
181         import time
182         if self.previous_share_hash is not None:
183             if self.header['timestamp'] <= math.median((s.timestamp for s in itertools.islice(tracker.get_chain_to_root(self.previous_share_hash), 11)), use_float=False):
184                 raise ValueError('share from too far in the past!')
185         
186         if self.header['timestamp'] > now + 2*60*60:
187             raise ValueError('share from too far in the future!')
188         
189         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
190         
191         if len(gentx['tx_ins'][0]['script']) > 100:
192             raise ValueError('''coinbase too large! %i bytes''' % (len(gentx['tx_ins'][0]['script']),))
193         
194         if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
195             raise ValueError('''gentx doesn't match header via merkle_branch''')
196         
197         if self.other_txs is not None:
198             if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
199                 raise ValueError('''gentx doesn't match header via other_txs''')
200             
201             if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
202                 raise ValueError('''block size too large''')
203     
204     def flag_shared(self):
205         self.shared = True
206     
207     def __repr__(self):
208         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
209
210 def get_pool_attempts_per_second(tracker, previous_share_hash, net, dist=None):
211     if dist is None:
212         dist = net.TARGET_LOOKBEHIND
213     near = tracker.shares[previous_share_hash]
214     far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
215     attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash)
216     time = near.timestamp - far.timestamp
217     if time == 0:
218         time = 1
219     return attempts//time
220
221 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
222     height, last = tracker.get_height_and_last(previous_share_hash)
223     assert height >= net.CHAIN_LENGTH or last is None
224     if height < net.TARGET_LOOKBEHIND:
225         target = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
226     else:
227         attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
228         previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
229         pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
230         pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
231         pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
232         target = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
233     
234     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
235     max_weight = net.SPREAD * attempts_to_block
236     
237     this_weight = min(bitcoin_data.target_to_average_attempts(target), max_weight)
238     other_weights, other_weights_total = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), max(0, max_weight - this_weight))
239     dest_weights, total_weight = math.add_dicts([{new_script: this_weight}, other_weights]), this_weight + other_weights_total
240     assert total_weight == sum(dest_weights.itervalues())
241
242     if net.SCRIPT:
243         amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
244         amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
245         amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*2//400
246         amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
247     else:
248         amounts = dict((script, subsidy*(398*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
249         amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
250         amounts[new_script] = amounts.get(new_script, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
251
252     if sum(amounts.itervalues()) != subsidy:
253         raise ValueError()
254     if any(x < 0 for x in amounts.itervalues()):
255         raise ValueError()
256     
257     pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
258     pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
259     
260     dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
261     assert dests[-1] == new_script
262     
263     return dict(
264         version=1,
265         tx_ins=[dict(
266             previous_output=None,
267             sequence=None,
268             script=coinbase_type.pack(dict(
269                 identifier=net.IDENTIFIER,
270                 share_data=dict(
271                     previous_share_hash=previous_share_hash,
272                     nonce=nonce,
273                     target=target,
274                 ),
275             )),
276         )],
277         tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
278         lock_time=0,
279     )
280
281
282
283 class OkayTracker(bitcoin_data.Tracker):
284     def __init__(self, net):
285         bitcoin_data.Tracker.__init__(self)
286         self.net = net
287         self.verified = bitcoin_data.Tracker()
288         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
289         
290         self.get_cumulative_weights = skiplists.WeightsSkipList(self)
291     
292     def add(self, share, known_verified=False):
293         bitcoin_data.Tracker.add(self, share)
294         if known_verified:
295             self.verified.add(share)
296     
297     def attempt_verify(self, share, now):
298         if share.hash in self.verified.shares:
299             return True
300         height, last = self.get_height_and_last(share.hash)
301         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
302             raise AssertionError()
303         try:
304             share.check(self, now, self.net)
305         except:
306             log.err(None, 'Share check failed:')
307             return False
308         else:
309             self.verified.add(share)
310             return True
311     
312     def think(self, ht, previous_block, now):
313         desired = set()
314         
315         # O(len(self.heads))
316         #   make 'unverified heads' set?
317         # for each overall head, attempt verification
318         # if it fails, attempt on parent, and repeat
319         # if no successful verification because of lack of parents, request parent
320         bads = set()
321         for head in set(self.heads) - set(self.verified.heads):
322             head_height, last = self.get_height_and_last(head)
323             
324             for share in itertools.islice(self.get_chain_known(head), None if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
325                 if self.attempt_verify(share, now):
326                     break
327                 if share.hash in self.heads:
328                     bads.add(share.hash)
329             else:
330                 if last is not None:
331                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
332         for bad in bads:
333             assert bad not in self.verified.shares
334             assert bad in self.heads
335             if p2pool.DEBUG:
336                 print "BAD", bad
337             self.remove(bad)
338         
339         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
340         for head in list(self.verified.heads):
341             head_height, last_hash = self.verified.get_height_and_last(head)
342             last_height, last_last_hash = self.get_height_and_last(last_hash)
343             # XXX review boundary conditions
344             want = max(self.net.CHAIN_LENGTH - head_height, 0)
345             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
346             get = min(want, can)
347             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
348             for share in itertools.islice(self.get_chain_known(last_hash), get):
349                 if not self.attempt_verify(share, now):
350                     break
351             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
352                 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
353         
354         # decide best tree
355         best_tail = max(self.verified.tails, key=lambda h: self.score(max(self.verified.tails[h], key=self.verified.get_height), ht)) if self.verified.tails else None
356         # decide best verified head
357         scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
358             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
359             #self.verified.shares[h].peer is None,
360             ht.get_min_height(self.verified.shares[h].previous_block),
361             -self.verified.shares[h].time_seen
362         ))
363         
364         
365         if p2pool.DEBUG:
366             print len(self.verified.tails), "chain tails and", len(self.verified.tails.get(best_tail, [])), 'chain heads. Top 10 tails:'
367             if len(scores) > 10:
368                 print '    ...'
369             for h in scores[-10:]:
370                 print '   ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
371                     self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
372                     self.verified.shares[h].peer is None,
373                     ht.get_min_height(self.verified.shares[h].previous_block),
374                     -self.verified.shares[h].time_seen
375                 )
376         
377         # eat away at heads
378         if scores:
379             for i in xrange(1000):
380                 to_remove = set()
381                 for share_hash, tail in self.heads.iteritems():
382                     if share_hash in scores[-5:]:
383                         #print 1
384                         continue
385                     if self.shares[share_hash].time_seen > time.time() - 300:
386                         #print 2
387                         continue
388                     if share_hash not in self.verified.shares and max(self.shares[after_tail_hash].time_seen for after_tail_hash in self.reverse_shares.get(tail)) > time.time() - 120: # XXX stupid
389                         #print 3
390                         continue
391                     to_remove.add(share_hash)
392                 if not to_remove:
393                     break
394                 for share_hash in to_remove:
395                     self.remove(share_hash)
396                     if share_hash in self.verified.shares:
397                         self.verified.remove(share_hash)
398                 #print "_________", to_remove
399         
400         # drop tails
401         for i in xrange(1000):
402             to_remove = set()
403             for tail, heads in self.tails.iteritems():
404                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
405                     continue
406                 for aftertail in self.reverse_shares.get(tail, set()):
407                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
408                         print "raw"
409                         continue
410                     to_remove.add(aftertail)
411             if not to_remove:
412                 break
413             # if removed from this, it must be removed from verified
414             #start = time.time()
415             for aftertail in to_remove:
416                 if self.shares[aftertail].previous_hash not in self.tails:
417                     print "erk", aftertail, self.shares[aftertail].previous_hash
418                     continue
419                 self.remove(aftertail)
420                 if aftertail in self.verified.shares:
421                     self.verified.remove(aftertail)
422             #end = time.time()
423             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
424         
425         best = scores[-1] if scores else None
426         
427         if best is not None:
428             best_share = self.verified.shares[best]
429             if ht.get_min_height(best_share.header['previous_block']) < ht.get_min_height(previous_block) and best_share.bitcoin_hash != previous_block and best_share.peer is not None:
430                 if p2pool.DEBUG:
431                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
432                 best = best_share.previous_hash
433         
434         return best, desired
435     
436     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
437     def score(self, share_hash, ht):
438         head_height, last = self.verified.get_height_and_last(share_hash)
439         score2 = 0
440         attempts = 0
441         max_height = 0
442         share2_hash = self.verified.get_nth_parent_hash(share_hash, min(self.net.CHAIN_LENGTH//2, head_height//2)) if last is not None else share_hash
443         for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
444             max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
445             attempts += bitcoin_data.target_to_average_attempts(share.target)
446             this_score = attempts//(ht.get_highest_height() - max_height + 1)
447             if this_score > score2:
448                 score2 = this_score
449         return min(head_height, self.net.CHAIN_LENGTH), score2
450
451 def format_hash(x):
452     if x is None:
453         return 'xxxxxxxx'
454     return '%08x' % (x % 2**32)
455
456 class ShareStore(object):
457     def __init__(self, prefix, net):
458         self.filename = prefix
459         self.net = net
460         self.known = None # will be filename -> set of share hashes, set of verified hashes
461     
462     def get_shares(self):
463         if self.known is not None:
464             raise AssertionError()
465         known = {}
466         filenames, next = self.get_filenames_and_next()
467         for filename in filenames:
468             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
469             with open(filename, 'rb') as f:
470                 for line in f:
471                     try:
472                         type_id_str, data_hex = line.strip().split(' ')
473                         type_id = int(type_id_str)
474                         if type_id == 0:
475                             share = Share.from_share1a(share1a_type.unpack(data_hex.decode('hex')), self.net)
476                             yield 'share', share
477                             share_hashes.add(share.hash)
478                         elif type_id == 1:
479                             share = Share.from_share1b(share1b_type.unpack(data_hex.decode('hex')), self.net)
480                             yield 'share', share
481                             share_hashes.add(share.hash)
482                         elif type_id == 2:
483                             verified_hash = int(data_hex, 16)
484                             yield 'verified_hash', verified_hash
485                             verified_hashes.add(verified_hash)
486                         else:
487                             raise NotImplementedError("share type %i" % (type_id,))
488                     except Exception:
489                         log.err(None, "Error while reading saved shares, continuing where left off:")
490         self.known = known
491     
492     def _add_line(self, line):
493         filenames, next = self.get_filenames_and_next()
494         if filenames and os.path.getsize(filenames[-1]) < 10e6:
495             filename = filenames[-1]
496         else:
497             filename = next
498         
499         with open(filename, 'ab') as f:
500             f.write(line + '\n')
501         
502         return filename
503     
504     def add_share(self, share):
505         if share.bitcoin_hash <= share.header['target']:
506             type_id, data = 1, share1b_type.pack(share.as_share1b())
507         else:
508             type_id, data = 0, share1a_type.pack(share.as_share1a())
509         filename = self._add_line("%i %s" % (type_id, data.encode('hex')))
510         share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
511         share_hashes.add(share.hash)
512     
513     def add_verified_hash(self, share_hash):
514         filename = self._add_line("%i %x" % (2, share_hash))
515         share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
516         verified_hashes.add(share_hash)
517     
518     def get_filenames_and_next(self):
519         suffixes = sorted(int(x[len(self.filename):]) for x in os.listdir('.') if x.startswith(self.filename) and x[len(self.filename):].isdigit())
520         return [self.filename + str(suffix) for suffix in suffixes], self.filename + str(suffixes[-1] + 1) if suffixes else self.filename + str(0)
521     
522     def forget_share(self, share_hash):
523         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
524             if share_hash in share_hashes:
525                 share_hashes.remove(share_hash)
526         self.check_remove()
527     
528     def forget_verified_share(self, share_hash):
529         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
530             if share_hash in verified_hashes:
531                 verified_hashes.remove(share_hash)
532         self.check_remove()
533     
534     def check_remove(self):
535         to_remove = set()
536         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
537             #print filename, len(share_hashes) + len(verified_hashes)
538             if not share_hashes and not verified_hashes:
539                 to_remove.add(filename)
540         for filename in to_remove:
541             self.known.pop(filename)
542             os.remove(filename)
543             print "REMOVED", filename
544
545 class BitcoinMainnet(networks.BitcoinMainnet):
546     SHARE_PERIOD = 10 # seconds
547     CHAIN_LENGTH = 24*60*60//5 # shares
548     TARGET_LOOKBEHIND = 200 # shares
549     SPREAD = 3 # blocks
550     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
551     IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
552     PREFIX = '2472ef181efcd37b'.decode('hex')
553     NAME = 'bitcoin'
554     P2P_PORT = 9333
555     MAX_TARGET = 2**256//2**32 - 1
556     PERSIST = True
557     WORKER_PORT = 9332
558
559 class BitcoinTestnet(networks.BitcoinTestnet):
560     SHARE_PERIOD = 1 # seconds
561     CHAIN_LENGTH = 24*60*60//5 # shares
562     TARGET_LOOKBEHIND = 200 # shares
563     SPREAD = 3 # blocks
564     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
565     IDENTIFIER = '5fc2be2d4f0d6bfb'.decode('hex')
566     PREFIX = '3f6057a15036f441'.decode('hex')
567     NAME = 'bitcoin_testnet'
568     P2P_PORT = 19333
569     MAX_TARGET = 2**256//2**32 - 1
570     PERSIST = False
571     WORKER_PORT = 19332
572
573 class NamecoinMainnet(networks.NamecoinMainnet):
574     SHARE_PERIOD = 10 # seconds
575     CHAIN_LENGTH = 24*60*60//10 # shares
576     TARGET_LOOKBEHIND = 3600//10 # shares
577     SPREAD = 3 # blocks
578     SCRIPT = '41043da5beb73f8f18cede1a41b0ed953123f1342b8e0216ab5bf71ed3e024201b4017f472bddb6041f17978d89ed8f8ed84f9e726b0bca80cacf96347c7153e8df0ac'.decode('hex')
579     IDENTIFIER = 'd5b1192062c4c454'.decode('hex')
580     PREFIX = 'b56f3d0fb24fc982'.decode('hex')
581     NAME = 'namecoin'
582     P2P_PORT = 9334
583     MAX_TARGET = 2**256//2**32 - 1
584     PERSIST = True
585     WORKER_PORT = 9331
586
587 class NamecoinTestnet(networks.NamecoinTestnet):
588     SHARE_PERIOD = 1 # seconds
589     CHAIN_LENGTH = 24*60*60//5 # shares
590     TARGET_LOOKBEHIND = 200 # shares
591     SPREAD = 3 # blocks
592     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
593     IDENTIFIER = '8dd303d014a01a60'.decode('hex')
594     PREFIX = '4d6581d24f51acbf'.decode('hex')
595     NAME = 'namecoin_testnet'
596     P2P_PORT = 19334
597     MAX_TARGET = 2**256//2**20 - 1
598     PERSIST = False
599     WORKER_PORT = 19331
600
601 class IxcoinMainnet(networks.IxcoinMainnet):
602     SHARE_PERIOD = 10 # seconds
603     CHAIN_LENGTH = 24*60*60//10 # shares
604     TARGET_LOOKBEHIND = 3600//10 # shares
605     SPREAD = 3 # blocks
606     SCRIPT = '41043da5beb73f8f18cede1a41b0ed953123f1342b8e0216ab5bf71ed3e024201b4017f472bddb6041f17978d89ed8f8ed84f9e726b0bca80cacf96347c7153e8df0ac'.decode('hex')
607     IDENTIFIER = '27b564116e2a2666'.decode('hex')
608     PREFIX = '9dd6c4a619401f2f'.decode('hex')
609     NAME = 'ixcoin'
610     P2P_PORT = 9335
611     MAX_TARGET = 2**256//2**32 - 1
612     PERSIST = True
613     WORKER_PORT = 9330
614
615 class IxcoinTestnet(networks.IxcoinTestnet):
616     SHARE_PERIOD = 1 # seconds
617     CHAIN_LENGTH = 24*60*60//5 # shares
618     TARGET_LOOKBEHIND = 200 # shares
619     SPREAD = 3 # blocks
620     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
621     IDENTIFIER = '7430cbeb01249e44'.decode('hex')
622     PREFIX = '7cfffda946709c1f'.decode('hex')
623     NAME = 'ixcoin_testnet'
624     P2P_PORT = 19335
625     MAX_TARGET = 2**256//2**20 - 1
626     PERSIST = False
627     WORKER_PORT = 19330
628
629 class I0coinMainnet(networks.I0coinMainnet):
630     SHARE_PERIOD = 10 # seconds
631     CHAIN_LENGTH = 24*60*60//10 # shares
632     TARGET_LOOKBEHIND = 3600//10 # shares
633     SPREAD = 3 # blocks
634     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
635     IDENTIFIER = 'b32e3f10c2ff221b'.decode('hex')
636     PREFIX = '6155537ed977a3b5'.decode('hex')
637     NAME = 'i0coin'
638     P2P_PORT = 9336
639     MAX_TARGET = 2**256//2**32 - 1
640     PERSIST = False
641     WORKER_PORT = 9329
642
643 class I0coinTestnet(networks.I0coinTestnet):
644     SHARE_PERIOD = 1 # seconds
645     CHAIN_LENGTH = 24*60*60//5 # shares
646     TARGET_LOOKBEHIND = 200 # shares
647     SPREAD = 3 # blocks
648     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
649     IDENTIFIER = '7712c1a8181b5f2e'.decode('hex')
650     PREFIX = '792d2e7d770fbe68'.decode('hex')
651     NAME = 'i0coin_testnet'
652     P2P_PORT = 19336
653     MAX_TARGET = 2**256//2**20 - 1
654     PERSIST = False
655     WORKER_PORT = 19329
656
657 class SolidcoinMainnet(networks.SolidcoinMainnet):
658     SHARE_PERIOD = 10
659     CHAIN_LENGTH = 24*60*60//10 # shares
660     TARGET_LOOKBEHIND = 3600//10 # shares
661     SPREAD = 3 # blocks
662     SCRIPT = bitcoin_data.pubkey_hash_to_script2(bitcoin_data.address_to_pubkey_hash('sMKZ1yxHETxPYKh4Z2anWnwZDJZU7ztroy', networks.SolidcoinMainnet))
663     IDENTIFIER = '9cc9c421cca258cd'.decode('hex')
664     PREFIX = 'c059125b8070f00a'.decode('hex')
665     NAME = 'solidcoin'
666     P2P_PORT = 9337
667     MAX_TARGET = 2**256//2**32 - 1
668     PERSIST = True
669     WORKER_PORT = 9328
670
671 class LitecoinMainnet(networks.LitecoinMainnet):
672     SHARE_PERIOD = 10 # seconds
673     CHAIN_LENGTH = 24*60*60//5 # shares
674     TARGET_LOOKBEHIND = 200 # shares
675     SPREAD = 12 # blocks
676     SCRIPT = None # no fee
677     IDENTIFIER = 'e037d5b8c6923410'.decode('hex')
678     PREFIX = '7208c1a53ef629b0'.decode('hex')
679     NAME = 'litecoin'
680     P2P_PORT = 9338
681     MAX_TARGET = 2**256//2**20 - 1
682     PERSIST = True
683     WORKER_PORT = 9327
684
685 class LitecoinTestnet(networks.LitecoinTestnet):
686     SHARE_PERIOD = 1 # seconds
687     CHAIN_LENGTH = 24*60*60//5 # shares
688     TARGET_LOOKBEHIND = 200 # shares
689     SPREAD = 12 # blocks
690     SCRIPT = None # no fee
691     IDENTIFIER = 'cca5e24ec6408b1e'.decode('hex')
692     PREFIX = 'ad9614f6466a39cf'.decode('hex')
693     NAME = 'litecoin_testnet'
694     P2P_PORT = 19338
695     MAX_TARGET = 2**256//2**17 - 1
696     PERSIST = False
697     WORKER_PORT = 19327
698
699 nets = dict((net.NAME, net) for net in set([BitcoinMainnet, BitcoinTestnet, NamecoinMainnet, NamecoinTestnet, IxcoinMainnet, IxcoinTestnet, I0coinMainnet, I0coinTestnet, SolidcoinMainnet, LitecoinMainnet, LitecoinTestnet]))