885b40697807d1f7a5c0def62ec31962e64d0a58
[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             raise p2p.PeerMisbehavingError('share PoW invalid')
233         
234         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
235             raise ValueError('other_txs provided when not a block solution')
236         if other_txs is None and self.pow_hash <= self.header['bits'].target:
237             raise ValueError('other_txs not provided when a block solution')
238         
239         self.hash = bitcoin_data.hash256(share_type.pack(self.as_share()))
240         
241         # XXX eww
242         self.time_seen = time.time()
243     
244     def __repr__(self):
245         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
246     
247     def check(self, tracker):
248         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)
249         if share_info != self.share_info:
250             raise ValueError('share difficulty invalid')
251         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
252             raise ValueError('''gentx doesn't match hash_link''')
253     
254     def as_share(self):
255         if not self.pow_hash <= self.header['bits'].target: # share1a
256             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)))
257         else: # share1b
258             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)))
259     
260     def as_block(self, tracker):
261         if self.other_txs is None:
262             raise ValueError('share does not contain all txs')
263         
264         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)
265         assert share_info == self.share_info
266         
267         return dict(header=self.header, txs=[gentx] + self.other_txs)
268
269 class WeightsSkipList(forest.TrackerSkipList):
270     # share_count, weights, total_weight
271     
272     def get_delta(self, element):
273         from p2pool.bitcoin import data as bitcoin_data
274         share = self.tracker.shares[element]
275         att = bitcoin_data.target_to_average_attempts(share.target)
276         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
277     
278     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
279         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
280     
281     def initial_solution(self, start, (max_shares, desired_weight)):
282         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
283         return 0, None, 0, 0
284     
285     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)):
286         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
287             assert (desired_weight - total_weight1) % 65535 == 0
288             script, = weights2.iterkeys()
289             new_weights = dict(script=(desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535))
290             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)
291         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
292     
293     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
294         if share_count > max_shares or total_weight > desired_weight:
295             return 1
296         elif share_count == max_shares or total_weight == desired_weight:
297             return 0
298         else:
299             return -1
300     
301     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
302         assert share_count <= max_shares and total_weight <= desired_weight
303         assert share_count == max_shares or total_weight == desired_weight
304         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
305
306 class OkayTracker(forest.Tracker):
307     def __init__(self, net, my_share_hashes, my_doa_share_hashes):
308         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
309             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
310             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
311         )))
312         self.net = net
313         self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
314             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
315             my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
316             my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
317             my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 253 else 0,
318             my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 254 else 0,
319         )))
320         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
321         
322         self.get_cumulative_weights = WeightsSkipList(self)
323     
324     def attempt_verify(self, share):
325         if share.hash in self.verified.shares:
326             return True
327         height, last = self.get_height_and_last(share.hash)
328         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
329             raise AssertionError()
330         try:
331             share.check(self)
332         except:
333             log.err(None, 'Share check failed:')
334             return False
335         else:
336             self.verified.add(share)
337             return True
338     
339     def think(self, block_rel_height_func, previous_block, bits):
340         desired = set()
341         
342         # O(len(self.heads))
343         #   make 'unverified heads' set?
344         # for each overall head, attempt verification
345         # if it fails, attempt on parent, and repeat
346         # if no successful verification because of lack of parents, request parent
347         bads = set()
348         for head in set(self.heads) - set(self.verified.heads):
349             head_height, last = self.get_height_and_last(head)
350             
351             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
352                 if self.attempt_verify(share):
353                     break
354                 if share.hash in self.heads:
355                     bads.add(share.hash)
356             else:
357                 if last is not None:
358                     desired.add((
359                         self.shares[random.choice(list(self.reverse_shares[last]))].peer,
360                         last,
361                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
362                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
363                     ))
364         for bad in bads:
365             assert bad not in self.verified.shares
366             assert bad in self.heads
367             if p2pool.DEBUG:
368                 print "BAD", bad
369             self.remove(bad)
370         
371         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
372         for head in list(self.verified.heads):
373             head_height, last_hash = self.verified.get_height_and_last(head)
374             last_height, last_last_hash = self.get_height_and_last(last_hash)
375             # XXX review boundary conditions
376             want = max(self.net.CHAIN_LENGTH - head_height, 0)
377             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
378             get = min(want, can)
379             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
380             for share in self.get_chain(last_hash, get):
381                 if not self.attempt_verify(share):
382                     break
383             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
384                 desired.add((
385                     self.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
386                     last_last_hash,
387                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
388                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
389                 ))
390         
391         # decide best tree
392         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)
393         if p2pool.DEBUG:
394             print len(decorated_tails), 'tails:'
395             for score, tail_hash in decorated_tails:
396                 print format_hash(tail_hash), score
397         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
398         
399         # decide best verified head
400         decorated_heads = sorted(((
401             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
402             #self.shares[h].peer is None,
403             self.shares[h].pow_hash <= self.shares[h].header['bits'].target, # is block solution
404             (self.shares[h].header['previous_block'], self.shares[h].header['bits']) == (previous_block, bits) or self.shares[h].peer is None,
405             -self.shares[h].time_seen,
406         ), h) for h in self.verified.tails.get(best_tail, []))
407         if p2pool.DEBUG:
408             print len(decorated_heads), 'heads. Top 10:'
409             for score, head_hash in decorated_heads[-10:]:
410                 print '   ', format_hash(head_hash), format_hash(self.shares[head_hash].previous_hash), score
411         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
412         
413         # eat away at heads
414         if decorated_heads:
415             for i in xrange(1000):
416                 to_remove = set()
417                 for share_hash, tail in self.heads.iteritems():
418                     if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
419                         #print 1
420                         continue
421                     if self.shares[share_hash].time_seen > time.time() - 300:
422                         #print 2
423                         continue
424                     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
425                         #print 3
426                         continue
427                     to_remove.add(share_hash)
428                 if not to_remove:
429                     break
430                 for share_hash in to_remove:
431                     self.remove(share_hash)
432                     if share_hash in self.verified.shares:
433                         self.verified.remove(share_hash)
434                 #print "_________", to_remove
435         
436         # drop tails
437         for i in xrange(1000):
438             to_remove = set()
439             for tail, heads in self.tails.iteritems():
440                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
441                     continue
442                 for aftertail in self.reverse_shares.get(tail, set()):
443                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
444                         print "raw"
445                         continue
446                     to_remove.add(aftertail)
447             if not to_remove:
448                 break
449             # if removed from this, it must be removed from verified
450             #start = time.time()
451             for aftertail in to_remove:
452                 if self.shares[aftertail].previous_hash not in self.tails:
453                     print "erk", aftertail, self.shares[aftertail].previous_hash
454                     continue
455                 self.remove(aftertail)
456                 if aftertail in self.verified.shares:
457                     self.verified.remove(aftertail)
458             #end = time.time()
459             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
460         
461         if best is not None:
462             best_share = self.shares[best]
463             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:
464                 if p2pool.DEBUG:
465                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
466                 best = best_share.previous_hash
467             
468             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
469             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
470         else:
471             timestamp_cutoff = int(time.time()) - 24*60*60
472             target_cutoff = 2**256-1
473         
474         if p2pool.DEBUG:
475             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))
476             for peer, hash, ts, targ in desired:
477                 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
478         
479         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
480     
481     def score(self, share_hash, block_rel_height_func):
482         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
483         
484         head_height = self.verified.get_height(share_hash)
485         if head_height < self.net.CHAIN_LENGTH:
486             return head_height, None
487         
488         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
489         
490         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
491             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
492         
493         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)
494
495 def format_hash(x):
496     if x is None:
497         return 'xxxxxxxx'
498     return '%08x' % (x % 2**32)
499
500 class ShareStore(object):
501     def __init__(self, prefix, net):
502         self.filename = prefix
503         self.dirname = os.path.dirname(os.path.abspath(prefix))
504         self.filename = os.path.basename(os.path.abspath(prefix))
505         self.net = net
506         self.known = None # will be filename -> set of share hashes, set of verified hashes
507         self.known_desired = None
508     
509     def get_shares(self):
510         if self.known is not None:
511             raise AssertionError()
512         known = {}
513         filenames, next = self.get_filenames_and_next()
514         for filename in filenames:
515             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
516             with open(filename, 'rb') as f:
517                 for line in f:
518                     try:
519                         type_id_str, data_hex = line.strip().split(' ')
520                         type_id = int(type_id_str)
521                         if type_id == 0:
522                             pass
523                         elif type_id == 1:
524                             pass
525                         elif type_id == 2:
526                             verified_hash = int(data_hex, 16)
527                             yield 'verified_hash', verified_hash
528                             verified_hashes.add(verified_hash)
529                         elif type_id == 5:
530                             raw_share = share_type.unpack(data_hex.decode('hex'))
531                             if raw_share['type'] in [0, 1]:
532                                 continue
533                             share = Share.from_share(raw_share, self.net, None)
534                             yield 'share', share
535                             share_hashes.add(share.hash)
536                         else:
537                             raise NotImplementedError("share type %i" % (type_id,))
538                     except Exception:
539                         log.err(None, "Error while reading saved shares, continuing where left off:")
540         self.known = known
541         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
542     
543     def _add_line(self, line):
544         filenames, next = self.get_filenames_and_next()
545         if filenames and os.path.getsize(filenames[-1]) < 10e6:
546             filename = filenames[-1]
547         else:
548             filename = next
549         
550         with open(filename, 'ab') as f:
551             f.write(line + '\n')
552         
553         return filename
554     
555     def add_share(self, share):
556         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
557             if share.hash in share_hashes:
558                 break
559         else:
560             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
561             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
562             share_hashes.add(share.hash)
563         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
564         share_hashes.add(share.hash)
565     
566     def add_verified_hash(self, share_hash):
567         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
568             if share_hash in verified_hashes:
569                 break
570         else:
571             filename = self._add_line("%i %x" % (2, share_hash))
572             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
573             verified_hashes.add(share_hash)
574         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
575         verified_hashes.add(share_hash)
576     
577     def get_filenames_and_next(self):
578         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())
579         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)))
580     
581     def forget_share(self, share_hash):
582         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
583             if share_hash in share_hashes:
584                 share_hashes.remove(share_hash)
585         self.check_remove()
586     
587     def forget_verified_share(self, share_hash):
588         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
589             if share_hash in verified_hashes:
590                 verified_hashes.remove(share_hash)
591         self.check_remove()
592     
593     def check_remove(self):
594         to_remove = set()
595         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
596             #print filename, len(share_hashes) + len(verified_hashes)
597             if not share_hashes and not verified_hashes:
598                 to_remove.add(filename)
599         for filename in to_remove:
600             self.known.pop(filename)
601             self.known_desired.pop(filename)
602             os.remove(filename)
603             print "REMOVED", filename