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