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