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