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