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