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