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