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