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