moved WeightsSkipList to p2pool.data
[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 small_block_header_type = pack.ComposedType([
37     ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
38     ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
39     ('timestamp', pack.IntType(32)),
40     ('bits', bitcoin_data.FloatingIntegerType()),
41     ('nonce', pack.IntType(32)),
42 ])
43
44 share_data_type = pack.ComposedType([
45     ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
46     ('coinbase', pack.VarStrType()),
47     ('nonce', pack.IntType(32)),
48     ('pubkey_hash', pack.IntType(160)),
49     ('subsidy', pack.IntType(64)),
50     ('donation', pack.IntType(16)),
51     ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
52 ])
53
54 share_info_type = pack.ComposedType([
55     ('share_data', share_data_type),
56     ('max_bits', bitcoin_data.FloatingIntegerType()),
57     ('bits', bitcoin_data.FloatingIntegerType()),
58     ('timestamp', pack.IntType(32)),
59 ])
60
61 share1a_type = pack.ComposedType([
62     ('min_header', small_block_header_type),
63     ('share_info', share_info_type),
64     ('hash_link', hash_link_type),
65     ('merkle_branch', bitcoin_data.merkle_branch_type),
66 ])
67
68 share1b_type = pack.ComposedType([
69     ('min_header', small_block_header_type),
70     ('share_info', share_info_type),
71     ('hash_link', hash_link_type),
72     ('other_txs', pack.ListType(bitcoin_data.tx_type)),
73 ])
74
75
76 # type:
77 # 2: share1a
78 # 3: share1b
79
80 share_type = pack.ComposedType([
81     ('type', pack.VarIntType()),
82     ('contents', pack.VarStrType()),
83 ])
84
85
86 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
87     assert dist >= 2
88     near = tracker.shares[previous_share_hash]
89     far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
90     attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash) if not min_work else tracker.get_delta(near.hash).min_work - tracker.get_delta(far.hash).min_work
91     time = near.timestamp - far.timestamp
92     if time <= 0:
93         time = 1
94     if integer:
95         return attempts//time
96     return attempts/time
97
98 def get_average_stale_prop(tracker, share_hash, lookbehind):
99     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] in [253, 254])
100     return stales/(lookbehind + stales)
101
102 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
103
104 ref_type = pack.ComposedType([
105     ('identifier', pack.FixedStrType(64//8)),
106     ('share_info', share_info_type),
107 ])
108
109 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
110
111 def generate_transaction(tracker, share_data, block_target, desired_timestamp, desired_target, net):
112     previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
113     
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
118     else:
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, (0, 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)))
125     
126     weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
127         min(height, net.REAL_CHAIN_LENGTH),
128         65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
129     )
130     assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
131     
132     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
133     this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
134     amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
135     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
136     
137     if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
138         raise ValueError()
139     
140     dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
141     
142     share_info = dict(
143         share_data=share_data,
144         max_bits=max_bits,
145         bits=bits,
146         timestamp=math.clip(desired_timestamp, (
147             (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
148             (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
149         )) if previous_share is not None else desired_timestamp,
150     )
151     
152     return share_info, dict(
153         version=1,
154         tx_ins=[dict(
155             previous_output=None,
156             sequence=None,
157             script=share_data['coinbase'].ljust(2, '\x00'),
158         )],
159         tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]] + [dict(
160             value=0,
161             script='\x20' + pack.IntType(256).pack(bitcoin_data.hash256(ref_type.pack(dict(
162                 identifier=net.IDENTIFIER,
163                 share_info=share_info,
164             )))),
165         )],
166         lock_time=0,
167     )
168
169 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
170     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))
171     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
172     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
173     return res
174
175 class Share(object):
176     __slots__ = 'net min_header share_info hash_link merkle_branch other_txs hash share_data max_target target timestamp previous_hash new_script gentx_hash header pow_hash header_hash time_seen peer'.split(' ')
177     
178     @classmethod
179     def from_share(cls, share, net, peer):
180         if share['type'] in [0, 1]:
181             from p2pool import p2p
182             raise p2p.PeerMisbehavingError('sent an obsolete share')
183         elif share['type'] == 2:
184             return cls(net, peer, other_txs=None, **share1a_type.unpack(share['contents']))
185         elif share['type'] == 3:
186             share1b = share1b_type.unpack(share['contents'])
187             return cls(net, peer, merkle_branch=bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
188         else:
189             raise ValueError('unknown share type: %r' % (share['type'],))
190     
191     def __init__(self, net, peer, min_header, share_info, hash_link, merkle_branch, other_txs):
192         if len(share_info['share_data']['coinbase']) > 100:
193             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
194         
195         if len(merkle_branch) > 16:
196             raise ValueError('merkle_branch too long!')
197         
198         if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_branch:
199             raise ValueError('merkle_branch and other_txs do not match')
200         
201         assert not hash_link['extra_data'], repr(hash_link['extra_data'])
202         
203         self.net = net
204         self.peer = peer
205         self.min_header = min_header
206         self.share_info = share_info
207         self.hash_link = hash_link
208         self.merkle_branch = merkle_branch
209         self.other_txs = other_txs
210         
211         self.share_data = self.share_info['share_data']
212         self.max_target = self.share_info['max_bits'].target
213         self.target = self.share_info['bits'].target
214         self.timestamp = self.share_info['timestamp']
215         self.previous_hash = self.share_data['previous_share_hash']
216         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
217         
218         self.gentx_hash = check_hash_link(
219             hash_link,
220             pack.IntType(256).pack(bitcoin_data.hash256(ref_type.pack(dict(
221                 identifier=net.IDENTIFIER,
222                 share_info=share_info,
223             )))) + pack.IntType(32).pack(0),
224             gentx_before_refhash,
225         )
226         merkle_root = bitcoin_data.check_merkle_branch(self.gentx_hash, 0, merkle_branch)
227         self.header = dict(min_header, merkle_root=merkle_root)
228         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
229         self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
230         
231         if self.pow_hash > self.target:
232             print 'hash %x' % self.pow_hash
233             print 'targ %x' % self.target
234             raise ValueError('not enough work!')
235         
236         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
237             raise ValueError('other_txs provided when not a block solution')
238         if other_txs is None and self.pow_hash <= self.header['bits'].target:
239             raise ValueError('other_txs not provided when a block solution')
240         
241         self.hash = bitcoin_data.hash256(share_type.pack(self.as_share()))
242         
243         # XXX eww
244         self.time_seen = time.time()
245     
246     def __repr__(self):
247         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
248     
249     def check(self, tracker):
250         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
251         if share_info != self.share_info:
252             raise ValueError('share difficulty invalid')
253         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
254             raise ValueError('''gentx doesn't match hash_link''')
255     
256     def as_share(self):
257         if not self.pow_hash <= self.header['bits'].target: # share1a
258             return dict(type=2, contents=share1a_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, merkle_branch=self.merkle_branch)))
259         else: # share1b
260             return dict(type=3, contents=share1b_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, other_txs=self.other_txs)))
261     
262     def as_block(self, tracker):
263         if self.other_txs is None:
264             raise ValueError('share does not contain all txs')
265         
266         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
267         assert share_info == self.share_info
268         
269         return dict(header=self.header, txs=[gentx] + self.other_txs)
270
271 class WeightsSkipList(forest.TrackerSkipList):
272     # share_count, weights, total_weight
273     
274     def get_delta(self, element):
275         from p2pool.bitcoin import data as bitcoin_data
276         share = self.tracker.shares[element]
277         att = bitcoin_data.target_to_average_attempts(share.target)
278         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
279     
280     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
281         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
282     
283     def initial_solution(self, start, (max_shares, desired_weight)):
284         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
285         return 0, None, 0, 0
286     
287     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)):
288         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
289             assert (desired_weight - total_weight1) % 65535 == 0
290             script, = weights2.iterkeys()
291             new_weights = dict(script=(desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535))
292             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)
293         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
294     
295     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
296         if share_count > max_shares or total_weight > desired_weight:
297             return 1
298         elif share_count == max_shares or total_weight == desired_weight:
299             return 0
300         else:
301             return -1
302     
303     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
304         assert share_count <= max_shares and total_weight <= desired_weight
305         assert share_count == max_shares or total_weight == desired_weight
306         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
307
308 class OkayTracker(forest.Tracker):
309     def __init__(self, net, my_share_hashes, my_doa_share_hashes):
310         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
311             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
312             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
313         )))
314         self.net = net
315         self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
316             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
317             my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
318             my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
319             my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 253 else 0,
320             my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 254 else 0,
321         )))
322         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
323         
324         self.get_cumulative_weights = WeightsSkipList(self)
325     
326     def attempt_verify(self, share):
327         if share.hash in self.verified.shares:
328             return True
329         height, last = self.get_height_and_last(share.hash)
330         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
331             raise AssertionError()
332         try:
333             share.check(self)
334         except:
335             log.err(None, 'Share check failed:')
336             return False
337         else:
338             self.verified.add(share)
339             return True
340     
341     def think(self, block_rel_height_func, previous_block, bits):
342         desired = set()
343         
344         # O(len(self.heads))
345         #   make 'unverified heads' set?
346         # for each overall head, attempt verification
347         # if it fails, attempt on parent, and repeat
348         # if no successful verification because of lack of parents, request parent
349         bads = set()
350         for head in set(self.heads) - set(self.verified.heads):
351             head_height, last = self.get_height_and_last(head)
352             
353             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
354                 if self.attempt_verify(share):
355                     break
356                 if share.hash in self.heads:
357                     bads.add(share.hash)
358             else:
359                 if last is not None:
360                     desired.add((
361                         self.shares[random.choice(list(self.reverse_shares[last]))].peer,
362                         last,
363                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
364                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
365                     ))
366         for bad in bads:
367             assert bad not in self.verified.shares
368             assert bad in self.heads
369             if p2pool.DEBUG:
370                 print "BAD", bad
371             self.remove(bad)
372         
373         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
374         for head in list(self.verified.heads):
375             head_height, last_hash = self.verified.get_height_and_last(head)
376             last_height, last_last_hash = self.get_height_and_last(last_hash)
377             # XXX review boundary conditions
378             want = max(self.net.CHAIN_LENGTH - head_height, 0)
379             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
380             get = min(want, can)
381             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
382             for share in self.get_chain(last_hash, get):
383                 if not self.attempt_verify(share):
384                     break
385             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
386                 desired.add((
387                     self.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
388                     last_last_hash,
389                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
390                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
391                 ))
392         
393         # decide best tree
394         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)
395         if p2pool.DEBUG:
396             print len(decorated_tails), 'tails:'
397             for score, tail_hash in decorated_tails:
398                 print format_hash(tail_hash), score
399         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
400         
401         # decide best verified head
402         decorated_heads = sorted(((
403             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
404             #self.shares[h].peer is None,
405             self.shares[h].pow_hash <= self.shares[h].header['bits'].target, # is block solution
406             (self.shares[h].header['previous_block'], self.shares[h].header['bits']) == (previous_block, bits) or self.shares[h].peer is None,
407             -self.shares[h].time_seen,
408         ), h) for h in self.verified.tails.get(best_tail, []))
409         if p2pool.DEBUG:
410             print len(decorated_heads), 'heads. Top 10:'
411             for score, head_hash in decorated_heads[-10:]:
412                 print '   ', format_hash(head_hash), format_hash(self.shares[head_hash].previous_hash), score
413         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
414         
415         # eat away at heads
416         if decorated_heads:
417             for i in xrange(1000):
418                 to_remove = set()
419                 for share_hash, tail in self.heads.iteritems():
420                     if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
421                         #print 1
422                         continue
423                     if self.shares[share_hash].time_seen > time.time() - 300:
424                         #print 2
425                         continue
426                     if share_hash not in self.verified.shares and max(self.shares[after_tail_hash].time_seen for after_tail_hash in self.reverse_shares.get(tail)) > time.time() - 120: # XXX stupid
427                         #print 3
428                         continue
429                     to_remove.add(share_hash)
430                 if not to_remove:
431                     break
432                 for share_hash in to_remove:
433                     self.remove(share_hash)
434                     if share_hash in self.verified.shares:
435                         self.verified.remove(share_hash)
436                 #print "_________", to_remove
437         
438         # drop tails
439         for i in xrange(1000):
440             to_remove = set()
441             for tail, heads in self.tails.iteritems():
442                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
443                     continue
444                 for aftertail in self.reverse_shares.get(tail, set()):
445                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
446                         print "raw"
447                         continue
448                     to_remove.add(aftertail)
449             if not to_remove:
450                 break
451             # if removed from this, it must be removed from verified
452             #start = time.time()
453             for aftertail in to_remove:
454                 if self.shares[aftertail].previous_hash not in self.tails:
455                     print "erk", aftertail, self.shares[aftertail].previous_hash
456                     continue
457                 self.remove(aftertail)
458                 if aftertail in self.verified.shares:
459                     self.verified.remove(aftertail)
460             #end = time.time()
461             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
462         
463         if best is not None:
464             best_share = self.shares[best]
465             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:
466                 if p2pool.DEBUG:
467                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
468                 best = best_share.previous_hash
469             
470             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
471             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
472         else:
473             timestamp_cutoff = int(time.time()) - 24*60*60
474             target_cutoff = 2**256-1
475         
476         if p2pool.DEBUG:
477             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))
478             for peer, hash, ts, targ in desired:
479                 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
480         
481         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
482     
483     def score(self, share_hash, block_rel_height_func):
484         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
485         
486         head_height = self.verified.get_height(share_hash)
487         if head_height < self.net.CHAIN_LENGTH:
488             return head_height, None
489         
490         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
491         
492         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
493             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
494         
495         return self.net.CHAIN_LENGTH, (self.verified.get_work(share_hash) - self.verified.get_work(end_point))//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
496
497 def format_hash(x):
498     if x is None:
499         return 'xxxxxxxx'
500     return '%08x' % (x % 2**32)
501
502 class ShareStore(object):
503     def __init__(self, prefix, net):
504         self.filename = prefix
505         self.dirname = os.path.dirname(os.path.abspath(prefix))
506         self.filename = os.path.basename(os.path.abspath(prefix))
507         self.net = net
508         self.known = None # will be filename -> set of share hashes, set of verified hashes
509         self.known_desired = None
510     
511     def get_shares(self):
512         if self.known is not None:
513             raise AssertionError()
514         known = {}
515         filenames, next = self.get_filenames_and_next()
516         for filename in filenames:
517             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
518             with open(filename, 'rb') as f:
519                 for line in f:
520                     try:
521                         type_id_str, data_hex = line.strip().split(' ')
522                         type_id = int(type_id_str)
523                         if type_id == 0:
524                             pass
525                         elif type_id == 1:
526                             pass
527                         elif type_id == 2:
528                             verified_hash = int(data_hex, 16)
529                             yield 'verified_hash', verified_hash
530                             verified_hashes.add(verified_hash)
531                         elif type_id == 5:
532                             raw_share = share_type.unpack(data_hex.decode('hex'))
533                             if raw_share['type'] in [0, 1]:
534                                 continue
535                             share = Share.from_share(raw_share, self.net, None)
536                             yield 'share', share
537                             share_hashes.add(share.hash)
538                         else:
539                             raise NotImplementedError("share type %i" % (type_id,))
540                     except Exception:
541                         log.err(None, "Error while reading saved shares, continuing where left off:")
542         self.known = known
543         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
544     
545     def _add_line(self, line):
546         filenames, next = self.get_filenames_and_next()
547         if filenames and os.path.getsize(filenames[-1]) < 10e6:
548             filename = filenames[-1]
549         else:
550             filename = next
551         
552         with open(filename, 'ab') as f:
553             f.write(line + '\n')
554         
555         return filename
556     
557     def add_share(self, share):
558         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
559             if share.hash in share_hashes:
560                 break
561         else:
562             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
563             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
564             share_hashes.add(share.hash)
565         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
566         share_hashes.add(share.hash)
567     
568     def add_verified_hash(self, share_hash):
569         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
570             if share_hash in verified_hashes:
571                 break
572         else:
573             filename = self._add_line("%i %x" % (2, share_hash))
574             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
575             verified_hashes.add(share_hash)
576         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
577         verified_hashes.add(share_hash)
578     
579     def get_filenames_and_next(self):
580         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())
581         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)))
582     
583     def forget_share(self, share_hash):
584         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
585             if share_hash in share_hashes:
586                 share_hashes.remove(share_hash)
587         self.check_remove()
588     
589     def forget_verified_share(self, share_hash):
590         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
591             if share_hash in verified_hashes:
592                 verified_hashes.remove(share_hash)
593         self.check_remove()
594     
595     def check_remove(self):
596         to_remove = set()
597         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
598             #print filename, len(share_hashes) + len(verified_hashes)
599             if not share_hashes and not verified_hashes:
600                 to_remove.add(filename)
601         for filename in to_remove:
602             self.known.pop(filename)
603             self.known_desired.pop(filename)
604             os.remove(filename)
605             print "REMOVED", filename