3395e6491bfde80952e6e5d471b4e84f46f67db1
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import hashlib
4 import os
5 import random
6 import sys
7 import time
8
9 from twisted.python import log
10
11 import p2pool
12 from p2pool.bitcoin import data as bitcoin_data, script, sha256
13 from p2pool.util import math, forest, pack
14
15 # hashlink
16
17 hash_link_type = pack.ComposedType([
18     ('state', pack.FixedStrType(32)),
19     ('extra_data', pack.FixedStrType(0)), # bit of a hack, but since the donation script is at the end, const_ending is long enough to always make this empty
20     ('length', pack.VarIntType()),
21 ])
22
23 def prefix_to_hash_link(prefix, const_ending=''):
24     assert prefix.endswith(const_ending), (prefix, const_ending)
25     x = sha256.sha256(prefix)
26     return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
27
28 def check_hash_link(hash_link, data, const_ending=''):
29     extra_length = hash_link['length'] % (512//8)
30     assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
31     extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
32     assert len(extra) == extra_length
33     return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
34
35 # shares
36
37 share_type = pack.ComposedType([
38     ('type', pack.VarIntType()),
39     ('contents', pack.VarStrType()),
40 ])
41
42 def load_share(share, net, peer):
43     if share['type'] in [0, 1, 2, 3]:
44         from p2pool import p2p
45         raise p2p.PeerMisbehavingError('sent an obsolete share')
46     elif share['type'] == 4:
47         return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
48     elif share['type'] == 5:
49         share1b = Share.share1b_type.unpack(share['contents'])
50         return Share(net, peer, merkle_link=bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
51     elif share['type'] == NewShare.VERSION:
52         return NewShare(net, peer, NewShare.share_type.unpack(share['contents']))
53     else:
54         raise ValueError('unknown share type: %r' % (share['type'],))
55
56 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
57
58 class Share(object):
59     VERSION = 7
60     SUCCESSOR = None
61     
62     small_block_header_type = pack.ComposedType([
63         ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
64         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
65         ('timestamp', pack.IntType(32)),
66         ('bits', bitcoin_data.FloatingIntegerType()),
67         ('nonce', pack.IntType(32)),
68     ])
69     
70     share_data_type = pack.ComposedType([
71         ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
72         ('coinbase', pack.VarStrType()),
73         ('nonce', pack.IntType(32)),
74         ('pubkey_hash', pack.IntType(160)),
75         ('subsidy', pack.IntType(64)),
76         ('donation', pack.IntType(16)),
77         ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))),
78         ('desired_version', pack.VarIntType()),
79     ])
80     
81     share_info_type = pack.ComposedType([
82         ('share_data', share_data_type),
83         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
84         ('max_bits', bitcoin_data.FloatingIntegerType()),
85         ('bits', bitcoin_data.FloatingIntegerType()),
86         ('timestamp', pack.IntType(32)),
87     ])
88     
89     share_common_type = pack.ComposedType([
90         ('min_header', small_block_header_type),
91         ('share_info', share_info_type),
92         ('ref_merkle_link', pack.ComposedType([
93             ('branch', pack.ListType(pack.IntType(256))),
94             ('index', pack.VarIntType()),
95         ])),
96         ('hash_link', hash_link_type),
97     ])
98     share1a_type = pack.ComposedType([
99         ('common', share_common_type),
100         ('merkle_link', pack.ComposedType([
101             ('branch', pack.ListType(pack.IntType(256))),
102             ('index', pack.IntType(0)), # it will always be 0
103         ])),
104     ])
105     share1b_type = pack.ComposedType([
106         ('common', share_common_type),
107         ('other_txs', pack.ListType(bitcoin_data.tx_type)),
108     ])
109     
110     ref_type = pack.ComposedType([
111         ('identifier', pack.FixedStrType(64//8)),
112         ('share_info', share_info_type),
113     ])
114     
115     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
116     
117     @classmethod
118     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
119         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
120         
121         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
122         assert height >= net.REAL_CHAIN_LENGTH or last is None
123         if height < net.TARGET_LOOKBEHIND:
124             pre_target3 = net.MAX_TARGET
125         else:
126             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
127             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
128             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
129             pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
130         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
131         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
132         
133         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
134             min(height, net.REAL_CHAIN_LENGTH),
135             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
136         )
137         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
138         
139         amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share
140         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
141         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
142         amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding
143         
144         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
145             raise ValueError()
146         
147         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
148         
149         share_info = dict(
150             share_data=share_data,
151             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
152             max_bits=max_bits,
153             bits=bits,
154             timestamp=math.clip(desired_timestamp, (
155                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
156                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
157             )) if previous_share is not None else desired_timestamp,
158         )
159         
160         gentx = dict(
161             version=1,
162             tx_ins=[dict(
163                 previous_output=None,
164                 sequence=None,
165                 script=share_data['coinbase'].ljust(2, '\x00'),
166             )],
167             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
168                 value=0,
169                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
170             )],
171             lock_time=0,
172         )
173         
174         def get_share(header, transactions):
175             assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
176             min_header = dict(header);del min_header['merkle_root']
177             hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
178             merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
179             pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
180             return cls(net, None, dict(
181                 min_header=min_header, share_info=share_info, hash_link=hash_link,
182                 ref_merkle_link=dict(branch=[], index=0),
183             ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
184         
185         return share_info, gentx, desired_other_transaction_hashes, get_share
186     
187     @classmethod
188     def get_ref_hash(cls, net, share_info, ref_merkle_link):
189         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
190             identifier=net.IDENTIFIER,
191             share_info=share_info,
192         ))), ref_merkle_link))
193     
194     __slots__ = 'net peer common min_header share_info hash_link merkle_link other_txs hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash new_transaction_hashes time_seen'.split(' ')
195     
196     def __init__(self, net, peer, common, merkle_link, other_txs):
197         self.net = net
198         self.peer = peer
199         self.common = common
200         self.min_header = common['min_header']
201         self.share_info = common['share_info']
202         self.hash_link = common['hash_link']
203         self.merkle_link = merkle_link
204         self.other_txs = other_txs
205         
206         if len(self.share_info['share_data']['coinbase']) > 100:
207             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
208         
209         if len(merkle_link['branch']) > 16:
210             raise ValueError('merkle branch too long!')
211         
212         if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_link:
213             raise ValueError('merkle_link and other_txs do not match')
214         
215         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
216         
217         self.share_data = self.share_info['share_data']
218         self.max_target = self.share_info['max_bits'].target
219         self.target = self.share_info['bits'].target
220         self.timestamp = self.share_info['timestamp']
221         self.previous_hash = self.share_data['previous_share_hash']
222         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
223         self.desired_version = self.share_data['desired_version']
224         
225         self.gentx_hash = check_hash_link(
226             self.hash_link,
227             self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
228             self.gentx_before_refhash,
229         )
230         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
231         self.header = dict(self.min_header, merkle_root=merkle_root)
232         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
233         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
234         
235         if self.pow_hash > self.target:
236             from p2pool import p2p
237             raise p2p.PeerMisbehavingError('share PoW invalid')
238         
239         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
240             raise ValueError('other_txs provided when not a block solution')
241         if other_txs is None and self.pow_hash <= self.header['bits'].target:
242             raise ValueError('other_txs not provided when a block solution')
243         
244         self.new_transaction_hashes = []
245         
246         # XXX eww
247         self.time_seen = time.time()
248     
249     def __repr__(self):
250         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
251     
252     def as_share1a(self):
253         return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
254     
255     def as_share1b(self):
256         return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
257     
258     def as_share(self):
259         if not self.pow_hash <= self.header['bits'].target: # share1a
260             return self.as_share1a()
261         else:
262             return self.as_share1b()
263     
264     def check(self, tracker):
265         from p2pool import p2p
266         if self.share_data['previous_share_hash'] is not None:
267             previous_share = tracker.items[self.share_data['previous_share_hash']]
268             if type(self) is type(previous_share):
269                 pass
270             elif type(self) is type(previous_share).SUCCESSOR:
271                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
272                     from p2pool import p2p
273                     raise p2p.PeerMisbehavingError('switch without enough history')
274                 
275                 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
276                 counts = get_desired_version_counts(tracker,
277                     tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
278                 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
279                     raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
280             else:
281                 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
282         
283         share_info, gentx, other_transaction_hashes, get_share = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.common['ref_merkle_link'], [], self.net) # ok because desired_other_transaction_hashes is only used in get_share
284         if share_info != self.share_info:
285             raise ValueError('share_info invalid')
286         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
287             raise ValueError('''gentx doesn't match hash_link''')
288         return gentx # only used by as_block
289     
290     def get_other_tx_hashes(self, tracker):
291         return []
292     
293     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
294         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
295             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
296         
297         if self.pow_hash <= self.header['bits'].target:
298             return -1, 'block solution'
299         
300         return False, None
301     
302     def as_block(self, tracker, known_txs):
303         if self.other_txs is None:
304             raise ValueError('share does not contain all txs')
305         return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
306
307 class NewShare(object):
308     VERSION = 8
309     SUCCESSOR = None
310     
311     other_txs = None
312     
313     small_block_header_type = pack.ComposedType([
314         ('version', pack.VarIntType()),
315         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
316         ('timestamp', pack.IntType(32)),
317         ('bits', bitcoin_data.FloatingIntegerType()),
318         ('nonce', pack.IntType(32)),
319     ])
320     
321     share_info_type = pack.ComposedType([
322         ('share_data', pack.ComposedType([
323             ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
324             ('coinbase', pack.VarStrType()),
325             ('nonce', pack.IntType(32)),
326             ('pubkey_hash', pack.IntType(160)),
327             ('subsidy', pack.IntType(64)),
328             ('donation', pack.IntType(16)),
329             ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))),
330             ('desired_version', pack.VarIntType()),
331         ])),
332         ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
333         ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
334             ('share_count', pack.VarIntType()),
335             ('tx_count', pack.VarIntType()),
336         ]))),
337         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
338         ('max_bits', bitcoin_data.FloatingIntegerType()),
339         ('bits', bitcoin_data.FloatingIntegerType()),
340         ('timestamp', pack.IntType(32)),
341     ])
342     
343     share_type = pack.ComposedType([
344         ('min_header', small_block_header_type),
345         ('share_info', share_info_type),
346         ('ref_merkle_link', pack.ComposedType([
347             ('branch', pack.ListType(pack.IntType(256))),
348             ('index', pack.IntType(0)),
349         ])),
350         ('hash_link', hash_link_type),
351         ('merkle_link', pack.ComposedType([
352             ('branch', pack.ListType(pack.IntType(256))),
353             ('index', pack.IntType(0)), # it will always be 0
354         ])),
355     ])
356     
357     ref_type = pack.ComposedType([
358         ('identifier', pack.FixedStrType(64//8)),
359         ('share_info', share_info_type),
360     ])
361     
362     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
363     
364     @classmethod
365     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
366         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
367         
368         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
369         assert height >= net.REAL_CHAIN_LENGTH or last is None
370         if height < net.TARGET_LOOKBEHIND:
371             pre_target3 = net.MAX_TARGET
372         else:
373             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
374             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
375             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
376             pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
377         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
378         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
379         
380         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
381             min(height, net.REAL_CHAIN_LENGTH),
382             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
383         )
384         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
385         
386         amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share
387         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
388         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
389         amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding
390         
391         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
392             raise ValueError()
393         
394         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
395         
396         new_transaction_hashes = []
397         new_transaction_size = 0
398         transaction_hash_refs = []
399         other_transaction_hashes = []
400         
401         for tx_hash in desired_other_transaction_hashes:
402             for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
403                 if tx_hash in share.new_transaction_hashes:
404                     this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
405                     break
406             else:
407                 if known_txs is not None:
408                     this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
409                     if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
410                         break
411                     new_transaction_size += this_size
412                 new_transaction_hashes.append(tx_hash)
413                 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
414             transaction_hash_refs.append(this)
415             other_transaction_hashes.append(tx_hash)
416         
417         share_info = dict(
418             share_data=share_data,
419             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
420             max_bits=max_bits,
421             bits=bits,
422             timestamp=math.clip(desired_timestamp, (
423                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
424                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
425             )) if previous_share is not None else desired_timestamp,
426             new_transaction_hashes=new_transaction_hashes,
427             transaction_hash_refs=transaction_hash_refs,
428         )
429         
430         gentx = dict(
431             version=1,
432             tx_ins=[dict(
433                 previous_output=None,
434                 sequence=None,
435                 script=share_data['coinbase'],
436             )],
437             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
438                 value=0,
439                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
440             )],
441             lock_time=0,
442         )
443         
444         def get_share(header, transactions):
445             min_header=dict(header);del min_header['merkle_root']
446             return cls(net, None, dict(
447                 min_header=min_header,
448                 share_info=share_info,
449                 ref_merkle_link=dict(branch=[], index=0),
450                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
451                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
452             ))
453         
454         return share_info, gentx, other_transaction_hashes, get_share
455     
456     @classmethod
457     def get_ref_hash(cls, net, share_info, ref_merkle_link):
458         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
459             identifier=net.IDENTIFIER,
460             share_info=share_info,
461         ))), ref_merkle_link))
462     
463     __slots__ = 'net peer contents min_header share_info hash_link merkle_link hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash new_transaction_hashes time_seen'.split(' ')
464     
465     def __init__(self, net, peer, contents):
466         self.net = net
467         self.peer = peer
468         self.contents = contents
469         
470         self.min_header = contents['min_header']
471         self.share_info = contents['share_info']
472         self.hash_link = contents['hash_link']
473         self.merkle_link = contents['merkle_link']
474         
475         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
476             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
477         
478         if len(self.merkle_link['branch']) > 16:
479             raise ValueError('merkle branch too long!')
480         
481         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
482         
483         self.share_data = self.share_info['share_data']
484         self.max_target = self.share_info['max_bits'].target
485         self.target = self.share_info['bits'].target
486         self.timestamp = self.share_info['timestamp']
487         self.previous_hash = self.share_data['previous_share_hash']
488         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
489         self.desired_version = self.share_data['desired_version']
490         
491         for x in self.share_info['transaction_hash_refs']:
492             assert x['share_count'] < 110
493         for i, x in enumerate(self.share_info['new_transaction_hashes']):
494             assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
495         
496         self.gentx_hash = check_hash_link(
497             self.hash_link,
498             self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
499             self.gentx_before_refhash,
500         )
501         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
502         self.header = dict(self.min_header, merkle_root=merkle_root)
503         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
504         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
505         
506         if self.target > net.MAX_TARGET:
507             from p2pool import p2p
508             raise p2p.PeerMisbehavingError('share target invalid')
509         
510         if self.pow_hash > self.target:
511             from p2pool import p2p
512             raise p2p.PeerMisbehavingError('share PoW invalid')
513         
514         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
515         
516         # XXX eww
517         self.time_seen = time.time()
518     
519     def __repr__(self):
520         return 'Share' + repr((self.net, self.peer, self.contents))
521     
522     def as_share(self):
523         return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
524     
525     def check(self, tracker):
526         from p2pool import p2p
527         if self.share_data['previous_share_hash'] is not None:
528             previous_share = tracker.items[self.share_data['previous_share_hash']]
529             if type(self) is type(previous_share):
530                 pass
531             elif type(self) is type(previous_share).SUCCESSOR:
532                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
533                     from p2pool import p2p
534                     raise p2p.PeerMisbehavingError('switch without enough history')
535                 
536                 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
537                 counts = get_desired_version_counts(tracker,
538                     tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
539                 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
540                     raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
541             else:
542                 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
543         
544         other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, x['share_count'])].share_info['new_transaction_hashes'][x['tx_count']] for x in self.share_info['transaction_hash_refs']]
545         
546         share_info, gentx, other_tx_hashes2, get_share = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.contents['ref_merkle_link'], other_tx_hashes, self.net)
547         assert other_tx_hashes2 == other_tx_hashes
548         if share_info != self.share_info:
549             raise ValueError('share_info invalid')
550         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
551             raise ValueError('''gentx doesn't match hash_link''')
552         
553         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
554             raise ValueError('merkle_link and other_tx_hashes do not match')
555         
556         return gentx # only used by as_block
557     
558     def get_other_tx_hashes(self, tracker):
559         return [tracker.items[tracker.get_nth_parent_hash(self.hash, x['share_count'])].share_info['new_transaction_hashes'][x['tx_count']] for x in self.share_info['transaction_hash_refs']]
560     
561     def _get_other_txs(self, tracker, known_txs):
562         other_tx_hashes = self.get_other_tx_hashes(tracker)
563         
564         if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
565             return None # not all txs present
566         
567         return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
568     
569     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
570         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
571             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
572         
573         if self.pow_hash <= self.header['bits'].target:
574             return -1, 'block solution'
575         
576         other_txs = self._get_other_txs(tracker, known_txs)
577         if other_txs is None:
578             return True, 'not all txs present'
579         else:
580             all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
581             if all_txs_size > 1000000:
582                 return True, 'txs over block size limit'
583             
584             new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
585             if new_txs_size > 50000:
586                 return True, 'new txs over limit'
587         
588         return False, None
589     
590     def as_block(self, tracker, known_txs):
591         other_txs = self._get_other_txs(tracker, known_txs)
592         if other_txs is None:
593             return None # not all txs present
594         return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
595
596
597 class WeightsSkipList(forest.TrackerSkipList):
598     # share_count, weights, total_weight
599     
600     def get_delta(self, element):
601         from p2pool.bitcoin import data as bitcoin_data
602         share = self.tracker.items[element]
603         att = bitcoin_data.target_to_average_attempts(share.target)
604         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
605     
606     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
607         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
608     
609     def initial_solution(self, start, (max_shares, desired_weight)):
610         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
611         return 0, None, 0, 0
612     
613     def apply_delta(self, (share_count1, weights_list, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2), (max_shares, desired_weight)):
614         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
615             assert (desired_weight - total_weight1) % 65535 == 0
616             script, = weights2.iterkeys()
617             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
618             return share_count1 + share_count2, (weights_list, new_weights), desired_weight, total_donation_weight1 + (desired_weight - total_weight1)//65535*total_donation_weight2//(total_weight2//65535)
619         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
620     
621     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
622         if share_count > max_shares or total_weight > desired_weight:
623             return 1
624         elif share_count == max_shares or total_weight == desired_weight:
625             return 0
626         else:
627             return -1
628     
629     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
630         assert share_count <= max_shares and total_weight <= desired_weight
631         assert share_count == max_shares or total_weight == desired_weight
632         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
633
634 class OkayTracker(forest.Tracker):
635     def __init__(self, net):
636         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
637             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
638             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
639         )))
640         self.net = net
641         self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
642             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
643         )), subset_of=self)
644         self.get_cumulative_weights = WeightsSkipList(self)
645     
646     def attempt_verify(self, share):
647         if share.hash in self.verified.items:
648             return True
649         height, last = self.get_height_and_last(share.hash)
650         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
651             raise AssertionError()
652         try:
653             share.check(self)
654         except:
655             log.err(None, 'Share check failed:')
656             return False
657         else:
658             self.verified.add(share)
659             return True
660     
661     def think(self, block_rel_height_func, previous_block, bits, known_txs):
662         desired = set()
663         
664         # O(len(self.heads))
665         #   make 'unverified heads' set?
666         # for each overall head, attempt verification
667         # if it fails, attempt on parent, and repeat
668         # if no successful verification because of lack of parents, request parent
669         bads = set()
670         for head in set(self.heads) - set(self.verified.heads):
671             head_height, last = self.get_height_and_last(head)
672             
673             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
674                 if self.attempt_verify(share):
675                     break
676                 if share.hash in self.heads:
677                     bads.add(share.hash)
678             else:
679                 if last is not None:
680                     desired.add((
681                         self.items[random.choice(list(self.reverse[last]))].peer,
682                         last,
683                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
684                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
685                     ))
686         for bad in bads:
687             assert bad not in self.verified.items
688             assert bad in self.heads
689             if p2pool.DEBUG:
690                 print "BAD", bad
691             self.remove(bad)
692         
693         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
694         for head in list(self.verified.heads):
695             head_height, last_hash = self.verified.get_height_and_last(head)
696             last_height, last_last_hash = self.get_height_and_last(last_hash)
697             # XXX review boundary conditions
698             want = max(self.net.CHAIN_LENGTH - head_height, 0)
699             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
700             get = min(want, can)
701             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
702             for share in self.get_chain(last_hash, get):
703                 if not self.attempt_verify(share):
704                     break
705             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
706                 desired.add((
707                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
708                     last_last_hash,
709                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
710                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
711                 ))
712         
713         # decide best tree
714         decorated_tails = sorted((self.score(max(self.verified.tails[tail_hash], key=self.verified.get_work), block_rel_height_func), tail_hash) for tail_hash in self.verified.tails)
715         if p2pool.DEBUG:
716             print len(decorated_tails), 'tails:'
717             for score, tail_hash in decorated_tails:
718                 print format_hash(tail_hash), score
719         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
720         
721         # decide best verified head
722         decorated_heads = sorted(((
723             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
724             #self.items[h].peer is None,
725             -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
726             -self.items[h].time_seen,
727         ), h) for h in self.verified.tails.get(best_tail, []))
728         if p2pool.DEBUG:
729             print len(decorated_heads), 'heads. Top 10:'
730             for score, head_hash in decorated_heads[-10:]:
731                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
732         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
733         
734         if best is not None:
735             best_share = self.items[best]
736             punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
737             if punish > 0:
738                 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
739                 best = best_share.previous_hash
740             
741             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
742             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
743         else:
744             timestamp_cutoff = int(time.time()) - 24*60*60
745             target_cutoff = 2**256-1
746         
747         if p2pool.DEBUG:
748             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))
749             for peer, hash, ts, targ in desired:
750                 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
751         
752         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
753     
754     def score(self, share_hash, block_rel_height_func):
755         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
756         
757         head_height = self.verified.get_height(share_hash)
758         if head_height < self.net.CHAIN_LENGTH:
759             return head_height, None
760         
761         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
762         
763         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
764             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
765         
766         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
767
768 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
769     assert dist >= 2
770     near = tracker.items[previous_share_hash]
771     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
772     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
773     time = near.timestamp - far.timestamp
774     if time <= 0:
775         time = 1
776     if integer:
777         return attempts//time
778     return attempts/time
779
780 def get_average_stale_prop(tracker, share_hash, lookbehind):
781     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
782     return stales/(lookbehind + stales)
783
784 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
785     res = {}
786     for share in tracker.get_chain(share_hash, lookbehind - 1):
787         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
788         s = share.share_data['stale_info']
789         if s is not None:
790             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
791     if rates:
792         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
793         res = dict((k, v/dt) for k, v in res.iteritems())
794     return res
795
796 def get_user_stale_props(tracker, share_hash, lookbehind):
797     res = {}
798     for share in tracker.get_chain(share_hash, lookbehind - 1):
799         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
800         total += 1
801         if share.share_data['stale_info'] is not None:
802             stale += 1
803             total += 1
804         res[share.share_data['pubkey_hash']] = stale, total
805     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
806
807 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
808     weights, total_weight, donation_weight = tracker.get_cumulative_weights(best_share_hash, min(tracker.get_height(best_share_hash), net.REAL_CHAIN_LENGTH), 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target))
809     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
810     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
811     return res
812
813 def get_desired_version_counts(tracker, best_share_hash, dist):
814     res = {}
815     for share in tracker.get_chain(best_share_hash, dist):
816         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
817     return res
818
819 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
820     res = []
821     
822     desired_version_counts = get_desired_version_counts(tracker, best_share,
823         min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
824     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
825     if majority_desired_version > NewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
826         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
827             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
828                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
829     
830     if bitcoind_warning is not None:
831         res.append('(from bitcoind) %s' % (bitcoind_warning,))
832     
833     if time.time() > bitcoind_work_value['last_update'] + 60:
834         res.append('''LOST CONTACT WITH BITCOIND for %s! Check that it isn't frozen or dead!''' % (math.format_dt(time.time() - bitcoind_work_value['last_update']),))
835     
836     return res
837
838 def format_hash(x):
839     if x is None:
840         return 'xxxxxxxx'
841     return '%08x' % (x % 2**32)
842
843 class ShareStore(object):
844     def __init__(self, prefix, net):
845         self.filename = prefix
846         self.dirname = os.path.dirname(os.path.abspath(prefix))
847         self.filename = os.path.basename(os.path.abspath(prefix))
848         self.net = net
849         self.known = None # will be filename -> set of share hashes, set of verified hashes
850         self.known_desired = None
851     
852     def get_shares(self):
853         if self.known is not None:
854             raise AssertionError()
855         known = {}
856         filenames, next = self.get_filenames_and_next()
857         for filename in filenames:
858             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
859             with open(filename, 'rb') as f:
860                 for line in f:
861                     try:
862                         type_id_str, data_hex = line.strip().split(' ')
863                         type_id = int(type_id_str)
864                         if type_id == 0:
865                             pass
866                         elif type_id == 1:
867                             pass
868                         elif type_id == 2:
869                             verified_hash = int(data_hex, 16)
870                             yield 'verified_hash', verified_hash
871                             verified_hashes.add(verified_hash)
872                         elif type_id == 5:
873                             raw_share = share_type.unpack(data_hex.decode('hex'))
874                             if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
875                                 continue
876                             share = load_share(raw_share, self.net, None)
877                             yield 'share', share
878                             share_hashes.add(share.hash)
879                         else:
880                             raise NotImplementedError("share type %i" % (type_id,))
881                     except Exception:
882                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
883         self.known = known
884         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
885     
886     def _add_line(self, line):
887         filenames, next = self.get_filenames_and_next()
888         if filenames and os.path.getsize(filenames[-1]) < 10e6:
889             filename = filenames[-1]
890         else:
891             filename = next
892         
893         with open(filename, 'ab') as f:
894             f.write(line + '\n')
895         
896         return filename
897     
898     def add_share(self, share):
899         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
900             if share.hash in share_hashes:
901                 break
902         else:
903             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
904             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
905             share_hashes.add(share.hash)
906         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
907         share_hashes.add(share.hash)
908     
909     def add_verified_hash(self, share_hash):
910         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
911             if share_hash in verified_hashes:
912                 break
913         else:
914             filename = self._add_line("%i %x" % (2, share_hash))
915             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
916             verified_hashes.add(share_hash)
917         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
918         verified_hashes.add(share_hash)
919     
920     def get_filenames_and_next(self):
921         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())
922         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)))
923     
924     def forget_share(self, share_hash):
925         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
926             if share_hash in share_hashes:
927                 share_hashes.remove(share_hash)
928         self.check_remove()
929     
930     def forget_verified_share(self, share_hash):
931         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
932             if share_hash in verified_hashes:
933                 verified_hashes.remove(share_hash)
934         self.check_remove()
935     
936     def check_remove(self):
937         to_remove = set()
938         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
939             #print filename, len(share_hashes) + len(verified_hashes)
940             if not share_hashes and not verified_hashes:
941                 to_remove.add(filename)
942         for filename in to_remove:
943             self.known.pop(filename)
944             self.known_desired.pop(filename)
945             os.remove(filename)
946             print "REMOVED", filename