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