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