moved stale skiplist to tracker's delta object
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import random
4 import time
5 import os
6
7 from twisted.python import log
8
9 import p2pool
10 from p2pool import skiplists
11 from p2pool.bitcoin import data as bitcoin_data, script
12 from p2pool.util import math, forest
13
14
15 share_data_type = bitcoin_data.ComposedType([
16     ('previous_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
17     ('coinbase', bitcoin_data.VarStrType()),
18     ('nonce', bitcoin_data.VarStrType()),
19     ('new_script', bitcoin_data.VarStrType()),
20     ('subsidy', bitcoin_data.StructType('<Q')),
21     ('donation', bitcoin_data.StructType('<H')),
22     ('stale_info', bitcoin_data.StructType('<B')), # 0 nothing, 253 orphan, 254 doa. previously: 254*perfect_round(my_stale_prop), None if no shares
23 ])
24
25 share_info_type = bitcoin_data.ComposedType([
26     ('share_data', share_data_type),
27     ('bits', bitcoin_data.FloatingIntegerType()),
28     ('timestamp', bitcoin_data.StructType('<I')),
29 ])
30
31 share1a_type = bitcoin_data.ComposedType([
32     ('header', bitcoin_data.block_header_type),
33     ('share_info', share_info_type),
34     ('merkle_branch', bitcoin_data.merkle_branch_type),
35 ])
36
37 share1b_type = bitcoin_data.ComposedType([
38     ('header', bitcoin_data.block_header_type),
39     ('share_info', share_info_type),
40     ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
41 ])
42
43 # type:
44 # 0: share1a
45 # 1: share1b
46
47 share_type = bitcoin_data.ComposedType([
48     ('type', bitcoin_data.VarIntType()),
49     ('contents', bitcoin_data.VarStrType()),
50 ])
51
52 class Share(object):
53     __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce pow_hash header_hash hash time_seen peer donation net'.split(' ')
54     
55     @classmethod
56     def from_share(cls, share, net):
57         if share['type'] == 0:
58             res = cls.from_share1a(share1a_type.unpack(share['contents']), net)
59             if not (res.pow_hash > res.header['bits'].target):
60                 raise ValueError('invalid share type')
61             return res
62         elif share['type'] == 1:
63             res = cls.from_share1b(share1b_type.unpack(share['contents']), net)
64             if not (res.pow_hash <= res.header['bits'].target):
65                 raise ValueError('invalid share type')
66             return res
67         else:
68             raise ValueError('unknown share type: %r' % (share['type'],))
69     
70     @classmethod
71     def from_share1a(cls, share1a, net):
72         return cls(net, **share1a)
73     
74     @classmethod
75     def from_share1b(cls, share1b, net):
76         return cls(net, **share1b)
77     
78     def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
79         self.net = net
80         
81         if merkle_branch is None and other_txs is None:
82             raise ValueError('need either merkle_branch or other_txs')
83         if other_txs is not None:
84             new_merkle_branch = bitcoin_data.calculate_merkle_branch([0] + map(bitcoin_data.tx_type.hash256, other_txs), 0)
85             if merkle_branch is not None:
86                 if merke_branch != new_merkle_branch:
87                     raise ValueError('invalid merkle_branch and other_txs')
88             merkle_branch = new_merkle_branch
89         
90         if len(merkle_branch) > 16:
91             raise ValueError('merkle_branch too long!')
92         
93         self.header = header
94         self.previous_block = header['previous_block']
95         self.share_info = share_info
96         self.merkle_branch = merkle_branch
97         
98         self.share_data = self.share_info['share_data']
99         self.target = self.share_info['bits'].target
100         self.timestamp = self.share_info['timestamp']
101         
102         self.new_script = self.share_data['new_script']
103         self.subsidy = self.share_data['subsidy']
104         self.donation = self.share_data['donation']
105         
106         if len(self.new_script) > 100:
107             raise ValueError('new_script too long!')
108         
109         self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
110         self.nonce = self.share_data['nonce']
111         
112         if len(self.nonce) > 100:
113             raise ValueError('nonce too long!')
114         
115         if len(self.share_data['coinbase']) > 100:
116             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
117         
118         self.pow_hash = net.PARENT.POW_FUNC(header)
119         self.header_hash = bitcoin_data.block_header_type.hash256(header)
120         
121         self.hash = share1a_type.hash256(self.as_share1a())
122         
123         if self.pow_hash > self.target:
124             print 'hash %x' % self.pow_hash
125             print 'targ %x' % self.target
126             raise ValueError('not enough work!')
127         
128         self.other_txs = other_txs if self.pow_hash <= self.header['bits'].target else None
129         
130         # XXX eww
131         self.time_seen = time.time()
132         self.peer = None
133     
134     def __repr__(self):
135         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
136     
137     def check(self, tracker):
138         if script.get_sigop_count(self.new_script) > 1:
139             raise ValueError('too many sigops!')
140         
141         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.net)
142         if share_info != self.share_info:
143             raise ValueError('share difficulty invalid')
144         
145         if bitcoin_data.check_merkle_branch(bitcoin_data.tx_type.hash256(gentx), 0, self.merkle_branch) != self.header['merkle_root']:
146             raise ValueError('''gentx doesn't match header via merkle_branch''')
147     
148     def as_share(self):
149         if self.pow_hash > self.header['bits'].target: # share1a
150             return dict(type=0, contents=share1a_type.pack(self.as_share1a()))
151         elif self.pow_hash <= self.header['bits'].target: # share1b
152             return dict(type=1, contents=share1b_type.pack(self.as_share1b()))
153         else:
154             raise AssertionError()
155     
156     def as_share1a(self):
157         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
158     
159     def as_share1b(self):
160         if self.other_txs is None:
161             raise ValueError('share does not contain all txs')
162         
163         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
164     
165     def as_block(self, tracker):
166         if self.other_txs is None:
167             raise ValueError('share does not contain all txs')
168         
169         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.net)
170         assert share_info == self.share_info
171         
172         return dict(header=self.header, txs=[gentx] + self.other_txs)
173
174 def get_pool_attempts_per_second(tracker, previous_share_hash, dist):
175     assert dist >= 2
176     near = tracker.shares[previous_share_hash]
177     far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
178     attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash)
179     time = near.timestamp - far.timestamp
180     if time <= 0:
181         time = 1
182     return attempts//time
183
184 def get_average_stale_prop(tracker, share_hash, lookbehind):
185     def stales_per_share(share):
186         if share.share_data['stale_info'] == 253: # orphan
187             return 1
188         elif share.share_data['stale_info'] == 254: # doa
189             return 1
190         elif share.share_data['stale_info'] == 0:
191             return 0
192         elif share.share_data['stale_info'] == 255: # temporary hack until everyone uses new-style stale data
193             return 0
194         else:
195             return 1/(254/share.share_data['stale_info'] - 1) # converts stales/shares to stales/nonstales
196             # 0 and 254 case are taken care of above and this will soon be removed anyway
197     stales = sum(stales_per_share(share) for share in tracker.get_chain(share_hash, lookbehind))
198     return stales/(lookbehind + stales)
199
200 def generate_transaction(tracker, share_data, block_target, desired_timestamp, net):
201     previous_share_hash = share_data['previous_share_hash']
202     new_script = share_data['new_script']
203     subsidy = share_data['subsidy']
204     donation = share_data['donation']
205     assert 0 <= donation <= 65535
206     
207     if len(share_data['coinbase']) > 100:
208         raise ValueError('coinbase too long!')
209     
210     previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
211     
212     chain_length = getattr(net, 'REAL_CHAIN_LENGTH_FUNC', lambda _: net.REAL_CHAIN_LENGTH)(previous_share.timestamp if previous_share is not None else None)
213     
214     height, last = tracker.get_height_and_last(previous_share_hash)
215     assert height >= chain_length or last is None
216     if height < net.TARGET_LOOKBEHIND:
217         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
218     else:
219         attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net.TARGET_LOOKBEHIND)
220         pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
221         pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
222         pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
223         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
224     
225     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
226     max_att = net.SPREAD * attempts_to_block
227     
228     this_att = min(bitcoin_data.target_to_average_attempts(bits.target), max_att)
229     other_weights, other_total_weight, other_donation_weight = tracker.get_cumulative_weights(previous_share_hash, min(height, chain_length), 65535*max(0, max_att - this_att))
230     assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
231     weights, total_weight, donation_weight = math.add_dicts({new_script: this_att*(65535-donation)}, other_weights), this_att*65535 + other_total_weight, this_att*donation + other_donation_weight
232     assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
233     
234     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
235     
236     # 1 satoshi is always donated so that a list of p2pool generated blocks can be easily found by looking at the donation address
237     amounts = dict((script, (subsidy-1)*(199*weight)//(200*total_weight)) for (script, weight) in weights.iteritems())
238     amounts[new_script] = amounts.get(new_script, 0) + (subsidy-1)//200
239     amounts[SCRIPT] = amounts.get(SCRIPT, 0) + (subsidy-1)*(199*donation_weight)//(200*total_weight)
240     amounts[SCRIPT] = amounts.get(SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra satoshis :P
241     
242     if sum(amounts.itervalues()) != subsidy:
243         raise ValueError()
244     if any(x < 0 for x in amounts.itervalues()):
245         raise ValueError()
246     
247     dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
248     dests = dests[-4000:] # block length limit, unlikely to ever be hit
249     
250     share_info = dict(
251         share_data=share_data,
252         bits=bits,
253         timestamp=math.clip(desired_timestamp, (previous_share.timestamp - 60, previous_share.timestamp + 60)) if previous_share is not None else desired_timestamp,
254     )
255     
256     return share_info, dict(
257         version=1,
258         tx_ins=[dict(
259             previous_output=None,
260             sequence=None,
261             script=share_data['coinbase'].ljust(2, '\x00'),
262         )],
263         tx_outs=[dict(value=0, script='\x20' + bitcoin_data.HashType().pack(share_info_type.hash256(share_info)))] + [dict(value=amounts[script], script=script) for script in dests if amounts[script]],
264         lock_time=0,
265     )
266
267
268 class OkayTrackerDelta(object):
269     __slots__ = 'head height work my_count my_doa_count my_orphan_announce_count my_dead_announce_count tail'.split(' ')
270     
271     @classmethod
272     def get_none(cls, element_id):
273         return cls(element_id, 0, 0, 0, 0, 0, 0, element_id)
274     
275     @classmethod
276     def from_element(cls, share):
277         return cls(share.hash,
278             1, bitcoin_data.target_to_average_attempts(share.target),
279             1 if share.hash in cls.my_share_hashes else 0,
280             1 if share.hash in cls.my_doa_share_hashes else 0,
281             1 if share.hash in cls.my_share_hashes and share.share_data['stale_info'] == 253 else 0,
282             1 if share.hash in cls.my_share_hashes and share.share_data['stale_info'] == 254 else 0,
283         share.previous_hash)
284     
285     def __init__(self, head, height, work, my_count, my_doa_count, my_orphan_announce_count, my_dead_announce_count, tail):
286         self.head, self.height, self.work, self.tail = head, height, work, tail
287         self.my_count, self.my_doa_count, self.my_orphan_announce_count, self.my_dead_announce_count = my_count, my_doa_count, my_orphan_announce_count, my_dead_announce_count
288     
289     def __add__(self, other):
290         assert self.tail == other.head
291         return OkayTrackerDelta(self.head,
292             self.height + other.height, self.work + other.work,
293             self.my_count + other.my_count, self.my_doa_count + other.my_doa_count, self.my_orphan_announce_count + other.my_orphan_announce_count, self.my_dead_announce_count + other.my_dead_announce_count,
294         other.tail)
295     
296     def __sub__(self, other):
297         if self.head == other.head:
298             return OkayTrackerDelta(other.tail, self.height - other.height, self.work - other.work,
299                 self.my_count - other.my_count, self.my_doa_count - other.my_doa_count, self.my_orphan_announce_count - other.my_orphan_announce_count, self.my_dead_announce_count - other.my_dead_announce_count,
300             self.tail)
301         elif self.tail == other.tail:
302             return OkayTrackerDelta(self.head, self.height - other.height, self.work - other.work,
303                 self.my_count - other.my_count, self.my_doa_count - other.my_doa_count, self.my_orphan_announce_count - other.my_orphan_announce_count, self.my_dead_announce_count - other.my_dead_announce_count,
304             other.head)
305         else:
306             raise AssertionError()
307
308 class OkayTracker(forest.Tracker):
309     def __init__(self, net):
310         forest.Tracker.__init__(self)
311         self.net = net
312         self.verified = forest.Tracker(delta_type=OkayTrackerDelta)
313         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
314         
315         self.get_cumulative_weights = skiplists.WeightsSkipList(self)
316     
317     def attempt_verify(self, share):
318         if share.hash in self.verified.shares:
319             return True
320         height, last = self.get_height_and_last(share.hash)
321         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
322             raise AssertionError()
323         try:
324             share.check(self)
325         except:
326             log.err(None, 'Share check failed:')
327             return False
328         else:
329             self.verified.add(share)
330             return True
331     
332     def think(self, ht, previous_block):
333         desired = set()
334         
335         # O(len(self.heads))
336         #   make 'unverified heads' set?
337         # for each overall head, attempt verification
338         # if it fails, attempt on parent, and repeat
339         # if no successful verification because of lack of parents, request parent
340         bads = set()
341         for head in set(self.heads) - set(self.verified.heads):
342             head_height, last = self.get_height_and_last(head)
343             
344             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
345                 if self.attempt_verify(share):
346                     break
347                 if share.hash in self.heads:
348                     bads.add(share.hash)
349             else:
350                 if last is not None:
351                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
352         for bad in bads:
353             assert bad not in self.verified.shares
354             assert bad in self.heads
355             if p2pool.DEBUG:
356                 print "BAD", bad
357             self.remove(bad)
358         
359         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
360         for head in list(self.verified.heads):
361             head_height, last_hash = self.verified.get_height_and_last(head)
362             last_height, last_last_hash = self.get_height_and_last(last_hash)
363             # XXX review boundary conditions
364             want = max(self.net.CHAIN_LENGTH - head_height, 0)
365             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
366             get = min(want, can)
367             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
368             for share in self.get_chain(last_hash, get):
369                 if not self.attempt_verify(share):
370                     break
371             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
372                 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
373         if p2pool.DEBUG:
374             print len(self.verified.tails), "tails:"
375             for x in self.verified.tails:
376                 print format_hash(x), self.score(max(self.verified.tails[x], key=self.verified.get_height), ht)
377         
378         # decide best tree
379         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
380         # decide best verified head
381         scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
382             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
383             #self.verified.shares[h].peer is None,
384             ht.get_height_rel_highest(self.verified.shares[h].previous_block),
385             -self.verified.shares[h].time_seen
386         ))
387         
388         
389         if p2pool.DEBUG:
390             print len(self.verified.tails), "chain tails and", len(self.verified.tails.get(best_tail, [])), 'chain heads. Top 10 heads:'
391             if len(scores) > 10:
392                 print '    ...'
393             for h in scores[-10:]:
394                 print '   ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
395                     self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
396                     self.verified.shares[h].peer is None,
397                     ht.get_height_rel_highest(self.verified.shares[h].previous_block),
398                     -self.verified.shares[h].time_seen
399                 )
400         
401         # eat away at heads
402         if scores:
403             for i in xrange(1000):
404                 to_remove = set()
405                 for share_hash, tail in self.heads.iteritems():
406                     if share_hash in scores[-5:]:
407                         #print 1
408                         continue
409                     if self.shares[share_hash].time_seen > time.time() - 300:
410                         #print 2
411                         continue
412                     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
413                         #print 3
414                         continue
415                     to_remove.add(share_hash)
416                 if not to_remove:
417                     break
418                 for share_hash in to_remove:
419                     self.remove(share_hash)
420                     if share_hash in self.verified.shares:
421                         self.verified.remove(share_hash)
422                 #print "_________", to_remove
423         
424         # drop tails
425         for i in xrange(1000):
426             to_remove = set()
427             for tail, heads in self.tails.iteritems():
428                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
429                     continue
430                 for aftertail in self.reverse_shares.get(tail, set()):
431                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
432                         print "raw"
433                         continue
434                     to_remove.add(aftertail)
435             if not to_remove:
436                 break
437             # if removed from this, it must be removed from verified
438             #start = time.time()
439             for aftertail in to_remove:
440                 if self.shares[aftertail].previous_hash not in self.tails:
441                     print "erk", aftertail, self.shares[aftertail].previous_hash
442                     continue
443                 self.remove(aftertail)
444                 if aftertail in self.verified.shares:
445                     self.verified.remove(aftertail)
446             #end = time.time()
447             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
448         
449         best = scores[-1] if scores else None
450         
451         if best is not None:
452             best_share = self.verified.shares[best]
453             if ht.get_height_rel_highest(best_share.header['previous_block']) < ht.get_height_rel_highest(previous_block) and best_share.header_hash != previous_block and best_share.peer is not None:
454                 if p2pool.DEBUG:
455                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
456                 best = best_share.previous_hash
457         
458         return best, desired
459     
460     def score(self, share_hash, ht):
461         head_height = self.verified.get_height(share_hash)
462         if head_height < self.net.CHAIN_LENGTH:
463             return head_height, None
464         
465         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
466         
467         block_height = max(ht.get_height_rel_highest(share.header['previous_block']) for share in
468             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
469         
470         return self.net.CHAIN_LENGTH, (self.verified.get_work(share_hash) - self.verified.get_work(end_point))//(0 - block_height + 1)
471
472 def format_hash(x):
473     if x is None:
474         return 'xxxxxxxx'
475     return '%08x' % (x % 2**32)
476
477 class ShareStore(object):
478     def __init__(self, prefix, net):
479         self.filename = prefix
480         self.dirname = os.path.dirname(os.path.abspath(prefix))
481         self.filename = os.path.basename(os.path.abspath(prefix))
482         self.net = net
483         self.known = None # will be filename -> set of share hashes, set of verified hashes
484         self.known_desired = None
485     
486     def get_shares(self):
487         if self.known is not None:
488             raise AssertionError()
489         known = {}
490         filenames, next = self.get_filenames_and_next()
491         for filename in filenames:
492             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
493             with open(filename, 'rb') as f:
494                 for line in f:
495                     try:
496                         type_id_str, data_hex = line.strip().split(' ')
497                         type_id = int(type_id_str)
498                         if type_id == 0:
499                             pass
500                         elif type_id == 1:
501                             pass
502                         elif type_id == 2:
503                             verified_hash = int(data_hex, 16)
504                             yield 'verified_hash', verified_hash
505                             verified_hashes.add(verified_hash)
506                         elif type_id == 5:
507                             share = Share.from_share(share_type.unpack(data_hex.decode('hex')), self.net)
508                             yield 'share', share
509                             share_hashes.add(share.hash)
510                         else:
511                             raise NotImplementedError("share type %i" % (type_id,))
512                     except Exception:
513                         log.err(None, "Error while reading saved shares, continuing where left off:")
514         self.known = known
515         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
516     
517     def _add_line(self, line):
518         filenames, next = self.get_filenames_and_next()
519         if filenames and os.path.getsize(filenames[-1]) < 10e6:
520             filename = filenames[-1]
521         else:
522             filename = next
523         
524         with open(filename, 'ab') as f:
525             f.write(line + '\n')
526         
527         return filename
528     
529     def add_share(self, share):
530         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
531             if share.hash in share_hashes:
532                 break
533         else:
534             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
535             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
536             share_hashes.add(share.hash)
537         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
538         share_hashes.add(share.hash)
539     
540     def add_verified_hash(self, share_hash):
541         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
542             if share_hash in verified_hashes:
543                 break
544         else:
545             filename = self._add_line("%i %x" % (2, share_hash))
546             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
547             verified_hashes.add(share_hash)
548         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
549         verified_hashes.add(share_hash)
550     
551     def get_filenames_and_next(self):
552         suffixes = sorted(int(x[len(self.filename):]) for x in os.listdir(self.dirname) if x.startswith(self.filename) and x[len(self.filename):].isdigit())
553         return [os.path.join(self.dirname, self.filename + str(suffix)) for suffix in suffixes], os.path.join(self.dirname, self.filename + (str(suffixes[-1] + 1) if suffixes else str(0)))
554     
555     def forget_share(self, share_hash):
556         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
557             if share_hash in share_hashes:
558                 share_hashes.remove(share_hash)
559         self.check_remove()
560     
561     def forget_verified_share(self, share_hash):
562         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
563             if share_hash in verified_hashes:
564                 verified_hashes.remove(share_hash)
565         self.check_remove()
566     
567     def check_remove(self):
568         to_remove = set()
569         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
570             #print filename, len(share_hashes) + len(verified_hashes)
571             if not share_hashes and not verified_hashes:
572                 to_remove.add(filename)
573         for filename in to_remove:
574             self.known.pop(filename)
575             self.known_desired.pop(filename)
576             os.remove(filename)
577             print "REMOVED", filename