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