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