1 from __future__ import division
9 from twisted.python import log
12 from p2pool.bitcoin import data as bitcoin_data, script, sha256
13 from p2pool.util import math, forest, pack
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()),
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)
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())
37 share_type = pack.ComposedType([
38 ('type', pack.VarIntType()),
39 ('contents', pack.VarStrType()),
42 def load_share(share, net, peer_addr):
43 assert peer_addr is None or isinstance(peer_addr, tuple)
44 if share['type'] < Share.VERSION:
45 from p2pool import p2p
46 raise p2p.PeerMisbehavingError('sent an obsolete share')
47 elif share['type'] == Share.VERSION:
48 return Share(net, peer_addr, Share.share_type.unpack(share['contents']))
49 elif share['type'] == NewShare.VERSION:
50 return NewShare(net, peer_addr, NewShare.share_type.unpack(share['contents']))
52 raise ValueError('unknown share type: %r' % (share['type'],))
54 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
56 class NewShare(object):
61 small_block_header_type = pack.ComposedType([
62 ('version', pack.VarIntType()),
63 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
64 ('timestamp', pack.IntType(32)),
65 ('bits', bitcoin_data.FloatingIntegerType()),
66 ('nonce', pack.IntType(32)),
69 share_info_type = pack.ComposedType([
70 ('share_data', 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()),
80 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
81 ('transaction_hash_refs', pack.ListType(pack.VarIntType(), 2)), # pairs of share_count, tx_count
82 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
83 ('max_bits', bitcoin_data.FloatingIntegerType()),
84 ('bits', bitcoin_data.FloatingIntegerType()),
85 ('timestamp', pack.IntType(32)),
88 share_type = pack.ComposedType([
89 ('min_header', small_block_header_type),
90 ('share_info', share_info_type),
91 ('ref_merkle_link', pack.ComposedType([
92 ('branch', pack.ListType(pack.IntType(256))),
93 ('index', pack.IntType(0)),
95 ('last_txout_nonce', pack.IntType(64)),
96 ('hash_link', hash_link_type),
97 ('merkle_link', pack.ComposedType([
98 ('branch', pack.ListType(pack.IntType(256))),
99 ('index', pack.IntType(0)), # it will always be 0
103 ref_type = pack.ComposedType([
104 ('identifier', pack.FixedStrType(64//8)),
105 ('share_info', share_info_type),
108 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x6a\x28' + pack.IntType(256).pack(0) + pack.IntType(64).pack(0))[:3]
111 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes_and_fees, net, known_txs=None, last_txout_nonce=0, base_subsidy=None):
112 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
114 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
115 assert height >= net.REAL_CHAIN_LENGTH or last is None
116 if height < net.TARGET_LOOKBEHIND:
117 pre_target3 = net.MAX_TARGET
119 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
120 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
121 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
122 pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
123 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
124 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
126 new_transaction_hashes = []
127 new_transaction_size = 0
128 transaction_hash_refs = []
129 other_transaction_hashes = []
131 past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100)))
133 for i, share in enumerate(past_shares):
134 for j, tx_hash in enumerate(share.new_transaction_hashes):
135 if tx_hash not in tx_hash_to_this:
136 tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count
137 for tx_hash, fee in desired_other_transaction_hashes_and_fees:
138 if tx_hash in tx_hash_to_this:
139 this = tx_hash_to_this[tx_hash]
141 if known_txs is not None:
142 this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
143 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
145 new_transaction_size += this_size
146 new_transaction_hashes.append(tx_hash)
147 this = [0, len(new_transaction_hashes)-1]
148 transaction_hash_refs.extend(this)
149 other_transaction_hashes.append(tx_hash)
151 included_transactions = set(other_transaction_hashes)
152 removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions]
153 definite_fees = sum(0 if fee is None else fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash in included_transactions)
154 if None not in removed_fees:
155 share_data = dict(share_data, subsidy=share_data['subsidy'] - sum(removed_fees))
157 assert base_subsidy is not None
158 share_data = dict(share_data, subsidy=base_subsidy + definite_fees)
160 weights, total_weight, donation_weight = tracker.get_cumulative_weights(previous_share.share_data['previous_share_hash'] if previous_share is not None else None,
161 min(height, net.REAL_CHAIN_LENGTH-1),
162 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
164 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
166 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
167 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
168 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
169 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
171 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
174 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
177 share_data=share_data,
178 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
181 timestamp=math.clip(desired_timestamp, (
182 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
183 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
184 )) if previous_share is not None else desired_timestamp,
185 new_transaction_hashes=new_transaction_hashes,
186 transaction_hash_refs=transaction_hash_refs,
192 previous_output=None,
194 script=share_data['coinbase'],
196 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
198 script='\x6a\x28' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(64).pack(last_txout_nonce),
203 def get_share(header, last_txout_nonce=last_txout_nonce):
204 min_header = dict(header); del min_header['merkle_root']
205 share = cls(net, None, dict(
206 min_header=min_header,
207 share_info=share_info,
208 ref_merkle_link=dict(branch=[], index=0),
209 last_txout_nonce=last_txout_nonce*2**32,
210 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-8-4], cls.gentx_before_refhash),
211 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
213 assert share.header == header # checks merkle_root
216 return share_info, gentx, other_transaction_hashes, get_share
219 def get_ref_hash(cls, net, share_info, ref_merkle_link):
220 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
221 identifier=net.IDENTIFIER,
222 share_info=share_info,
223 ))), ref_merkle_link))
225 __slots__ = 'net peer_addr 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(' ')
227 def __init__(self, net, peer_addr, contents):
229 self.peer_addr = peer_addr
230 self.contents = contents
232 self.min_header = contents['min_header']
233 self.share_info = contents['share_info']
234 self.hash_link = contents['hash_link']
235 self.merkle_link = contents['merkle_link']
237 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
238 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
240 if len(self.merkle_link['branch']) > 16:
241 raise ValueError('merkle branch too long!')
243 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
245 self.share_data = self.share_info['share_data']
246 self.max_target = self.share_info['max_bits'].target
247 self.target = self.share_info['bits'].target
248 self.timestamp = self.share_info['timestamp']
249 self.previous_hash = self.share_data['previous_share_hash']
250 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
251 self.desired_version = self.share_data['desired_version']
254 for share_count, tx_count in self.iter_transaction_hash_refs():
255 assert share_count < 110
258 assert n == set(range(len(self.share_info['new_transaction_hashes'])))
260 self.gentx_hash = check_hash_link(
262 self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(64).pack(self.contents['last_txout_nonce']) + pack.IntType(32).pack(0),
263 self.gentx_before_refhash,
265 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
266 self.header = dict(self.min_header, merkle_root=merkle_root)
267 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
268 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
270 if self.target > net.MAX_TARGET:
271 from p2pool import p2p
272 raise p2p.PeerMisbehavingError('share target invalid')
274 if self.pow_hash > self.target:
275 from p2pool import p2p
276 raise p2p.PeerMisbehavingError('share PoW invalid')
278 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
281 self.time_seen = time.time()
284 return 'Share' + repr((self.net, self.peer_addr, self.contents))
287 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
289 def iter_transaction_hash_refs(self):
290 return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2])
292 def check(self, tracker):
293 from p2pool import p2p
294 if self.share_data['previous_share_hash'] is not None:
295 previous_share = tracker.items[self.share_data['previous_share_hash']]
296 if type(self) is type(previous_share):
298 elif type(self) is type(previous_share).SUCCESSOR:
299 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
300 from p2pool import p2p
301 raise p2p.PeerMisbehavingError('switch without enough history')
303 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
304 counts = get_desired_version_counts(tracker,
305 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
306 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
307 raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
309 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
311 other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, share_count)].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
313 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'], [(h, None) for h in other_tx_hashes], self.net, last_txout_nonce=self.contents['last_txout_nonce'])
314 assert other_tx_hashes2 == other_tx_hashes
315 if share_info != self.share_info:
316 raise ValueError('share_info invalid')
317 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
318 raise ValueError('''gentx doesn't match hash_link''')
320 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
321 raise ValueError('merkle_link and other_tx_hashes do not match')
323 return gentx # only used by as_block
325 def get_other_tx_hashes(self, tracker):
326 parents_needed = max(share_count for share_count, tx_count in self.iter_transaction_hash_refs()) if self.share_info['transaction_hash_refs'] else 0
327 parents = tracker.get_height(self.hash) - 1
328 if parents < parents_needed:
330 last_shares = list(tracker.get_chain(self.hash, parents_needed + 1))
331 return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
333 def _get_other_txs(self, tracker, known_txs):
334 other_tx_hashes = self.get_other_tx_hashes(tracker)
335 if other_tx_hashes is None:
336 return None # not all parents present
338 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
339 return None # not all txs present
341 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
343 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
344 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None:
345 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
347 if self.pow_hash <= self.header['bits'].target:
348 return -1, 'block solution'
350 other_txs = self._get_other_txs(tracker, known_txs)
351 if other_txs is None:
352 if self.time_seen != 0: # ignore if loaded from ShareStore
353 return True, 'not all txs present'
355 all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
356 if all_txs_size > 1000000:
357 return True, 'txs over block size limit'
359 new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
360 if new_txs_size > 50000:
361 return True, 'new txs over limit'
365 def as_block(self, tracker, known_txs):
366 other_txs = self._get_other_txs(tracker, known_txs)
367 if other_txs is None:
368 return None # not all txs present
369 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
376 small_block_header_type = pack.ComposedType([
377 ('version', pack.VarIntType()),
378 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
379 ('timestamp', pack.IntType(32)),
380 ('bits', bitcoin_data.FloatingIntegerType()),
381 ('nonce', pack.IntType(32)),
384 share_info_type = pack.ComposedType([
385 ('share_data', pack.ComposedType([
386 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
387 ('coinbase', pack.VarStrType()),
388 ('nonce', pack.IntType(32)),
389 ('pubkey_hash', pack.IntType(160)),
390 ('subsidy', pack.IntType(64)),
391 ('donation', pack.IntType(16)),
392 ('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)))),
393 ('desired_version', pack.VarIntType()),
395 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
396 ('transaction_hash_refs', pack.ListType(pack.VarIntType(), 2)), # pairs of share_count, tx_count
397 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
398 ('max_bits', bitcoin_data.FloatingIntegerType()),
399 ('bits', bitcoin_data.FloatingIntegerType()),
400 ('timestamp', pack.IntType(32)),
403 share_type = pack.ComposedType([
404 ('min_header', small_block_header_type),
405 ('share_info', share_info_type),
406 ('ref_merkle_link', pack.ComposedType([
407 ('branch', pack.ListType(pack.IntType(256))),
408 ('index', pack.IntType(0)),
410 ('last_txout_nonce', pack.IntType(32)),
411 ('hash_link', hash_link_type),
412 ('merkle_link', pack.ComposedType([
413 ('branch', pack.ListType(pack.IntType(256))),
414 ('index', pack.IntType(0)), # it will always be 0
418 ref_type = pack.ComposedType([
419 ('identifier', pack.FixedStrType(64//8)),
420 ('share_info', share_info_type),
423 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x24' + pack.IntType(256).pack(0) + pack.IntType(32).pack(0))[:2]
426 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes_and_fees, net, known_txs=None, last_txout_nonce=0, base_subsidy=None):
427 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
429 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
430 assert height >= net.REAL_CHAIN_LENGTH or last is None
431 if height < net.TARGET_LOOKBEHIND:
432 pre_target3 = net.MAX_TARGET
434 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
435 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
436 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
437 pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
438 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
439 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
441 new_transaction_hashes = []
442 new_transaction_size = 0
443 transaction_hash_refs = []
444 other_transaction_hashes = []
446 past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100)))
448 for i, share in enumerate(past_shares):
449 for j, tx_hash in enumerate(share.new_transaction_hashes):
450 if tx_hash not in tx_hash_to_this:
451 tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count
452 for tx_hash, fee in desired_other_transaction_hashes_and_fees:
453 if tx_hash in tx_hash_to_this:
454 this = tx_hash_to_this[tx_hash]
456 if known_txs is not None:
457 this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
458 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
460 new_transaction_size += this_size
461 new_transaction_hashes.append(tx_hash)
462 this = [0, len(new_transaction_hashes)-1]
463 transaction_hash_refs.extend(this)
464 other_transaction_hashes.append(tx_hash)
466 included_transactions = set(other_transaction_hashes)
467 removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions]
468 definite_fees = sum(0 if fee is None else fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash in included_transactions)
469 if None not in removed_fees:
470 share_data = dict(share_data, subsidy=share_data['subsidy'] - sum(removed_fees))
472 assert base_subsidy is not None
473 share_data = dict(share_data, subsidy=base_subsidy + definite_fees)
475 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
476 min(height, net.REAL_CHAIN_LENGTH),
477 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
479 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
481 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
482 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
483 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
484 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
486 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
489 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
492 share_data=share_data,
493 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
496 timestamp=math.clip(desired_timestamp, (
497 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
498 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
499 )) if previous_share is not None else desired_timestamp,
500 new_transaction_hashes=new_transaction_hashes,
501 transaction_hash_refs=transaction_hash_refs,
507 previous_output=None,
509 script=share_data['coinbase'],
511 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
513 script='\x24' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(32).pack(last_txout_nonce),
518 def get_share(header, last_txout_nonce=last_txout_nonce):
519 min_header = dict(header); del min_header['merkle_root']
520 share = cls(net, None, dict(
521 min_header=min_header,
522 share_info=share_info,
523 ref_merkle_link=dict(branch=[], index=0),
524 last_txout_nonce=last_txout_nonce,
525 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4-4], cls.gentx_before_refhash),
526 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
528 assert share.header == header # checks merkle_root
531 return share_info, gentx, other_transaction_hashes, get_share
534 def get_ref_hash(cls, net, share_info, ref_merkle_link):
535 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
536 identifier=net.IDENTIFIER,
537 share_info=share_info,
538 ))), ref_merkle_link))
540 __slots__ = 'net peer_addr 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(' ')
542 def __init__(self, net, peer_addr, contents):
544 self.peer_addr = peer_addr
545 self.contents = contents
547 self.min_header = contents['min_header']
548 self.share_info = contents['share_info']
549 self.hash_link = contents['hash_link']
550 self.merkle_link = contents['merkle_link']
552 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
553 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
555 if len(self.merkle_link['branch']) > 16:
556 raise ValueError('merkle branch too long!')
558 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
560 self.share_data = self.share_info['share_data']
561 self.max_target = self.share_info['max_bits'].target
562 self.target = self.share_info['bits'].target
563 self.timestamp = self.share_info['timestamp']
564 self.previous_hash = self.share_data['previous_share_hash']
565 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
566 self.desired_version = self.share_data['desired_version']
569 for share_count, tx_count in self.iter_transaction_hash_refs():
570 assert share_count < 110
573 assert n == set(range(len(self.share_info['new_transaction_hashes'])))
575 self.gentx_hash = check_hash_link(
577 self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(self.contents['last_txout_nonce']) + pack.IntType(32).pack(0),
578 self.gentx_before_refhash,
580 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
581 self.header = dict(self.min_header, merkle_root=merkle_root)
582 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
583 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
585 if self.target > net.MAX_TARGET:
586 from p2pool import p2p
587 raise p2p.PeerMisbehavingError('share target invalid')
589 if self.pow_hash > self.target:
590 from p2pool import p2p
591 raise p2p.PeerMisbehavingError('share PoW invalid')
593 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
596 self.time_seen = time.time()
599 return 'Share' + repr((self.net, self.peer_addr, self.contents))
602 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
604 def iter_transaction_hash_refs(self):
605 return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2])
607 def check(self, tracker):
608 from p2pool import p2p
609 if self.share_data['previous_share_hash'] is not None:
610 previous_share = tracker.items[self.share_data['previous_share_hash']]
611 if type(self) is type(previous_share):
613 elif type(self) is type(previous_share).SUCCESSOR:
614 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
615 from p2pool import p2p
616 raise p2p.PeerMisbehavingError('switch without enough history')
618 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
619 counts = get_desired_version_counts(tracker,
620 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
621 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
622 raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
624 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
626 other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, share_count)].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
628 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'], [(h, None) for h in other_tx_hashes], self.net, last_txout_nonce=self.contents['last_txout_nonce'])
629 assert other_tx_hashes2 == other_tx_hashes
630 if share_info != self.share_info:
631 raise ValueError('share_info invalid')
632 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
633 raise ValueError('''gentx doesn't match hash_link''')
635 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
636 raise ValueError('merkle_link and other_tx_hashes do not match')
638 return gentx # only used by as_block
640 def get_other_tx_hashes(self, tracker):
641 parents_needed = max(share_count for share_count, tx_count in self.iter_transaction_hash_refs()) if self.share_info['transaction_hash_refs'] else 0
642 parents = tracker.get_height(self.hash) - 1
643 if parents < parents_needed:
645 last_shares = list(tracker.get_chain(self.hash, parents_needed + 1))
646 return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
648 def _get_other_txs(self, tracker, known_txs):
649 other_tx_hashes = self.get_other_tx_hashes(tracker)
650 if other_tx_hashes is None:
651 return None # not all parents present
653 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
654 return None # not all txs present
656 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
658 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
659 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None:
660 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
662 if self.pow_hash <= self.header['bits'].target:
663 return -1, 'block solution'
665 other_txs = self._get_other_txs(tracker, known_txs)
666 if other_txs is None:
667 if self.time_seen != 0: # ignore if loaded from ShareStore
668 return True, 'not all txs present'
670 all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
671 if all_txs_size > 1000000:
672 return True, 'txs over block size limit'
674 new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
675 if new_txs_size > 50000:
676 return True, 'new txs over limit'
680 def as_block(self, tracker, known_txs):
681 other_txs = self._get_other_txs(tracker, known_txs)
682 if other_txs is None:
683 return None # not all txs present
684 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
688 class WeightsSkipList(forest.TrackerSkipList):
689 # share_count, weights, total_weight
691 def get_delta(self, element):
692 from p2pool.bitcoin import data as bitcoin_data
693 share = self.tracker.items[element]
694 att = bitcoin_data.target_to_average_attempts(share.target)
695 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
697 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
698 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
700 def initial_solution(self, start, (max_shares, desired_weight)):
701 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
704 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)):
705 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
706 assert (desired_weight - total_weight1) % 65535 == 0
707 script, = weights2.iterkeys()
708 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
709 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)
710 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
712 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
713 if share_count > max_shares or total_weight > desired_weight:
715 elif share_count == max_shares or total_weight == desired_weight:
720 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
721 assert share_count <= max_shares and total_weight <= desired_weight
722 assert share_count == max_shares or total_weight == desired_weight
723 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
725 class OkayTracker(forest.Tracker):
726 def __init__(self, net):
727 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
728 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
729 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
732 self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
733 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
735 self.get_cumulative_weights = WeightsSkipList(self)
737 def attempt_verify(self, share):
738 if share.hash in self.verified.items:
740 height, last = self.get_height_and_last(share.hash)
741 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
742 raise AssertionError()
746 log.err(None, 'Share check failed:')
749 self.verified.add(share)
752 def think(self, block_rel_height_func, previous_block, bits, known_txs):
756 # make 'unverified heads' set?
757 # for each overall head, attempt verification
758 # if it fails, attempt on parent, and repeat
759 # if no successful verification because of lack of parents, request parent
761 for head in set(self.heads) - set(self.verified.heads):
762 head_height, last = self.get_height_and_last(head)
764 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
765 if self.attempt_verify(share):
767 if share.hash in self.heads:
772 self.items[random.choice(list(self.reverse[last]))].peer_addr,
774 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
775 min(x.target for x in self.get_chain(head, min(head_height, 5))),
778 assert bad not in self.verified.items
779 assert bad in self.heads
784 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
785 for head in list(self.verified.heads):
786 head_height, last_hash = self.verified.get_height_and_last(head)
787 last_height, last_last_hash = self.get_height_and_last(last_hash)
788 # XXX review boundary conditions
789 want = max(self.net.CHAIN_LENGTH - head_height, 0)
790 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
792 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
793 for share in self.get_chain(last_hash, get):
794 if not self.attempt_verify(share):
796 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
798 self.items[random.choice(list(self.verified.reverse[last_hash]))].peer_addr,
800 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
801 min(x.target for x in self.get_chain(head, min(head_height, 5))),
805 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)
807 print len(decorated_tails), 'tails:'
808 for score, tail_hash in decorated_tails:
809 print format_hash(tail_hash), score
810 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
812 # decide best verified head
813 decorated_heads = sorted(((
814 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
815 #self.items[h].peer_addr is None,
816 -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
817 -self.items[h].time_seen,
818 ), h) for h in self.verified.tails.get(best_tail, []))
820 print len(decorated_heads), 'heads. Top 10:'
821 for score, head_hash in decorated_heads[-10:]:
822 print ' ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
823 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
826 best_share = self.items[best]
827 punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
829 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
830 best = best_share.previous_hash
832 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
833 target_cutoff = int(2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 + .5) if best_tail_score[1] is not None else 2**256-1
835 timestamp_cutoff = int(time.time()) - 24*60*60
836 target_cutoff = 2**256-1
839 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))
840 for peer_addr, hash, ts, targ in desired:
841 print ' ', None if peer_addr is None else '%s:%i' % peer_addr, format_hash(hash), math.format_dt(time.time() - ts), bitcoin_data.target_to_difficulty(targ), ts >= timestamp_cutoff, targ <= target_cutoff
843 return best, [(peer_addr, hash) for peer_addr, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
845 def score(self, share_hash, block_rel_height_func):
846 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
848 head_height = self.verified.get_height(share_hash)
849 if head_height < self.net.CHAIN_LENGTH:
850 return head_height, None
852 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
854 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
855 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
857 return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work/((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
859 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
861 near = tracker.items[previous_share_hash]
862 far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
863 attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
864 time = near.timestamp - far.timestamp
868 return attempts//time
871 def get_average_stale_prop(tracker, share_hash, lookbehind):
872 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
873 return stales/(lookbehind + stales)
875 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
877 for share in tracker.get_chain(share_hash, lookbehind - 1):
878 res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
879 s = share.share_data['stale_info']
881 res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
883 dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
884 res = dict((k, v/dt) for k, v in res.iteritems())
887 def get_user_stale_props(tracker, share_hash, lookbehind):
889 for share in tracker.get_chain(share_hash, lookbehind - 1):
890 stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
892 if share.share_data['stale_info'] is not None:
895 res[share.share_data['pubkey_hash']] = stale, total
896 return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
898 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
899 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))
900 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
901 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
904 def get_desired_version_counts(tracker, best_share_hash, dist):
906 for share in tracker.get_chain(best_share_hash, dist):
907 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
910 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
913 desired_version_counts = get_desired_version_counts(tracker, best_share,
914 min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
915 majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
916 if majority_desired_version > (Share.SUCCESSOR if Share.SUCCESSOR is not None else Share).VOTING_VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
917 res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
918 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
919 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
921 if bitcoind_warning is not None:
922 if 'This is a pre-release test build' not in bitcoind_warning:
923 res.append('(from bitcoind) %s' % (bitcoind_warning,))
925 if time.time() > bitcoind_work_value['last_update'] + 60:
926 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']),))
933 return '%08x' % (x % 2**32)
935 class ShareStore(object):
936 def __init__(self, prefix, net):
937 self.filename = prefix
938 self.dirname = os.path.dirname(os.path.abspath(prefix))
939 self.filename = os.path.basename(os.path.abspath(prefix))
941 self.known = None # will be filename -> set of share hashes, set of verified hashes
942 self.known_desired = None
944 def get_shares(self):
945 if self.known is not None:
946 raise AssertionError()
948 filenames, next = self.get_filenames_and_next()
949 for filename in filenames:
950 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
951 with open(filename, 'rb') as f:
954 type_id_str, data_hex = line.strip().split(' ')
955 type_id = int(type_id_str)
961 verified_hash = int(data_hex, 16)
962 yield 'verified_hash', verified_hash
963 verified_hashes.add(verified_hash)
965 raw_share = share_type.unpack(data_hex.decode('hex'))
966 if raw_share['type'] in [0, 1, 2, 3, 4, 5, 6, 7, 8]:
968 share = load_share(raw_share, self.net, None)
970 share_hashes.add(share.hash)
972 raise NotImplementedError("share type %i" % (type_id,))
974 log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
976 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
978 def _add_line(self, line):
979 filenames, next = self.get_filenames_and_next()
980 if filenames and os.path.getsize(filenames[-1]) < 10e6:
981 filename = filenames[-1]
985 with open(filename, 'ab') as f:
990 def add_share(self, share):
991 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
992 if share.hash in share_hashes:
995 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
996 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
997 share_hashes.add(share.hash)
998 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
999 share_hashes.add(share.hash)
1001 def add_verified_hash(self, share_hash):
1002 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
1003 if share_hash in verified_hashes:
1006 filename = self._add_line("%i %x" % (2, share_hash))
1007 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
1008 verified_hashes.add(share_hash)
1009 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
1010 verified_hashes.add(share_hash)
1012 def get_filenames_and_next(self):
1013 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())
1014 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)))
1016 def forget_share(self, share_hash):
1017 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1018 if share_hash in share_hashes:
1019 share_hashes.remove(share_hash)
1022 def forget_verified_share(self, share_hash):
1023 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1024 if share_hash in verified_hashes:
1025 verified_hashes.remove(share_hash)
1028 def check_remove(self):
1030 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1031 #print filename, len(share_hashes) + len(verified_hashes)
1032 if not share_hashes and not verified_hashes:
1033 to_remove.add(filename)
1034 for filename in to_remove:
1035 self.known.pop(filename)
1036 self.known_desired.pop(filename)
1038 print "REMOVED", filename