2655f770bd646c87bb65c774793eed463db867e5
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import hashlib
4 import os
5 import random
6 import time
7
8 from twisted.python import log
9
10 import p2pool
11 from p2pool.bitcoin import data as bitcoin_data, script, sha256
12 from p2pool.util import math, forest, pack
13
14 # hashlink
15
16 hash_link_type = pack.ComposedType([
17     ('state', pack.FixedStrType(32)),
18     ('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
19     ('length', pack.VarIntType()),
20 ])
21
22 def prefix_to_hash_link(prefix, const_ending=''):
23     assert prefix.endswith(const_ending), (prefix, const_ending)
24     x = sha256.sha256(prefix)
25     return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
26
27 def check_hash_link(hash_link, data, const_ending=''):
28     extra_length = hash_link['length'] % (512//8)
29     assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
30     extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
31     assert len(extra) == extra_length
32     return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
33
34 # shares
35
36 # type:
37 # 2: share1a
38 # 3: share1b
39
40 share_type = pack.ComposedType([
41     ('type', pack.VarIntType()),
42     ('contents', pack.VarStrType()),
43 ])
44
45 def load_share(share, net, peer):
46     if share['type'] in [0, 1]:
47         from p2pool import p2p
48         raise p2p.PeerMisbehavingError('sent an obsolete share')
49     elif share['type'] == 2:
50         return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
51     elif share['type'] == 3:
52         share1b = Share.share1b_type.unpack(share['contents'])
53         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)
54     elif share['type'] == 4:
55         return NewShare(net, peer, other_txs=None, **NewShare.share1a_type.unpack(share['contents']))
56     elif share['type'] == 5:
57         share1b = NewShare.share1b_type.unpack(share['contents'])
58         return NewShare(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)
59     else:
60         raise ValueError('unknown share type: %r' % (share['type'],))
61
62 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
63
64 class Share(object):
65     small_block_header_type = pack.ComposedType([
66         ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
67         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
68         ('timestamp', pack.IntType(32)),
69         ('bits', bitcoin_data.FloatingIntegerType()),
70         ('nonce', pack.IntType(32)),
71     ])
72     
73     share_data_type = pack.ComposedType([
74         ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
75         ('coinbase', pack.VarStrType()),
76         ('nonce', pack.IntType(32)),
77         ('pubkey_hash', pack.IntType(160)),
78         ('subsidy', pack.IntType(64)),
79         ('donation', pack.IntType(16)),
80         ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
81     ])
82     
83     share_info_type = pack.ComposedType([
84         ('share_data', share_data_type),
85         ('max_bits', bitcoin_data.FloatingIntegerType()),
86         ('bits', bitcoin_data.FloatingIntegerType()),
87         ('timestamp', pack.IntType(32)),
88     ])
89     
90     share1a_type = pack.ComposedType([
91         ('min_header', small_block_header_type),
92         ('share_info', share_info_type),
93         ('hash_link', hash_link_type),
94         ('merkle_link', pack.ComposedType([
95             ('branch', pack.ListType(pack.IntType(256))),
96             ('index', pack.IntType(0)), # it will always be 0
97         ])),
98     ])
99     
100     share1b_type = pack.ComposedType([
101         ('min_header', small_block_header_type),
102         ('share_info', share_info_type),
103         ('hash_link', hash_link_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, net):
116         previous_share = tracker.shares[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             True,
134         )
135         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
136         
137         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
138         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
139         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
140         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
141         
142         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
143             raise ValueError()
144         
145         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
146         
147         share_info = dict(
148             share_data=share_data,
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         return share_info, 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]] + [dict(
165                 value=0,
166                 script='\x20' + pack.IntType(256).pack(bitcoin_data.hash256(cls.ref_type.pack(dict(
167                     identifier=net.IDENTIFIER,
168                     share_info=share_info,
169                 )))),
170             )],
171             lock_time=0,
172         )
173     
174     __slots__ = 'net 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 time_seen peer'.split(' ')
175     
176     def __init__(self, net, peer, min_header, share_info, hash_link, merkle_link, other_txs):
177         if len(share_info['share_data']['coinbase']) > 100:
178             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
179         
180         if len(merkle_link['branch']) > 16:
181             raise ValueError('merkle_branch too long!')
182         
183         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:
184             raise ValueError('merkle_link and other_txs do not match')
185         
186         assert not hash_link['extra_data'], repr(hash_link['extra_data'])
187         
188         self.net = net
189         self.peer = peer
190         self.min_header = min_header
191         self.share_info = share_info
192         self.hash_link = hash_link
193         self.merkle_link = merkle_link
194         self.other_txs = other_txs
195         
196         self.share_data = self.share_info['share_data']
197         self.max_target = self.share_info['max_bits'].target
198         self.target = self.share_info['bits'].target
199         self.timestamp = self.share_info['timestamp']
200         self.previous_hash = self.share_data['previous_share_hash']
201         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
202         self.desired_version = 0
203         
204         if self.timestamp > net.SWITCH_TIME:
205             from p2pool import p2p
206             raise p2p.PeerMisbehavingError('peer sent an old-style share with a timestamp after the switch time')
207         
208         self.gentx_hash = check_hash_link(
209             hash_link,
210             pack.IntType(256).pack(bitcoin_data.hash256(self.ref_type.pack(dict(
211                 identifier=net.IDENTIFIER,
212                 share_info=share_info,
213             )))) + pack.IntType(32).pack(0),
214             self.gentx_before_refhash,
215         )
216         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
217         self.header = dict(min_header, merkle_root=merkle_root)
218         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
219         self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
220         
221         if self.pow_hash > self.target:
222             raise p2p.PeerMisbehavingError('share PoW invalid')
223         
224         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
225             raise ValueError('other_txs provided when not a block solution')
226         if other_txs is None and self.pow_hash <= self.header['bits'].target:
227             raise ValueError('other_txs not provided when a block solution')
228         
229         self.hash = bitcoin_data.hash256(share_type.pack(self.as_share()))
230         
231         # XXX eww
232         self.time_seen = time.time()
233     
234     def __repr__(self):
235         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
236     
237     def check(self, tracker):
238         share_info, gentx = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
239         if share_info != self.share_info:
240             raise ValueError('share difficulty invalid')
241         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
242             raise ValueError('''gentx doesn't match hash_link''')
243     
244     def as_share(self):
245         if not self.pow_hash <= self.header['bits'].target: # share1a
246             return dict(type=2, contents=self.share1a_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, merkle_link=self.merkle_link)))
247         else: # share1b
248             return dict(type=3, contents=self.share1b_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, other_txs=self.other_txs)))
249     
250     def as_block(self, tracker):
251         if self.other_txs is None:
252             raise ValueError('share does not contain all txs')
253         
254         share_info, gentx = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
255         assert share_info == self.share_info
256         
257         return dict(header=self.header, txs=[gentx] + self.other_txs)
258
259 class NewShare(Share):
260     share_data_type = pack.ComposedType([
261         ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
262         ('coinbase', pack.VarStrType()),
263         ('nonce', pack.IntType(32)),
264         ('pubkey_hash', pack.IntType(160)),
265         ('subsidy', pack.IntType(64)),
266         ('donation', pack.IntType(16)),
267         ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
268         ('desired_version', pack.VarIntType()),
269     ])
270     
271     share_info_type = pack.ComposedType([
272         ('share_data', share_data_type),
273         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
274         ('max_bits', bitcoin_data.FloatingIntegerType()),
275         ('bits', bitcoin_data.FloatingIntegerType()),
276         ('timestamp', pack.IntType(32)),
277     ])
278     
279     share_common_type = pack.ComposedType([
280         ('min_header', Share.small_block_header_type),
281         ('share_info', share_info_type),
282         ('ref_merkle_link', pack.ComposedType([
283             ('branch', pack.ListType(pack.IntType(256))),
284             ('index', pack.VarIntType()),
285         ])),
286         ('hash_link', hash_link_type),
287     ])
288     share1a_type = pack.ComposedType([
289         ('common', share_common_type),
290         ('merkle_link', pack.ComposedType([
291             ('branch', pack.ListType(pack.IntType(256))),
292             ('index', pack.IntType(0)), # it will always be 0
293         ])),
294     ])
295     share1b_type = pack.ComposedType([
296         ('common', share_common_type),
297         ('other_txs', pack.ListType(bitcoin_data.tx_type)),
298     ])
299     
300     ref_type = pack.ComposedType([
301         ('identifier', pack.FixedStrType(64//8)),
302         ('share_info', share_info_type),
303     ])
304     
305     @classmethod
306     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, net):
307         previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
308         
309         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
310         assert height >= net.REAL_CHAIN_LENGTH or last is None
311         if height < net.TARGET_LOOKBEHIND:
312             pre_target3 = net.MAX_TARGET
313         else:
314             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
315             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
316             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
317             pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
318         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
319         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
320         
321         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
322             min(height, net.REAL_CHAIN_LENGTH),
323             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
324             False,
325         )
326         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
327         
328         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
329         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
330         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
331         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
332         
333         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
334             raise ValueError()
335         
336         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
337         
338         share_info = dict(
339             share_data=share_data,
340             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
341             max_bits=max_bits,
342             bits=bits,
343             timestamp=math.clip(desired_timestamp, (
344                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
345                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
346             )) if previous_share is not None else desired_timestamp,
347         )
348         
349         return share_info, dict(
350             version=1,
351             tx_ins=[dict(
352                 previous_output=None,
353                 sequence=None,
354                 script=share_data['coinbase'].ljust(2, '\x00'),
355             )],
356             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]] + [dict(
357                 value=0,
358                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
359             )],
360             lock_time=0,
361         )
362     
363     @classmethod
364     def get_ref_hash(cls, net, share_info, ref_merkle_link):
365         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
366             identifier=net.IDENTIFIER,
367             share_info=share_info,
368         ))), ref_merkle_link))
369     
370     __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 time_seen'.split(' ')
371     
372     def __init__(self, net, peer, common, merkle_link, other_txs):
373         self.net = net
374         self.peer = peer
375         self.common = common
376         self.min_header = common['min_header']
377         self.share_info = common['share_info']
378         self.hash_link = common['hash_link']
379         self.merkle_link = merkle_link
380         self.other_txs = other_txs
381         
382         if len(self.share_info['share_data']['coinbase']) > 100:
383             raise ValueError('''coinbase too large! %i bytes''' % (len(self.self.share_data['coinbase']),))
384         
385         if len(merkle_link['branch']) > 16:
386             raise ValueError('merkle branch too long!')
387         
388         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:
389             raise ValueError('merkle_link and other_txs do not match')
390         
391         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
392         
393         self.share_data = self.share_info['share_data']
394         self.max_target = self.share_info['max_bits'].target
395         self.target = self.share_info['bits'].target
396         self.timestamp = self.share_info['timestamp']
397         self.previous_hash = self.share_data['previous_share_hash']
398         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
399         self.desired_version = self.share_data['desired_version']
400         
401         if self.timestamp < net.SWITCH_TIME:
402             from p2pool import p2p
403             raise p2p.PeerMisbehavingError('peer sent a new-style share with a timestamp before the switch time')
404         
405         self.gentx_hash = check_hash_link(
406             self.hash_link,
407             self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
408             self.gentx_before_refhash,
409         )
410         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
411         self.header = dict(self.min_header, merkle_root=merkle_root)
412         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
413         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
414         
415         if self.pow_hash > self.target:
416             raise p2p.PeerMisbehavingError('share PoW invalid')
417         
418         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
419             raise ValueError('other_txs provided when not a block solution')
420         if other_txs is None and self.pow_hash <= self.header['bits'].target:
421             raise ValueError('other_txs not provided when a block solution')
422         
423         # XXX eww
424         self.time_seen = time.time()
425     
426     def as_share(self):
427         if not self.pow_hash <= self.header['bits'].target: # share1a
428             return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
429         else: # share1b
430             return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
431     
432     def check(self, tracker):
433         share_info, gentx = 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)
434         if share_info != self.share_info:
435             raise ValueError('share_info invalid')
436         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
437             raise ValueError('''gentx doesn't match hash_link''')
438         return gentx # only used by as_block
439     
440     def as_block(self, tracker):
441         if self.other_txs is None:
442             raise ValueError('share does not contain all txs')
443         return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
444
445 class WeightsSkipList(forest.TrackerSkipList):
446     # share_count, weights, total_weight
447     
448     def get_delta(self, element):
449         from p2pool.bitcoin import data as bitcoin_data
450         share = self.tracker.shares[element]
451         att = bitcoin_data.target_to_average_attempts(share.target)
452         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
453     
454     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
455         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
456     
457     def initial_solution(self, start, (max_shares, desired_weight, broken_mode)):
458         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
459         return 0, None, 0, 0
460     
461     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, broken_mode)):
462         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
463             assert (desired_weight - total_weight1) % 65535 == 0
464             script, = weights2.iterkeys()
465             if broken_mode:
466                 new_weights = dict(script=(desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535))
467             else:
468                 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
469             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)
470         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
471     
472     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight, broken_mode)):
473         if share_count > max_shares or total_weight > desired_weight:
474             return 1
475         elif share_count == max_shares or total_weight == desired_weight:
476             return 0
477         else:
478             return -1
479     
480     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight, broken_mode)):
481         assert share_count <= max_shares and total_weight <= desired_weight
482         assert share_count == max_shares or total_weight == desired_weight
483         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
484
485 class OkayTracker(forest.Tracker):
486     def __init__(self, net, my_share_hashes, my_doa_share_hashes):
487         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
488             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
489             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
490         )))
491         self.net = net
492         self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
493             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
494             my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
495             my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
496             my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 253 else 0,
497             my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 254 else 0,
498         )))
499         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
500         
501         self.get_cumulative_weights = WeightsSkipList(self)
502     
503     def attempt_verify(self, share):
504         if share.hash in self.verified.shares:
505             return True
506         height, last = self.get_height_and_last(share.hash)
507         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
508             raise AssertionError()
509         try:
510             share.check(self)
511         except:
512             log.err(None, 'Share check failed:')
513             return False
514         else:
515             self.verified.add(share)
516             return True
517     
518     def think(self, block_rel_height_func, previous_block, bits):
519         desired = set()
520         
521         # O(len(self.heads))
522         #   make 'unverified heads' set?
523         # for each overall head, attempt verification
524         # if it fails, attempt on parent, and repeat
525         # if no successful verification because of lack of parents, request parent
526         bads = set()
527         for head in set(self.heads) - set(self.verified.heads):
528             head_height, last = self.get_height_and_last(head)
529             
530             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
531                 if self.attempt_verify(share):
532                     break
533                 if share.hash in self.heads:
534                     bads.add(share.hash)
535             else:
536                 if last is not None:
537                     desired.add((
538                         self.shares[random.choice(list(self.reverse_shares[last]))].peer,
539                         last,
540                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
541                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
542                     ))
543         for bad in bads:
544             assert bad not in self.verified.shares
545             assert bad in self.heads
546             if p2pool.DEBUG:
547                 print "BAD", bad
548             self.remove(bad)
549         
550         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
551         for head in list(self.verified.heads):
552             head_height, last_hash = self.verified.get_height_and_last(head)
553             last_height, last_last_hash = self.get_height_and_last(last_hash)
554             # XXX review boundary conditions
555             want = max(self.net.CHAIN_LENGTH - head_height, 0)
556             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
557             get = min(want, can)
558             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
559             for share in self.get_chain(last_hash, get):
560                 if not self.attempt_verify(share):
561                     break
562             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
563                 desired.add((
564                     self.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
565                     last_last_hash,
566                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
567                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
568                 ))
569         
570         # decide best tree
571         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)
572         if p2pool.DEBUG:
573             print len(decorated_tails), 'tails:'
574             for score, tail_hash in decorated_tails:
575                 print format_hash(tail_hash), score
576         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
577         
578         # decide best verified head
579         decorated_heads = sorted(((
580             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
581             #self.shares[h].peer is None,
582             self.shares[h].pow_hash <= self.shares[h].header['bits'].target, # is block solution
583             (self.shares[h].header['previous_block'], self.shares[h].header['bits']) == (previous_block, bits) or self.shares[h].peer is None,
584             -self.shares[h].time_seen,
585         ), h) for h in self.verified.tails.get(best_tail, []))
586         if p2pool.DEBUG:
587             print len(decorated_heads), 'heads. Top 10:'
588             for score, head_hash in decorated_heads[-10:]:
589                 print '   ', format_hash(head_hash), format_hash(self.shares[head_hash].previous_hash), score
590         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
591         
592         # eat away at heads
593         if decorated_heads:
594             for i in xrange(1000):
595                 to_remove = set()
596                 for share_hash, tail in self.heads.iteritems():
597                     if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
598                         #print 1
599                         continue
600                     if self.shares[share_hash].time_seen > time.time() - 300:
601                         #print 2
602                         continue
603                     if share_hash not in self.verified.shares and max(self.shares[after_tail_hash].time_seen for after_tail_hash in self.reverse_shares.get(tail)) > time.time() - 120: # XXX stupid
604                         #print 3
605                         continue
606                     to_remove.add(share_hash)
607                 if not to_remove:
608                     break
609                 for share_hash in to_remove:
610                     self.remove(share_hash)
611                     if share_hash in self.verified.shares:
612                         self.verified.remove(share_hash)
613                 #print "_________", to_remove
614         
615         # drop tails
616         for i in xrange(1000):
617             to_remove = set()
618             for tail, heads in self.tails.iteritems():
619                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
620                     continue
621                 for aftertail in self.reverse_shares.get(tail, set()):
622                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
623                         print "raw"
624                         continue
625                     to_remove.add(aftertail)
626             if not to_remove:
627                 break
628             # if removed from this, it must be removed from verified
629             #start = time.time()
630             for aftertail in to_remove:
631                 if self.shares[aftertail].previous_hash not in self.tails:
632                     print "erk", aftertail, self.shares[aftertail].previous_hash
633                     continue
634                 self.remove(aftertail)
635                 if aftertail in self.verified.shares:
636                     self.verified.remove(aftertail)
637             #end = time.time()
638             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
639         
640         if best is not None:
641             best_share = self.shares[best]
642             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:
643                 if p2pool.DEBUG:
644                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
645                 best = best_share.previous_hash
646             
647             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
648             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
649         else:
650             timestamp_cutoff = int(time.time()) - 24*60*60
651             target_cutoff = 2**256-1
652         
653         if p2pool.DEBUG:
654             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))
655             for peer, hash, ts, targ in desired:
656                 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
657         
658         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
659     
660     def score(self, share_hash, block_rel_height_func):
661         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
662         
663         head_height = self.verified.get_height(share_hash)
664         if head_height < self.net.CHAIN_LENGTH:
665             return head_height, None
666         
667         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
668         
669         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
670             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
671         
672         return self.net.CHAIN_LENGTH, (self.verified.get_work(share_hash) - self.verified.get_work(end_point))//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
673
674 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
675     assert dist >= 2
676     near = tracker.shares[previous_share_hash]
677     far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
678     attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash) if not min_work else tracker.get_delta(near.hash).min_work - tracker.get_delta(far.hash).min_work
679     time = near.timestamp - far.timestamp
680     if time <= 0:
681         time = 1
682     if integer:
683         return attempts//time
684     return attempts/time
685
686 def get_average_stale_prop(tracker, share_hash, lookbehind):
687     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] != 0)
688     return stales/(lookbehind + stales)
689
690 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
691     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), False)
692     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
693     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
694     return res
695
696 def get_desired_version_counts(tracker, best_share_hash, dist):
697     res = {}
698     for share in tracker.get_chain(best_share_hash, dist):
699         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
700     return res
701
702 def format_hash(x):
703     if x is None:
704         return 'xxxxxxxx'
705     return '%08x' % (x % 2**32)
706
707 class ShareStore(object):
708     def __init__(self, prefix, net):
709         self.filename = prefix
710         self.dirname = os.path.dirname(os.path.abspath(prefix))
711         self.filename = os.path.basename(os.path.abspath(prefix))
712         self.net = net
713         self.known = None # will be filename -> set of share hashes, set of verified hashes
714         self.known_desired = None
715     
716     def get_shares(self):
717         if self.known is not None:
718             raise AssertionError()
719         known = {}
720         filenames, next = self.get_filenames_and_next()
721         for filename in filenames:
722             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
723             with open(filename, 'rb') as f:
724                 for line in f:
725                     try:
726                         type_id_str, data_hex = line.strip().split(' ')
727                         type_id = int(type_id_str)
728                         if type_id == 0:
729                             pass
730                         elif type_id == 1:
731                             pass
732                         elif type_id == 2:
733                             verified_hash = int(data_hex, 16)
734                             yield 'verified_hash', verified_hash
735                             verified_hashes.add(verified_hash)
736                         elif type_id == 5:
737                             raw_share = share_type.unpack(data_hex.decode('hex'))
738                             if raw_share['type'] in [0, 1]:
739                                 continue
740                             share = load_share(raw_share, self.net, None)
741                             yield 'share', share
742                             share_hashes.add(share.hash)
743                         else:
744                             raise NotImplementedError("share type %i" % (type_id,))
745                     except Exception:
746                         log.err(None, "Error while reading saved shares, continuing where left off:")
747         self.known = known
748         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
749     
750     def _add_line(self, line):
751         filenames, next = self.get_filenames_and_next()
752         if filenames and os.path.getsize(filenames[-1]) < 10e6:
753             filename = filenames[-1]
754         else:
755             filename = next
756         
757         with open(filename, 'ab') as f:
758             f.write(line + '\n')
759         
760         return filename
761     
762     def add_share(self, share):
763         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
764             if share.hash in share_hashes:
765                 break
766         else:
767             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
768             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
769             share_hashes.add(share.hash)
770         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
771         share_hashes.add(share.hash)
772     
773     def add_verified_hash(self, share_hash):
774         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
775             if share_hash in verified_hashes:
776                 break
777         else:
778             filename = self._add_line("%i %x" % (2, share_hash))
779             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
780             verified_hashes.add(share_hash)
781         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
782         verified_hashes.add(share_hash)
783     
784     def get_filenames_and_next(self):
785         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())
786         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)))
787     
788     def forget_share(self, share_hash):
789         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
790             if share_hash in share_hashes:
791                 share_hashes.remove(share_hash)
792         self.check_remove()
793     
794     def forget_verified_share(self, share_hash):
795         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
796             if share_hash in verified_hashes:
797                 verified_hashes.remove(share_hash)
798         self.check_remove()
799     
800     def check_remove(self):
801         to_remove = set()
802         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
803             #print filename, len(share_hashes) + len(verified_hashes)
804             if not share_hashes and not verified_hashes:
805                 to_remove.add(filename)
806         for filename in to_remove:
807             self.known.pop(filename)
808             self.known_desired.pop(filename)
809             os.remove(filename)
810             print "REMOVED", filename