moving forgetting about old shares into node
[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 get_other_txs(self, tracker, known_txs):
278         return []
279     
280     def get_other_txs_size(self, tracker, known_txs):
281         return 0
282     
283     def get_new_txs_size(self, known_txs):
284         return 0
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 get_other_txs_size(self, tracker, known_txs):
549         other_txs = self.get_other_txs(tracker, known_txs)
550         if other_txs is None:
551             return None # not all txs present
552         size = sum(len(bitcoin_data.tx_type.pack(tx)) for tx in other_txs)
553     
554     def get_new_txs_size(self, known_txs):
555         if not all(tx_hash in known_txs for tx_hash in self.share_info['new_transaction_hashes']):
556             return None # not all txs present
557         return sum(len(bitcoin_data.tx_type.pack(known_txs[tx_hash])) for tx_hash in self.share_info['new_transaction_hashes'])
558     
559     def as_block(self, tracker, known_txs):
560         other_txs = self.get_other_txs(tracker, known_txs)
561         if other_txs is None:
562             return None # not all txs present
563         return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
564
565
566 class WeightsSkipList(forest.TrackerSkipList):
567     # share_count, weights, total_weight
568     
569     def get_delta(self, element):
570         from p2pool.bitcoin import data as bitcoin_data
571         share = self.tracker.items[element]
572         att = bitcoin_data.target_to_average_attempts(share.target)
573         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
574     
575     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
576         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
577     
578     def initial_solution(self, start, (max_shares, desired_weight)):
579         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
580         return 0, None, 0, 0
581     
582     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)):
583         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
584             assert (desired_weight - total_weight1) % 65535 == 0
585             script, = weights2.iterkeys()
586             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
587             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)
588         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
589     
590     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
591         if share_count > max_shares or total_weight > desired_weight:
592             return 1
593         elif share_count == max_shares or total_weight == desired_weight:
594             return 0
595         else:
596             return -1
597     
598     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
599         assert share_count <= max_shares and total_weight <= desired_weight
600         assert share_count == max_shares or total_weight == desired_weight
601         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
602
603 class OkayTracker(forest.Tracker):
604     def __init__(self, net):
605         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
606             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
607             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
608         )))
609         self.net = net
610         self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
611             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
612         )), subset_of=self)
613         self.get_cumulative_weights = WeightsSkipList(self)
614     
615     def attempt_verify(self, share):
616         if share.hash in self.verified.items:
617             return True
618         height, last = self.get_height_and_last(share.hash)
619         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
620             raise AssertionError()
621         try:
622             share.check(self)
623         except:
624             log.err(None, 'Share check failed:')
625             return False
626         else:
627             self.verified.add(share)
628             return True
629     
630     def think(self, block_rel_height_func, previous_block, bits, known_txs):
631         desired = set()
632         
633         # O(len(self.heads))
634         #   make 'unverified heads' set?
635         # for each overall head, attempt verification
636         # if it fails, attempt on parent, and repeat
637         # if no successful verification because of lack of parents, request parent
638         bads = set()
639         for head in set(self.heads) - set(self.verified.heads):
640             head_height, last = self.get_height_and_last(head)
641             
642             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
643                 if self.attempt_verify(share):
644                     break
645                 if share.hash in self.heads:
646                     bads.add(share.hash)
647             else:
648                 if last is not None:
649                     desired.add((
650                         self.items[random.choice(list(self.reverse[last]))].peer,
651                         last,
652                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
653                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
654                     ))
655         for bad in bads:
656             assert bad not in self.verified.items
657             assert bad in self.heads
658             if p2pool.DEBUG:
659                 print "BAD", bad
660             self.remove(bad)
661         
662         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
663         for head in list(self.verified.heads):
664             head_height, last_hash = self.verified.get_height_and_last(head)
665             last_height, last_last_hash = self.get_height_and_last(last_hash)
666             # XXX review boundary conditions
667             want = max(self.net.CHAIN_LENGTH - head_height, 0)
668             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
669             get = min(want, can)
670             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
671             for share in self.get_chain(last_hash, get):
672                 if not self.attempt_verify(share):
673                     break
674             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
675                 desired.add((
676                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
677                     last_last_hash,
678                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
679                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
680                 ))
681         
682         # decide best tree
683         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)
684         if p2pool.DEBUG:
685             print len(decorated_tails), 'tails:'
686             for score, tail_hash in decorated_tails:
687                 print format_hash(tail_hash), score
688         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
689         
690         # decide best verified head
691         decorated_heads = sorted(((
692             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
693             #self.items[h].peer is None,
694             self.items[h].pow_hash <= self.items[h].header['bits'].target, # is block solution
695             (self.items[h].header['previous_block'], self.items[h].header['bits']) == (previous_block, bits) or self.items[h].peer is None,
696             self.items[h].get_other_txs(self, known_txs) is not None,
697             self.items[h].get_other_txs_size(self, known_txs) < 1000000,
698             self.items[h].get_new_txs_size(known_txs) < 50000,
699             -self.items[h].time_seen,
700         ), h) for h in self.verified.tails.get(best_tail, []))
701         if p2pool.DEBUG:
702             print len(decorated_heads), 'heads. Top 10:'
703             for score, head_hash in decorated_heads[-10:]:
704                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
705         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
706         
707         if best is not None:
708             best_share = self.items[best]
709             if (best_share.header['previous_block'], best_share.header['bits']) != (previous_block, bits) and best_share.header_hash != previous_block and best_share.peer is not None:
710                 if p2pool.DEBUG:
711                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
712                 best = best_share.previous_hash
713             elif best_share.get_other_txs(self, known_txs) is None:
714                 print 'Share with incomplete transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
715                 best = best_share.previous_hash
716             elif best_share.get_other_txs_size(self, known_txs) > 1000000:
717                 print >>sys.stderr, 'Share with too many transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
718                 best = best_share.previous_hash
719             elif best_share.get_new_txs_size(known_txs) > 50000:
720                 print >>sys.stderr, 'Share with too many new transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
721                 best = best_share.previous_hash
722             
723             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
724             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
725         else:
726             timestamp_cutoff = int(time.time()) - 24*60*60
727             target_cutoff = 2**256-1
728         
729         if p2pool.DEBUG:
730             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))
731             for peer, hash, ts, targ in desired:
732                 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
733         
734         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
735     
736     def score(self, share_hash, block_rel_height_func):
737         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
738         
739         head_height = self.verified.get_height(share_hash)
740         if head_height < self.net.CHAIN_LENGTH:
741             return head_height, None
742         
743         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
744         
745         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
746             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
747         
748         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
749
750 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
751     assert dist >= 2
752     near = tracker.items[previous_share_hash]
753     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
754     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
755     time = near.timestamp - far.timestamp
756     if time <= 0:
757         time = 1
758     if integer:
759         return attempts//time
760     return attempts/time
761
762 def get_average_stale_prop(tracker, share_hash, lookbehind):
763     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
764     return stales/(lookbehind + stales)
765
766 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
767     res = {}
768     for share in tracker.get_chain(share_hash, lookbehind - 1):
769         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
770         s = share.share_data['stale_info']
771         if s is not None:
772             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
773     if rates:
774         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
775         res = dict((k, v/dt) for k, v in res.iteritems())
776     return res
777
778 def get_user_stale_props(tracker, share_hash, lookbehind):
779     res = {}
780     for share in tracker.get_chain(share_hash, lookbehind - 1):
781         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
782         total += 1
783         if share.share_data['stale_info'] is not None:
784             stale += 1
785             total += 1
786         res[share.share_data['pubkey_hash']] = stale, total
787     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
788
789 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
790     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))
791     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
792     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
793     return res
794
795 def get_desired_version_counts(tracker, best_share_hash, dist):
796     res = {}
797     for share in tracker.get_chain(best_share_hash, dist):
798         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
799     return res
800
801 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
802     res = []
803     
804     desired_version_counts = get_desired_version_counts(tracker, best_share,
805         min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
806     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
807     if majority_desired_version > NewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
808         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
809             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
810                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
811     
812     if bitcoind_warning is not None:
813         res.append('(from bitcoind) %s' % (bitcoind_warning,))
814     
815     if time.time() > bitcoind_work_value['last_update'] + 60:
816         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']),))
817     
818     return res
819
820 def format_hash(x):
821     if x is None:
822         return 'xxxxxxxx'
823     return '%08x' % (x % 2**32)
824
825 class ShareStore(object):
826     def __init__(self, prefix, net):
827         self.filename = prefix
828         self.dirname = os.path.dirname(os.path.abspath(prefix))
829         self.filename = os.path.basename(os.path.abspath(prefix))
830         self.net = net
831         self.known = None # will be filename -> set of share hashes, set of verified hashes
832         self.known_desired = None
833     
834     def get_shares(self):
835         if self.known is not None:
836             raise AssertionError()
837         known = {}
838         filenames, next = self.get_filenames_and_next()
839         for filename in filenames:
840             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
841             with open(filename, 'rb') as f:
842                 for line in f:
843                     try:
844                         type_id_str, data_hex = line.strip().split(' ')
845                         type_id = int(type_id_str)
846                         if type_id == 0:
847                             pass
848                         elif type_id == 1:
849                             pass
850                         elif type_id == 2:
851                             verified_hash = int(data_hex, 16)
852                             yield 'verified_hash', verified_hash
853                             verified_hashes.add(verified_hash)
854                         elif type_id == 5:
855                             raw_share = share_type.unpack(data_hex.decode('hex'))
856                             if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
857                                 continue
858                             share = load_share(raw_share, self.net, None)
859                             yield 'share', share
860                             share_hashes.add(share.hash)
861                         else:
862                             raise NotImplementedError("share type %i" % (type_id,))
863                     except Exception:
864                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
865         self.known = known
866         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
867     
868     def _add_line(self, line):
869         filenames, next = self.get_filenames_and_next()
870         if filenames and os.path.getsize(filenames[-1]) < 10e6:
871             filename = filenames[-1]
872         else:
873             filename = next
874         
875         with open(filename, 'ab') as f:
876             f.write(line + '\n')
877         
878         return filename
879     
880     def add_share(self, share):
881         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
882             if share.hash in share_hashes:
883                 break
884         else:
885             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
886             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
887             share_hashes.add(share.hash)
888         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
889         share_hashes.add(share.hash)
890     
891     def add_verified_hash(self, share_hash):
892         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
893             if share_hash in verified_hashes:
894                 break
895         else:
896             filename = self._add_line("%i %x" % (2, share_hash))
897             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
898             verified_hashes.add(share_hash)
899         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
900         verified_hashes.add(share_hash)
901     
902     def get_filenames_and_next(self):
903         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())
904         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)))
905     
906     def forget_share(self, share_hash):
907         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
908             if share_hash in share_hashes:
909                 share_hashes.remove(share_hash)
910         self.check_remove()
911     
912     def forget_verified_share(self, share_hash):
913         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
914             if share_hash in verified_hashes:
915                 verified_hashes.remove(share_hash)
916         self.check_remove()
917     
918     def check_remove(self):
919         to_remove = set()
920         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
921             #print filename, len(share_hashes) + len(verified_hashes)
922             if not share_hashes and not verified_hashes:
923                 to_remove.add(filename)
924         for filename in to_remove:
925             self.known.pop(filename)
926             self.known_desired.pop(filename)
927             os.remove(filename)
928             print "REMOVED", filename