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