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