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