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