fixed punishing block solutions
[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     else:
54         raise ValueError('unknown share type: %r' % (share['type'],))
55
56 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
57
58 class Share(object):
59     small_block_header_type = pack.ComposedType([
60         ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
61         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
62         ('timestamp', pack.IntType(32)),
63         ('bits', bitcoin_data.FloatingIntegerType()),
64         ('nonce', pack.IntType(32)),
65     ])
66     
67     share_data_type = pack.ComposedType([
68         ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
69         ('coinbase', pack.VarStrType()),
70         ('nonce', pack.IntType(32)),
71         ('pubkey_hash', pack.IntType(160)),
72         ('subsidy', pack.IntType(64)),
73         ('donation', pack.IntType(16)),
74         ('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)))),
75         ('desired_version', pack.VarIntType()),
76     ])
77     
78     share_info_type = pack.ComposedType([
79         ('share_data', share_data_type),
80         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
81         ('max_bits', bitcoin_data.FloatingIntegerType()),
82         ('bits', bitcoin_data.FloatingIntegerType()),
83         ('timestamp', pack.IntType(32)),
84     ])
85     
86     share_common_type = pack.ComposedType([
87         ('min_header', small_block_header_type),
88         ('share_info', share_info_type),
89         ('ref_merkle_link', pack.ComposedType([
90             ('branch', pack.ListType(pack.IntType(256))),
91             ('index', pack.VarIntType()),
92         ])),
93         ('hash_link', hash_link_type),
94     ])
95     share1a_type = pack.ComposedType([
96         ('common', share_common_type),
97         ('merkle_link', pack.ComposedType([
98             ('branch', pack.ListType(pack.IntType(256))),
99             ('index', pack.IntType(0)), # it will always be 0
100         ])),
101     ])
102     share1b_type = pack.ComposedType([
103         ('common', share_common_type),
104         ('other_txs', pack.ListType(bitcoin_data.tx_type)),
105     ])
106     
107     ref_type = pack.ComposedType([
108         ('identifier', pack.FixedStrType(64//8)),
109         ('share_info', share_info_type),
110     ])
111     
112     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
113     
114     @classmethod
115     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
116         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
117         
118         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
119         assert height >= net.REAL_CHAIN_LENGTH or last is None
120         if height < net.TARGET_LOOKBEHIND:
121             pre_target3 = net.MAX_TARGET
122         else:
123             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
124             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
125             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
126             pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
127         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
128         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
129         
130         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
131             min(height, net.REAL_CHAIN_LENGTH),
132             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
133         )
134         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
135         
136         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
137         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
138         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
139         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
140         
141         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
142             raise ValueError()
143         
144         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
145         
146         share_info = dict(
147             share_data=share_data,
148             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
149             max_bits=max_bits,
150             bits=bits,
151             timestamp=math.clip(desired_timestamp, (
152                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
153                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
154             )) if previous_share is not None else desired_timestamp,
155         )
156         
157         gentx = dict(
158             version=1,
159             tx_ins=[dict(
160                 previous_output=None,
161                 sequence=None,
162                 script=share_data['coinbase'].ljust(2, '\x00'),
163             )],
164             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
165                 value=0,
166                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
167             )],
168             lock_time=0,
169         )
170         
171         def get_share(header, transactions):
172             assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
173             min_header = dict(header);del min_header['merkle_root']
174             hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
175             merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
176             pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
177             return cls(net, None, dict(
178                 min_header=min_header, share_info=share_info, hash_link=hash_link,
179                 ref_merkle_link=dict(branch=[], index=0),
180             ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
181         
182         return share_info, gentx, desired_other_transaction_hashes, get_share
183     
184     @classmethod
185     def get_ref_hash(cls, net, share_info, ref_merkle_link):
186         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
187             identifier=net.IDENTIFIER,
188             share_info=share_info,
189         ))), ref_merkle_link))
190     
191     __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(' ')
192     
193     def __init__(self, net, peer, common, merkle_link, other_txs):
194         self.net = net
195         self.peer = peer
196         self.common = common
197         self.min_header = common['min_header']
198         self.share_info = common['share_info']
199         self.hash_link = common['hash_link']
200         self.merkle_link = merkle_link
201         self.other_txs = other_txs
202         
203         if len(self.share_info['share_data']['coinbase']) > 100:
204             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
205         
206         if len(merkle_link['branch']) > 16:
207             raise ValueError('merkle branch too long!')
208         
209         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:
210             raise ValueError('merkle_link and other_txs do not match')
211         
212         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
213         
214         self.share_data = self.share_info['share_data']
215         self.max_target = self.share_info['max_bits'].target
216         self.target = self.share_info['bits'].target
217         self.timestamp = self.share_info['timestamp']
218         self.previous_hash = self.share_data['previous_share_hash']
219         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
220         self.desired_version = self.share_data['desired_version']
221         
222         self.gentx_hash = check_hash_link(
223             self.hash_link,
224             self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
225             self.gentx_before_refhash,
226         )
227         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
228         self.header = dict(self.min_header, merkle_root=merkle_root)
229         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
230         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
231         
232         if self.pow_hash > self.target:
233             from p2pool import p2p
234             raise p2p.PeerMisbehavingError('share PoW invalid')
235         
236         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
237             raise ValueError('other_txs provided when not a block solution')
238         if other_txs is None and self.pow_hash <= self.header['bits'].target:
239             raise ValueError('other_txs not provided when a block solution')
240         
241         self.new_transaction_hashes = []
242         
243         # XXX eww
244         self.time_seen = time.time()
245     
246     def __repr__(self):
247         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
248     
249     def as_share1a(self):
250         return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
251     
252     def as_share1b(self):
253         return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
254     
255     def as_share(self):
256         if not self.pow_hash <= self.header['bits'].target: # share1a
257             return self.as_share1a()
258         else:
259             return self.as_share1b()
260     
261     def check(self, tracker):
262         if self.share_data['previous_share_hash'] is not None:
263             previous_share = tracker.items[self.share_data['previous_share_hash']]
264             if isinstance(previous_share, NewShare):
265                 from p2pool import p2p
266                 raise p2p.PeerMisbehavingError('''Share can't follow NewShare''')
267         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
268         if share_info != self.share_info:
269             raise ValueError('share_info invalid')
270         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
271             raise ValueError('''gentx doesn't match hash_link''')
272         return gentx # only used by as_block
273     
274     def get_other_tx_hashes(self, tracker):
275         return []
276     
277     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
278         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
279             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
280         
281         if self.pow_hash <= self.header['bits'].target:
282             return -1, 'block solution'
283         
284         return False, None
285     
286     def as_block(self, tracker, known_txs):
287         if self.other_txs is None:
288             raise ValueError('share does not contain all txs')
289         return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
290
291 class NewShare(object):
292     VERSION = 8
293     
294     other_txs = None
295     
296     small_block_header_type = pack.ComposedType([
297         ('version', pack.VarIntType()),
298         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
299         ('timestamp', pack.IntType(32)),
300         ('bits', bitcoin_data.FloatingIntegerType()),
301         ('nonce', pack.IntType(32)),
302     ])
303     
304     share_info_type = pack.ComposedType([
305         ('share_data', pack.ComposedType([
306             ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
307             ('coinbase', pack.VarStrType()),
308             ('nonce', pack.IntType(32)),
309             ('pubkey_hash', pack.IntType(160)),
310             ('subsidy', pack.IntType(64)),
311             ('donation', pack.IntType(16)),
312             ('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)))),
313             ('desired_version', pack.VarIntType()),
314         ])),
315         ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
316         ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
317             ('share_count', pack.VarIntType()),
318             ('tx_count', pack.VarIntType()),
319         ]))),
320         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
321         ('max_bits', bitcoin_data.FloatingIntegerType()),
322         ('bits', bitcoin_data.FloatingIntegerType()),
323         ('timestamp', pack.IntType(32)),
324     ])
325     
326     share_type = pack.ComposedType([
327         ('min_header', small_block_header_type),
328         ('share_info', share_info_type),
329         ('ref_merkle_link', pack.ComposedType([
330             ('branch', pack.ListType(pack.IntType(256))),
331             ('index', pack.IntType(0)),
332         ])),
333         ('hash_link', hash_link_type),
334         ('merkle_link', pack.ComposedType([
335             ('branch', pack.ListType(pack.IntType(256))),
336             ('index', pack.IntType(0)), # it will always be 0
337         ])),
338     ])
339     
340     ref_type = pack.ComposedType([
341         ('identifier', pack.FixedStrType(64//8)),
342         ('share_info', share_info_type),
343     ])
344     
345     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
346     
347     @classmethod
348     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
349         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
350         
351         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
352         assert height >= net.REAL_CHAIN_LENGTH or last is None
353         if height < net.TARGET_LOOKBEHIND:
354             pre_target3 = net.MAX_TARGET
355         else:
356             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
357             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
358             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
359             pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
360         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
361         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
362         
363         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
364             min(height, net.REAL_CHAIN_LENGTH),
365             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
366         )
367         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
368         
369         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
370         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
371         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
372         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
373         
374         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
375             raise ValueError()
376         
377         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
378         
379         new_transaction_hashes = []
380         new_transaction_size = 0
381         transaction_hash_refs = []
382         other_transaction_hashes = []
383         
384         for tx_hash in desired_other_transaction_hashes:
385             for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
386                 if tx_hash in share.new_transaction_hashes:
387                     this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
388                     break
389             else:
390                 if known_txs is not None:
391                     this_size = len(bitcoin_data.tx_type.pack(known_txs[tx_hash]))
392                     if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
393                         break
394                     new_transaction_size += this_size
395                 new_transaction_hashes.append(tx_hash)
396                 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
397             transaction_hash_refs.append(this)
398             other_transaction_hashes.append(tx_hash)
399         
400         share_info = dict(
401             share_data=share_data,
402             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
403             max_bits=max_bits,
404             bits=bits,
405             timestamp=math.clip(desired_timestamp, (
406                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
407                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
408             )) if previous_share is not None else desired_timestamp,
409             new_transaction_hashes=new_transaction_hashes,
410             transaction_hash_refs=transaction_hash_refs,
411         )
412         
413         gentx = dict(
414             version=1,
415             tx_ins=[dict(
416                 previous_output=None,
417                 sequence=None,
418                 script=share_data['coinbase'],
419             )],
420             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
421                 value=0,
422                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
423             )],
424             lock_time=0,
425         )
426         
427         def get_share(header, transactions):
428             min_header=dict(header);del min_header['merkle_root']
429             return cls(net, None, dict(
430                 min_header=min_header,
431                 share_info=share_info,
432                 ref_merkle_link=dict(branch=[], index=0),
433                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
434                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
435             ))
436         
437         return share_info, gentx, other_transaction_hashes, get_share
438     
439     @classmethod
440     def get_ref_hash(cls, net, share_info, ref_merkle_link):
441         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
442             identifier=net.IDENTIFIER,
443             share_info=share_info,
444         ))), ref_merkle_link))
445     
446     __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(' ')
447     
448     def __init__(self, net, peer, contents):
449         self.net = net
450         self.peer = peer
451         self.contents = contents
452         
453         self.min_header = contents['min_header']
454         self.share_info = contents['share_info']
455         self.hash_link = contents['hash_link']
456         self.merkle_link = contents['merkle_link']
457         
458         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
459             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
460         
461         if len(self.merkle_link['branch']) > 16:
462             raise ValueError('merkle branch too long!')
463         
464         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
465         
466         self.share_data = self.share_info['share_data']
467         self.max_target = self.share_info['max_bits'].target
468         self.target = self.share_info['bits'].target
469         self.timestamp = self.share_info['timestamp']
470         self.previous_hash = self.share_data['previous_share_hash']
471         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
472         self.desired_version = self.share_data['desired_version']
473         
474         for x in self.share_info['transaction_hash_refs']:
475             assert x['share_count'] < 110
476         for i, x in enumerate(self.share_info['new_transaction_hashes']):
477             assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
478         
479         self.gentx_hash = check_hash_link(
480             self.hash_link,
481             self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
482             self.gentx_before_refhash,
483         )
484         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
485         self.header = dict(self.min_header, merkle_root=merkle_root)
486         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
487         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
488         
489         if self.target > net.MAX_TARGET:
490             from p2pool import p2p
491             raise p2p.PeerMisbehavingError('share target invalid')
492         
493         if self.pow_hash > self.target:
494             from p2pool import p2p
495             raise p2p.PeerMisbehavingError('share PoW invalid')
496         
497         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
498         
499         # XXX eww
500         self.time_seen = time.time()
501     
502     def __repr__(self):
503         return 'Share' + repr((self.net, self.peer, self.contents))
504     
505     def as_share(self):
506         return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
507     
508     def check(self, tracker):
509         if self.share_data['previous_share_hash'] is not None:
510             previous_share = tracker.items[self.share_data['previous_share_hash']]
511             if isinstance(previous_share, Share):
512                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
513                     from p2pool import p2p
514                     raise p2p.PeerMisbehavingError('NewShare without enough history')
515                 else:
516                     # Share -> NewShare only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
517                     counts = get_desired_version_counts(tracker,
518                         tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
519                     if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
520                         from p2pool import p2p
521                         raise p2p.PeerMisbehavingError('NewShare without enough hash power upgraded')
522         
523         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']]
524         
525         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)
526         assert other_tx_hashes2 == other_tx_hashes
527         if share_info != self.share_info:
528             raise ValueError('share_info invalid')
529         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
530             raise ValueError('''gentx doesn't match hash_link''')
531         
532         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
533             raise ValueError('merkle_link and other_tx_hashes do not match')
534         
535         return gentx # only used by as_block
536     
537     def get_other_tx_hashes(self, tracker):
538         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']]
539     
540     def _get_other_txs(self, tracker, known_txs):
541         other_tx_hashes = self.get_other_tx_hashes(tracker)
542         
543         if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
544             return None # not all txs present
545         
546         return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
547     
548     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
549         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
550             return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
551         
552         if self.pow_hash <= self.header['bits'].target:
553             return -1, 'block solution'
554         
555         other_txs = self._get_other_txs(tracker, known_txs)
556         if other_txs is None:
557             return True, 'not all txs present'
558         
559         all_txs_size = sum(len(bitcoin_data.tx_type.pack(tx)) for tx in other_txs)
560         if all_txs_size > 1000000:
561             return True, 'txs over block size limit'
562         
563         new_txs_size = sum(len(bitcoin_data.tx_type.pack(known_txs[tx_hash])) for tx_hash in self.share_info['new_transaction_hashes'])
564         if new_txs_size > 50000:
565             return True, 'new txs over limit'
566         
567         return False, None
568     
569     def as_block(self, tracker, known_txs):
570         other_txs = self._get_other_txs(tracker, known_txs)
571         if other_txs is None:
572             return None # not all txs present
573         return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
574
575
576 class WeightsSkipList(forest.TrackerSkipList):
577     # share_count, weights, total_weight
578     
579     def get_delta(self, element):
580         from p2pool.bitcoin import data as bitcoin_data
581         share = self.tracker.items[element]
582         att = bitcoin_data.target_to_average_attempts(share.target)
583         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
584     
585     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
586         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
587     
588     def initial_solution(self, start, (max_shares, desired_weight)):
589         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
590         return 0, None, 0, 0
591     
592     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)):
593         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
594             assert (desired_weight - total_weight1) % 65535 == 0
595             script, = weights2.iterkeys()
596             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
597             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)
598         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
599     
600     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
601         if share_count > max_shares or total_weight > desired_weight:
602             return 1
603         elif share_count == max_shares or total_weight == desired_weight:
604             return 0
605         else:
606             return -1
607     
608     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
609         assert share_count <= max_shares and total_weight <= desired_weight
610         assert share_count == max_shares or total_weight == desired_weight
611         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
612
613 class OkayTracker(forest.Tracker):
614     def __init__(self, net):
615         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
616             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
617             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
618         )))
619         self.net = net
620         self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
621             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
622         )), subset_of=self)
623         self.get_cumulative_weights = WeightsSkipList(self)
624     
625     def attempt_verify(self, share):
626         if share.hash in self.verified.items:
627             return True
628         height, last = self.get_height_and_last(share.hash)
629         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
630             raise AssertionError()
631         try:
632             share.check(self)
633         except:
634             log.err(None, 'Share check failed:')
635             return False
636         else:
637             self.verified.add(share)
638             return True
639     
640     def think(self, block_rel_height_func, previous_block, bits, known_txs):
641         desired = set()
642         
643         # O(len(self.heads))
644         #   make 'unverified heads' set?
645         # for each overall head, attempt verification
646         # if it fails, attempt on parent, and repeat
647         # if no successful verification because of lack of parents, request parent
648         bads = set()
649         for head in set(self.heads) - set(self.verified.heads):
650             head_height, last = self.get_height_and_last(head)
651             
652             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
653                 if self.attempt_verify(share):
654                     break
655                 if share.hash in self.heads:
656                     bads.add(share.hash)
657             else:
658                 if last is not None:
659                     desired.add((
660                         self.items[random.choice(list(self.reverse[last]))].peer,
661                         last,
662                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
663                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
664                     ))
665         for bad in bads:
666             assert bad not in self.verified.items
667             assert bad in self.heads
668             if p2pool.DEBUG:
669                 print "BAD", bad
670             self.remove(bad)
671         
672         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
673         for head in list(self.verified.heads):
674             head_height, last_hash = self.verified.get_height_and_last(head)
675             last_height, last_last_hash = self.get_height_and_last(last_hash)
676             # XXX review boundary conditions
677             want = max(self.net.CHAIN_LENGTH - head_height, 0)
678             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
679             get = min(want, can)
680             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
681             for share in self.get_chain(last_hash, get):
682                 if not self.attempt_verify(share):
683                     break
684             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
685                 desired.add((
686                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
687                     last_last_hash,
688                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
689                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
690                 ))
691         
692         # decide best tree
693         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)
694         if p2pool.DEBUG:
695             print len(decorated_tails), 'tails:'
696             for score, tail_hash in decorated_tails:
697                 print format_hash(tail_hash), score
698         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
699         
700         # decide best verified head
701         decorated_heads = sorted(((
702             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
703             #self.items[h].peer is None,
704             -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
705             -self.items[h].time_seen,
706         ), h) for h in self.verified.tails.get(best_tail, []))
707         if p2pool.DEBUG:
708             print len(decorated_heads), 'heads. Top 10:'
709             for score, head_hash in decorated_heads[-10:]:
710                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
711         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
712         
713         if best is not None:
714             best_share = self.items[best]
715             punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
716             if punish > 0:
717                 if p2pool.DEBUG:
718                     print >>sys.stderr, 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
719                 best = best_share.previous_hash
720             
721             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
722             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
723         else:
724             timestamp_cutoff = int(time.time()) - 24*60*60
725             target_cutoff = 2**256-1
726         
727         if p2pool.DEBUG:
728             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))
729             for peer, hash, ts, targ in desired:
730                 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
731         
732         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
733     
734     def score(self, share_hash, block_rel_height_func):
735         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
736         
737         head_height = self.verified.get_height(share_hash)
738         if head_height < self.net.CHAIN_LENGTH:
739             return head_height, None
740         
741         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
742         
743         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
744             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
745         
746         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
747
748 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
749     assert dist >= 2
750     near = tracker.items[previous_share_hash]
751     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
752     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
753     time = near.timestamp - far.timestamp
754     if time <= 0:
755         time = 1
756     if integer:
757         return attempts//time
758     return attempts/time
759
760 def get_average_stale_prop(tracker, share_hash, lookbehind):
761     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
762     return stales/(lookbehind + stales)
763
764 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
765     res = {}
766     for share in tracker.get_chain(share_hash, lookbehind - 1):
767         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
768         s = share.share_data['stale_info']
769         if s is not None:
770             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
771     if rates:
772         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
773         res = dict((k, v/dt) for k, v in res.iteritems())
774     return res
775
776 def get_user_stale_props(tracker, share_hash, lookbehind):
777     res = {}
778     for share in tracker.get_chain(share_hash, lookbehind - 1):
779         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
780         total += 1
781         if share.share_data['stale_info'] is not None:
782             stale += 1
783             total += 1
784         res[share.share_data['pubkey_hash']] = stale, total
785     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
786
787 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
788     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))
789     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
790     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
791     return res
792
793 def get_desired_version_counts(tracker, best_share_hash, dist):
794     res = {}
795     for share in tracker.get_chain(best_share_hash, dist):
796         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
797     return res
798
799 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
800     res = []
801     
802     desired_version_counts = get_desired_version_counts(tracker, best_share,
803         min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
804     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
805     if majority_desired_version > NewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
806         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
807             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
808                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
809     
810     if bitcoind_warning is not None:
811         res.append('(from bitcoind) %s' % (bitcoind_warning,))
812     
813     if time.time() > bitcoind_work_value['last_update'] + 60:
814         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']),))
815     
816     return res
817
818 def format_hash(x):
819     if x is None:
820         return 'xxxxxxxx'
821     return '%08x' % (x % 2**32)
822
823 class ShareStore(object):
824     def __init__(self, prefix, net):
825         self.filename = prefix
826         self.dirname = os.path.dirname(os.path.abspath(prefix))
827         self.filename = os.path.basename(os.path.abspath(prefix))
828         self.net = net
829         self.known = None # will be filename -> set of share hashes, set of verified hashes
830         self.known_desired = None
831     
832     def get_shares(self):
833         if self.known is not None:
834             raise AssertionError()
835         known = {}
836         filenames, next = self.get_filenames_and_next()
837         for filename in filenames:
838             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
839             with open(filename, 'rb') as f:
840                 for line in f:
841                     try:
842                         type_id_str, data_hex = line.strip().split(' ')
843                         type_id = int(type_id_str)
844                         if type_id == 0:
845                             pass
846                         elif type_id == 1:
847                             pass
848                         elif type_id == 2:
849                             verified_hash = int(data_hex, 16)
850                             yield 'verified_hash', verified_hash
851                             verified_hashes.add(verified_hash)
852                         elif type_id == 5:
853                             raw_share = share_type.unpack(data_hex.decode('hex'))
854                             if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
855                                 continue
856                             share = load_share(raw_share, self.net, None)
857                             yield 'share', share
858                             share_hashes.add(share.hash)
859                         else:
860                             raise NotImplementedError("share type %i" % (type_id,))
861                     except Exception:
862                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
863         self.known = known
864         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
865     
866     def _add_line(self, line):
867         filenames, next = self.get_filenames_and_next()
868         if filenames and os.path.getsize(filenames[-1]) < 10e6:
869             filename = filenames[-1]
870         else:
871             filename = next
872         
873         with open(filename, 'ab') as f:
874             f.write(line + '\n')
875         
876         return filename
877     
878     def add_share(self, share):
879         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
880             if share.hash in share_hashes:
881                 break
882         else:
883             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
884             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
885             share_hashes.add(share.hash)
886         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
887         share_hashes.add(share.hash)
888     
889     def add_verified_hash(self, share_hash):
890         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
891             if share_hash in verified_hashes:
892                 break
893         else:
894             filename = self._add_line("%i %x" % (2, share_hash))
895             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
896             verified_hashes.add(share_hash)
897         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
898         verified_hashes.add(share_hash)
899     
900     def get_filenames_and_next(self):
901         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())
902         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)))
903     
904     def forget_share(self, share_hash):
905         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
906             if share_hash in share_hashes:
907                 share_hashes.remove(share_hash)
908         self.check_remove()
909     
910     def forget_verified_share(self, share_hash):
911         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
912             if share_hash in verified_hashes:
913                 verified_hashes.remove(share_hash)
914         self.check_remove()
915     
916     def check_remove(self):
917         to_remove = set()
918         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
919             #print filename, len(share_hashes) + len(verified_hashes)
920             if not share_hashes and not verified_hashes:
921                 to_remove.add(filename)
922         for filename in to_remove:
923             self.known.pop(filename)
924             self.known_desired.pop(filename)
925             os.remove(filename)
926             print "REMOVED", filename