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