store total share count and work within shares
[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'] < Share.VERSION:
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     elif share['type'] == NewShare.VERSION:
50         return NewShare(net, peer_addr, NewShare.share_type.unpack(share['contents']))
51     else:
52         raise ValueError('unknown share type: %r' % (share['type'],))
53
54 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
55
56 class NewShare(object):
57     VERSION = 13
58     VOTING_VERSION = 13
59     SUCCESSOR = 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         ('absheight', pack.IntType(32)),
87         ('abswork', pack.IntType(128)),
88     ])
89     
90     share_type = pack.ComposedType([
91         ('min_header', small_block_header_type),
92         ('share_info', share_info_type),
93         ('ref_merkle_link', pack.ComposedType([
94             ('branch', pack.ListType(pack.IntType(256))),
95             ('index', pack.IntType(0)),
96         ])),
97         ('last_txout_nonce', pack.IntType(64)),
98         ('hash_link', hash_link_type),
99         ('merkle_link', pack.ComposedType([
100             ('branch', pack.ListType(pack.IntType(256))),
101             ('index', pack.IntType(0)), # it will always be 0
102         ])),
103     ])
104     
105     ref_type = pack.ComposedType([
106         ('identifier', pack.FixedStrType(64//8)),
107         ('share_info', share_info_type),
108     ])
109     
110     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x6a\x28' + pack.IntType(256).pack(0) + pack.IntType(64).pack(0))[:3]
111     
112     @classmethod
113     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):
114         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
115         
116         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
117         assert height >= net.REAL_CHAIN_LENGTH or last is None
118         if height < net.TARGET_LOOKBEHIND:
119             pre_target3 = net.MAX_TARGET
120         else:
121             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
122             pre_target = 2**256//(net.NEW_SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
123             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
124             pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
125         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
126         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
127         
128         new_transaction_hashes = []
129         new_transaction_size = 0
130         transaction_hash_refs = []
131         other_transaction_hashes = []
132         
133         past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100)))
134         tx_hash_to_this = {}
135         for i, share in enumerate(past_shares):
136             for j, tx_hash in enumerate(share.new_transaction_hashes):
137                 if tx_hash not in tx_hash_to_this:
138                     tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count
139         for tx_hash, fee in desired_other_transaction_hashes_and_fees:
140             if tx_hash in tx_hash_to_this:
141                 this = tx_hash_to_this[tx_hash]
142             else:
143                 if known_txs is not None:
144                     this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
145                     if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
146                         break
147                     new_transaction_size += this_size
148                 new_transaction_hashes.append(tx_hash)
149                 this = [0, len(new_transaction_hashes)-1]
150             transaction_hash_refs.extend(this)
151             other_transaction_hashes.append(tx_hash)
152         
153         included_transactions = set(other_transaction_hashes)
154         removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions]
155         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)
156         if None not in removed_fees:
157             share_data = dict(share_data, subsidy=share_data['subsidy'] - sum(removed_fees))
158         else:
159             assert base_subsidy is not None
160             share_data = dict(share_data, subsidy=base_subsidy + definite_fees)
161         
162         weights, total_weight, donation_weight = tracker.get_cumulative_weights(previous_share.share_data['previous_share_hash'] if previous_share is not None else None,
163             min(height, net.REAL_CHAIN_LENGTH-1),
164             65535*net.NEW_SPREAD*bitcoin_data.target_to_average_attempts(block_target),
165         )
166         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
167         
168         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
169         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
170         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
171         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
172         
173         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
174             raise ValueError()
175         
176         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
177         
178         share_info = dict(
179             share_data=share_data,
180             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
181             max_bits=max_bits,
182             bits=bits,
183             timestamp=math.clip(desired_timestamp, (
184                 (previous_share.timestamp + net.NEW_SHARE_PERIOD) - (net.NEW_SHARE_PERIOD - 1), # = previous_share.timestamp + 1
185                 (previous_share.timestamp + net.NEW_SHARE_PERIOD) + (net.NEW_SHARE_PERIOD - 1),
186             )) if previous_share is not None else desired_timestamp,
187             new_transaction_hashes=new_transaction_hashes,
188             transaction_hash_refs=transaction_hash_refs,
189             absheight=((previous_share.absheight if previous_share is not None else 0) + 1) % 2**32,
190             abswork=((previous_share.abswork if previous_share is not None else 0) + bitcoin_data.target_to_average_attempts(bits.target)) % 2**128,
191         )
192         
193         gentx = dict(
194             version=1,
195             tx_ins=[dict(
196                 previous_output=None,
197                 sequence=None,
198                 script=share_data['coinbase'],
199             )],
200             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
201                 value=0,
202                 script='\x6a\x28' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(64).pack(last_txout_nonce),
203             )],
204             lock_time=0,
205         )
206         
207         def get_share(header, last_txout_nonce=last_txout_nonce):
208             min_header = dict(header); del min_header['merkle_root']
209             share = cls(net, None, dict(
210                 min_header=min_header,
211                 share_info=share_info,
212                 ref_merkle_link=dict(branch=[], index=0),
213                 last_txout_nonce=last_txout_nonce*2**32,
214                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-8-4], cls.gentx_before_refhash),
215                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
216             ))
217             assert share.header == header # checks merkle_root
218             return share
219         
220         return share_info, gentx, other_transaction_hashes, get_share
221     
222     @classmethod
223     def get_ref_hash(cls, net, share_info, ref_merkle_link):
224         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
225             identifier=net.IDENTIFIER,
226             share_info=share_info,
227         ))), ref_merkle_link))
228     
229     __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 absheight abswork'.split(' ')
230     
231     def __init__(self, net, peer_addr, contents):
232         self.net = net
233         self.peer_addr = peer_addr
234         self.contents = contents
235         
236         self.min_header = contents['min_header']
237         self.share_info = contents['share_info']
238         self.hash_link = contents['hash_link']
239         self.merkle_link = contents['merkle_link']
240         
241         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
242             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
243         
244         if len(self.merkle_link['branch']) > 16:
245             raise ValueError('merkle branch too long!')
246         
247         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
248         
249         self.share_data = self.share_info['share_data']
250         self.max_target = self.share_info['max_bits'].target
251         self.target = self.share_info['bits'].target
252         self.timestamp = self.share_info['timestamp']
253         self.previous_hash = self.share_data['previous_share_hash']
254         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
255         self.desired_version = self.share_data['desired_version']
256         self.absheight = self.share_info['absheight']
257         self.abswork = self.share_info['abswork']
258         
259         n = set()
260         for share_count, tx_count in self.iter_transaction_hash_refs():
261             assert share_count < 110
262             if share_count == 0:
263                 n.add(tx_count)
264         assert n == set(range(len(self.share_info['new_transaction_hashes'])))
265         
266         self.gentx_hash = check_hash_link(
267             self.hash_link,
268             self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(64).pack(self.contents['last_txout_nonce']) + pack.IntType(32).pack(0),
269             self.gentx_before_refhash,
270         )
271         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
272         self.header = dict(self.min_header, merkle_root=merkle_root)
273         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
274         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
275         
276         if self.target > net.MAX_TARGET:
277             from p2pool import p2p
278             raise p2p.PeerMisbehavingError('share target invalid')
279         
280         if self.pow_hash > self.target:
281             from p2pool import p2p
282             raise p2p.PeerMisbehavingError('share PoW invalid')
283         
284         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
285         
286         # XXX eww
287         self.time_seen = time.time()
288     
289     def __repr__(self):
290         return 'Share' + repr((self.net, self.peer_addr, self.contents))
291     
292     def as_share(self):
293         return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
294     
295     def iter_transaction_hash_refs(self):
296         return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2])
297     
298     def check(self, tracker):
299         from p2pool import p2p
300         if self.share_data['previous_share_hash'] is not None:
301             previous_share = tracker.items[self.share_data['previous_share_hash']]
302             if type(self) is type(previous_share):
303                 pass
304             elif type(self) is type(previous_share).SUCCESSOR:
305                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
306                     from p2pool import p2p
307                     raise p2p.PeerMisbehavingError('switch without enough history')
308                 
309                 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
310                 counts = get_desired_version_counts(tracker,
311                     tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
312                 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
313                     raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
314             else:
315                 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
316         
317         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()]
318         
319         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'])
320         assert other_tx_hashes2 == other_tx_hashes
321         if share_info != self.share_info:
322             raise ValueError('share_info invalid')
323         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
324             raise ValueError('''gentx doesn't match hash_link''')
325         
326         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
327             raise ValueError('merkle_link and other_tx_hashes do not match')
328         
329         return gentx # only used by as_block
330     
331     def get_other_tx_hashes(self, tracker):
332         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
333         parents = tracker.get_height(self.hash) - 1
334         if parents < parents_needed:
335             return None
336         last_shares = list(tracker.get_chain(self.hash, parents_needed + 1))
337         return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
338     
339     def _get_other_txs(self, tracker, known_txs):
340         other_tx_hashes = self.get_other_tx_hashes(tracker)
341         if other_tx_hashes is None:
342             return None # not all parents present
343         
344         if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
345             return None # not all txs present
346         
347         return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
348     
349     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
350         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None:
351             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
352         
353         if self.pow_hash <= self.header['bits'].target:
354             return -1, 'block solution'
355         
356         other_txs = self._get_other_txs(tracker, known_txs)
357         if other_txs is None:
358             if self.time_seen != 0: # ignore if loaded from ShareStore
359                 return True, 'not all txs present'
360         else:
361             all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
362             if all_txs_size > 1000000:
363                 return True, 'txs over block size limit'
364             
365             new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
366             if new_txs_size > 50000:
367                 return True, 'new txs over limit'
368         
369         return False, None
370     
371     def as_block(self, tracker, known_txs):
372         other_txs = self._get_other_txs(tracker, known_txs)
373         if other_txs is None:
374             return None # not all txs present
375         return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
376
377 class Share(object):
378     VERSION = 9
379     VOTING_VERSION = 11
380     SUCCESSOR = NewShare
381     
382     absheight = abswork = 0
383     
384     small_block_header_type = pack.ComposedType([
385         ('version', pack.VarIntType()),
386         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
387         ('timestamp', pack.IntType(32)),
388         ('bits', bitcoin_data.FloatingIntegerType()),
389         ('nonce', pack.IntType(32)),
390     ])
391     
392     share_info_type = pack.ComposedType([
393         ('share_data', pack.ComposedType([
394             ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
395             ('coinbase', pack.VarStrType()),
396             ('nonce', pack.IntType(32)),
397             ('pubkey_hash', pack.IntType(160)),
398             ('subsidy', pack.IntType(64)),
399             ('donation', pack.IntType(16)),
400             ('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)))),
401             ('desired_version', pack.VarIntType()),
402         ])),
403         ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
404         ('transaction_hash_refs', pack.ListType(pack.VarIntType(), 2)), # pairs of share_count, tx_count
405         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
406         ('max_bits', bitcoin_data.FloatingIntegerType()),
407         ('bits', bitcoin_data.FloatingIntegerType()),
408         ('timestamp', pack.IntType(32)),
409     ])
410     
411     share_type = pack.ComposedType([
412         ('min_header', small_block_header_type),
413         ('share_info', share_info_type),
414         ('ref_merkle_link', pack.ComposedType([
415             ('branch', pack.ListType(pack.IntType(256))),
416             ('index', pack.IntType(0)),
417         ])),
418         ('last_txout_nonce', pack.IntType(32)),
419         ('hash_link', hash_link_type),
420         ('merkle_link', pack.ComposedType([
421             ('branch', pack.ListType(pack.IntType(256))),
422             ('index', pack.IntType(0)), # it will always be 0
423         ])),
424     ])
425     
426     ref_type = pack.ComposedType([
427         ('identifier', pack.FixedStrType(64//8)),
428         ('share_info', share_info_type),
429     ])
430     
431     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]
432     
433     @classmethod
434     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):
435         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
436         
437         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
438         assert height >= net.REAL_CHAIN_LENGTH or last is None
439         if height < net.TARGET_LOOKBEHIND:
440             pre_target3 = net.MAX_TARGET
441         else:
442             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
443             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
444             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
445             pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
446         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
447         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
448         
449         new_transaction_hashes = []
450         new_transaction_size = 0
451         transaction_hash_refs = []
452         other_transaction_hashes = []
453         
454         past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100)))
455         tx_hash_to_this = {}
456         for i, share in enumerate(past_shares):
457             for j, tx_hash in enumerate(share.new_transaction_hashes):
458                 if tx_hash not in tx_hash_to_this:
459                     tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count
460         for tx_hash, fee in desired_other_transaction_hashes_and_fees:
461             if tx_hash in tx_hash_to_this:
462                 this = tx_hash_to_this[tx_hash]
463             else:
464                 if known_txs is not None:
465                     this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
466                     if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
467                         break
468                     new_transaction_size += this_size
469                 new_transaction_hashes.append(tx_hash)
470                 this = [0, len(new_transaction_hashes)-1]
471             transaction_hash_refs.extend(this)
472             other_transaction_hashes.append(tx_hash)
473         
474         included_transactions = set(other_transaction_hashes)
475         removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions]
476         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)
477         if None not in removed_fees:
478             share_data = dict(share_data, subsidy=share_data['subsidy'] - sum(removed_fees))
479         else:
480             assert base_subsidy is not None
481             share_data = dict(share_data, subsidy=base_subsidy + definite_fees)
482         
483         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
484             min(height, net.REAL_CHAIN_LENGTH),
485             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
486         )
487         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
488         
489         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
490         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
491         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
492         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
493         
494         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
495             raise ValueError()
496         
497         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
498         
499         share_info = dict(
500             share_data=share_data,
501             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
502             max_bits=max_bits,
503             bits=bits,
504             timestamp=math.clip(desired_timestamp, (
505                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
506                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
507             )) if previous_share is not None else desired_timestamp,
508             new_transaction_hashes=new_transaction_hashes,
509             transaction_hash_refs=transaction_hash_refs,
510         )
511         
512         gentx = dict(
513             version=1,
514             tx_ins=[dict(
515                 previous_output=None,
516                 sequence=None,
517                 script=share_data['coinbase'],
518             )],
519             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
520                 value=0,
521                 script='\x24' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(32).pack(last_txout_nonce),
522             )],
523             lock_time=0,
524         )
525         
526         def get_share(header, last_txout_nonce=last_txout_nonce):
527             min_header = dict(header); del min_header['merkle_root']
528             share = cls(net, None, dict(
529                 min_header=min_header,
530                 share_info=share_info,
531                 ref_merkle_link=dict(branch=[], index=0),
532                 last_txout_nonce=last_txout_nonce,
533                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4-4], cls.gentx_before_refhash),
534                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
535             ))
536             assert share.header == header # checks merkle_root
537             return share
538         
539         return share_info, gentx, other_transaction_hashes, get_share
540     
541     @classmethod
542     def get_ref_hash(cls, net, share_info, ref_merkle_link):
543         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
544             identifier=net.IDENTIFIER,
545             share_info=share_info,
546         ))), ref_merkle_link))
547     
548     __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(' ')
549     
550     def __init__(self, net, peer_addr, contents):
551         self.net = net
552         self.peer_addr = peer_addr
553         self.contents = contents
554         
555         self.min_header = contents['min_header']
556         self.share_info = contents['share_info']
557         self.hash_link = contents['hash_link']
558         self.merkle_link = contents['merkle_link']
559         
560         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
561             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
562         
563         if len(self.merkle_link['branch']) > 16:
564             raise ValueError('merkle branch too long!')
565         
566         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
567         
568         self.share_data = self.share_info['share_data']
569         self.max_target = self.share_info['max_bits'].target
570         self.target = self.share_info['bits'].target
571         self.timestamp = self.share_info['timestamp']
572         self.previous_hash = self.share_data['previous_share_hash']
573         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
574         self.desired_version = self.share_data['desired_version']
575         
576         n = set()
577         for share_count, tx_count in self.iter_transaction_hash_refs():
578             assert share_count < 110
579             if share_count == 0:
580                 n.add(tx_count)
581         assert n == set(range(len(self.share_info['new_transaction_hashes'])))
582         
583         self.gentx_hash = check_hash_link(
584             self.hash_link,
585             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),
586             self.gentx_before_refhash,
587         )
588         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
589         self.header = dict(self.min_header, merkle_root=merkle_root)
590         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
591         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
592         
593         if self.target > net.MAX_TARGET:
594             from p2pool import p2p
595             raise p2p.PeerMisbehavingError('share target invalid')
596         
597         if self.pow_hash > self.target:
598             from p2pool import p2p
599             raise p2p.PeerMisbehavingError('share PoW invalid')
600         
601         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
602         
603         # XXX eww
604         self.time_seen = time.time()
605     
606     def __repr__(self):
607         return 'Share' + repr((self.net, self.peer_addr, self.contents))
608     
609     def as_share(self):
610         return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
611     
612     def iter_transaction_hash_refs(self):
613         return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2])
614     
615     def check(self, tracker):
616         from p2pool import p2p
617         if self.share_data['previous_share_hash'] is not None:
618             previous_share = tracker.items[self.share_data['previous_share_hash']]
619             if type(self) is type(previous_share):
620                 pass
621             elif type(self) is type(previous_share).SUCCESSOR:
622                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
623                     from p2pool import p2p
624                     raise p2p.PeerMisbehavingError('switch without enough history')
625                 
626                 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
627                 counts = get_desired_version_counts(tracker,
628                     tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
629                 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
630                     raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
631             else:
632                 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
633         
634         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()]
635         
636         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'])
637         assert other_tx_hashes2 == other_tx_hashes
638         if share_info != self.share_info:
639             raise ValueError('share_info invalid')
640         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
641             raise ValueError('''gentx doesn't match hash_link''')
642         
643         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
644             raise ValueError('merkle_link and other_tx_hashes do not match')
645         
646         return gentx # only used by as_block
647     
648     def get_other_tx_hashes(self, tracker):
649         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
650         parents = tracker.get_height(self.hash) - 1
651         if parents < parents_needed:
652             return None
653         last_shares = list(tracker.get_chain(self.hash, parents_needed + 1))
654         return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
655     
656     def _get_other_txs(self, tracker, known_txs):
657         other_tx_hashes = self.get_other_tx_hashes(tracker)
658         if other_tx_hashes is None:
659             return None # not all parents present
660         
661         if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
662             return None # not all txs present
663         
664         return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
665     
666     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
667         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None:
668             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
669         
670         if self.pow_hash <= self.header['bits'].target:
671             return -1, 'block solution'
672         
673         other_txs = self._get_other_txs(tracker, known_txs)
674         if other_txs is None:
675             if self.time_seen != 0: # ignore if loaded from ShareStore
676                 return True, 'not all txs present'
677         else:
678             all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
679             if all_txs_size > 1000000:
680                 return True, 'txs over block size limit'
681             
682             new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
683             if new_txs_size > 50000:
684                 return True, 'new txs over limit'
685         
686         return False, None
687     
688     def as_block(self, tracker, known_txs):
689         other_txs = self._get_other_txs(tracker, known_txs)
690         if other_txs is None:
691             return None # not all txs present
692         return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
693
694
695
696 class WeightsSkipList(forest.TrackerSkipList):
697     # share_count, weights, total_weight
698     
699     def get_delta(self, element):
700         from p2pool.bitcoin import data as bitcoin_data
701         share = self.tracker.items[element]
702         att = bitcoin_data.target_to_average_attempts(share.target)
703         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
704     
705     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
706         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
707     
708     def initial_solution(self, start, (max_shares, desired_weight)):
709         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
710         return 0, None, 0, 0
711     
712     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)):
713         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
714             assert (desired_weight - total_weight1) % 65535 == 0
715             script, = weights2.iterkeys()
716             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
717             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)
718         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
719     
720     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
721         if share_count > max_shares or total_weight > desired_weight:
722             return 1
723         elif share_count == max_shares or total_weight == desired_weight:
724             return 0
725         else:
726             return -1
727     
728     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
729         assert share_count <= max_shares and total_weight <= desired_weight
730         assert share_count == max_shares or total_weight == desired_weight
731         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
732
733 class OkayTracker(forest.Tracker):
734     def __init__(self, net):
735         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
736             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
737             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
738         )))
739         self.net = net
740         self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
741             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
742         )), subset_of=self)
743         self.get_cumulative_weights = WeightsSkipList(self)
744     
745     def attempt_verify(self, share):
746         if share.hash in self.verified.items:
747             return True
748         height, last = self.get_height_and_last(share.hash)
749         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
750             raise AssertionError()
751         try:
752             share.check(self)
753         except:
754             log.err(None, 'Share check failed:')
755             return False
756         else:
757             self.verified.add(share)
758             return True
759     
760     def think(self, block_rel_height_func, previous_block, bits, known_txs):
761         desired = set()
762         
763         # O(len(self.heads))
764         #   make 'unverified heads' set?
765         # for each overall head, attempt verification
766         # if it fails, attempt on parent, and repeat
767         # if no successful verification because of lack of parents, request parent
768         bads = set()
769         for head in set(self.heads) - set(self.verified.heads):
770             head_height, last = self.get_height_and_last(head)
771             
772             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
773                 if self.attempt_verify(share):
774                     break
775                 if share.hash in self.heads:
776                     bads.add(share.hash)
777             else:
778                 if last is not None:
779                     desired.add((
780                         self.items[random.choice(list(self.reverse[last]))].peer_addr,
781                         last,
782                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
783                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
784                     ))
785         for bad in bads:
786             assert bad not in self.verified.items
787             assert bad in self.heads
788             if p2pool.DEBUG:
789                 print "BAD", bad
790             self.remove(bad)
791         
792         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
793         for head in list(self.verified.heads):
794             head_height, last_hash = self.verified.get_height_and_last(head)
795             last_height, last_last_hash = self.get_height_and_last(last_hash)
796             # XXX review boundary conditions
797             want = max(self.net.CHAIN_LENGTH - head_height, 0)
798             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
799             get = min(want, can)
800             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
801             for share in self.get_chain(last_hash, get):
802                 if not self.attempt_verify(share):
803                     break
804             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
805                 desired.add((
806                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer_addr,
807                     last_last_hash,
808                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
809                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
810                 ))
811         
812         # decide best tree
813         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)
814         if p2pool.DEBUG:
815             print len(decorated_tails), 'tails:'
816             for score, tail_hash in decorated_tails:
817                 print format_hash(tail_hash), score
818         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
819         
820         # decide best verified head
821         decorated_heads = sorted(((
822             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
823             #self.items[h].peer_addr is None,
824             -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
825             -self.items[h].time_seen,
826         ), h) for h in self.verified.tails.get(best_tail, []))
827         if p2pool.DEBUG:
828             print len(decorated_heads), 'heads. Top 10:'
829             for score, head_hash in decorated_heads[-10:]:
830                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
831         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
832         
833         if best is not None:
834             best_share = self.items[best]
835             punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
836             if punish > 0:
837                 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
838                 best = best_share.previous_hash
839             
840             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
841             target_cutoff = int(2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 + .5) if best_tail_score[1] is not None else 2**256-1
842         else:
843             timestamp_cutoff = int(time.time()) - 24*60*60
844             target_cutoff = 2**256-1
845         
846         if p2pool.DEBUG:
847             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))
848             for peer_addr, hash, ts, targ in desired:
849                 print '   ', None if peer_addr is None else '%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
850         
851         return best, [(peer_addr, hash) for peer_addr, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
852     
853     def score(self, share_hash, block_rel_height_func):
854         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
855         
856         head_height = self.verified.get_height(share_hash)
857         if head_height < self.net.CHAIN_LENGTH:
858             return head_height, None
859         
860         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
861         
862         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
863             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
864         
865         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work/((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
866
867 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
868     assert dist >= 2
869     near = tracker.items[previous_share_hash]
870     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
871     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
872     time = near.timestamp - far.timestamp
873     if time <= 0:
874         time = 1
875     if integer:
876         return attempts//time
877     return attempts/time
878
879 def get_average_stale_prop(tracker, share_hash, lookbehind):
880     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
881     return stales/(lookbehind + stales)
882
883 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
884     res = {}
885     for share in tracker.get_chain(share_hash, lookbehind - 1):
886         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
887         s = share.share_data['stale_info']
888         if s is not None:
889             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
890     if rates:
891         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
892         res = dict((k, v/dt) for k, v in res.iteritems())
893     return res
894
895 def get_user_stale_props(tracker, share_hash, lookbehind):
896     res = {}
897     for share in tracker.get_chain(share_hash, lookbehind - 1):
898         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
899         total += 1
900         if share.share_data['stale_info'] is not None:
901             stale += 1
902             total += 1
903         res[share.share_data['pubkey_hash']] = stale, total
904     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
905
906 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
907     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))
908     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
909     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
910     return res
911
912 def get_desired_version_counts(tracker, best_share_hash, dist):
913     res = {}
914     for share in tracker.get_chain(best_share_hash, dist):
915         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
916     return res
917
918 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
919     res = []
920     
921     desired_version_counts = get_desired_version_counts(tracker, best_share,
922         min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
923     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
924     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:
925         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
926             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
927                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
928     
929     if bitcoind_warning is not None:
930         if 'This is a pre-release test build' not in bitcoind_warning:
931             res.append('(from bitcoind) %s' % (bitcoind_warning,))
932     
933     if time.time() > bitcoind_work_value['last_update'] + 60:
934         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']),))
935     
936     return res
937
938 def format_hash(x):
939     if x is None:
940         return 'xxxxxxxx'
941     return '%08x' % (x % 2**32)
942
943 class ShareStore(object):
944     def __init__(self, prefix, net):
945         self.filename = prefix
946         self.dirname = os.path.dirname(os.path.abspath(prefix))
947         self.filename = os.path.basename(os.path.abspath(prefix))
948         self.net = net
949         self.known = None # will be filename -> set of share hashes, set of verified hashes
950         self.known_desired = None
951     
952     def get_shares(self):
953         if self.known is not None:
954             raise AssertionError()
955         known = {}
956         filenames, next = self.get_filenames_and_next()
957         for filename in filenames:
958             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
959             with open(filename, 'rb') as f:
960                 for line in f:
961                     try:
962                         type_id_str, data_hex = line.strip().split(' ')
963                         type_id = int(type_id_str)
964                         if type_id == 0:
965                             pass
966                         elif type_id == 1:
967                             pass
968                         elif type_id == 2:
969                             verified_hash = int(data_hex, 16)
970                             yield 'verified_hash', verified_hash
971                             verified_hashes.add(verified_hash)
972                         elif type_id == 5:
973                             raw_share = share_type.unpack(data_hex.decode('hex'))
974                             if raw_share['type'] in [0, 1, 2, 3, 4, 5, 6, 7, 8]:
975                                 continue
976                             share = load_share(raw_share, self.net, None)
977                             yield 'share', share
978                             share_hashes.add(share.hash)
979                         else:
980                             raise NotImplementedError("share type %i" % (type_id,))
981                     except Exception:
982                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
983         self.known = known
984         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
985     
986     def _add_line(self, line):
987         filenames, next = self.get_filenames_and_next()
988         if filenames and os.path.getsize(filenames[-1]) < 10e6:
989             filename = filenames[-1]
990         else:
991             filename = next
992         
993         with open(filename, 'ab') as f:
994             f.write(line + '\n')
995         
996         return filename
997     
998     def add_share(self, share):
999         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
1000             if share.hash in share_hashes:
1001                 break
1002         else:
1003             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
1004             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
1005             share_hashes.add(share.hash)
1006         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
1007         share_hashes.add(share.hash)
1008     
1009     def add_verified_hash(self, share_hash):
1010         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
1011             if share_hash in verified_hashes:
1012                 break
1013         else:
1014             filename = self._add_line("%i %x" % (2, share_hash))
1015             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
1016             verified_hashes.add(share_hash)
1017         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
1018         verified_hashes.add(share_hash)
1019     
1020     def get_filenames_and_next(self):
1021         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())
1022         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)))
1023     
1024     def forget_share(self, share_hash):
1025         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1026             if share_hash in share_hashes:
1027                 share_hashes.remove(share_hash)
1028         self.check_remove()
1029     
1030     def forget_verified_share(self, share_hash):
1031         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1032             if share_hash in verified_hashes:
1033                 verified_hashes.remove(share_hash)
1034         self.check_remove()
1035     
1036     def check_remove(self):
1037         to_remove = set()
1038         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1039             #print filename, len(share_hashes) + len(verified_hashes)
1040             if not share_hashes and not verified_hashes:
1041                 to_remove.add(filename)
1042         for filename in to_remove:
1043             self.known.pop(filename)
1044             self.known_desired.pop(filename)
1045             os.remove(filename)
1046             print "REMOVED", filename