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