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