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