Don't include transaction if it still too young
[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_addr):
43     assert peer_addr is None or isinstance(peer_addr, tuple)
44     if share['type'] < Share.VERSION:
45         from p2pool import p2p
46         raise p2p.PeerMisbehavingError('sent an obsolete share')
47     elif share['type'] == Share.VERSION:
48         return Share(net, peer_addr, Share.share_type.unpack(share['contents']))
49     else:
50         raise ValueError('unknown share type: %r' % (share['type'],))
51
52 DONATION_SCRIPT  = '41043b253cc0b5c8ce26f24b84bb955bec955cbb4643f19ab7ea073884f22874abdafc42040b97efec3c9eeb29ce69022a96cc1772f8bc805f78af0d3dc5c441db5fac'.decode('hex')
53
54 class Share(object):
55     VERSION = 13
56     VOTING_VERSION = 13
57     SUCCESSOR = None
58     
59     small_block_header_type = pack.ComposedType([
60         ('version', pack.VarIntType()),
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_info_type = pack.ComposedType([
68         ('share_data', pack.ComposedType([
69             ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
70             ('coinbase', pack.VarStrType()),
71             ('nonce', pack.IntType(32)),
72             ('pubkey_hash', pack.IntType(160)),
73             ('subsidy', pack.IntType(64)),
74             ('donation', pack.IntType(16)),
75             ('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)))),
76             ('desired_version', pack.VarIntType()),
77         ])),
78         ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
79         ('transaction_hash_refs', pack.ListType(pack.VarIntType(), 2)), # pairs of share_count, tx_count
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         ('absheight', pack.IntType(32)),
85         ('abswork', pack.IntType(128)),
86     ])
87     
88     share_type = pack.ComposedType([
89         ('min_header', small_block_header_type),
90         ('share_info', share_info_type),
91         ('ref_merkle_link', pack.ComposedType([
92             ('branch', pack.ListType(pack.IntType(256))),
93             ('index', pack.IntType(0)),
94         ])),
95         ('last_txout_nonce', pack.IntType(64)),
96         ('hash_link', hash_link_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     
103     ref_type = pack.ComposedType([
104         ('identifier', pack.FixedStrType(64//8)),
105         ('share_info', share_info_type),
106     ])
107     
108     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x6a\x28' + pack.IntType(256).pack(0) + pack.IntType(64).pack(0))[:3]
109     
110     @classmethod
111     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes_and_fees, net, known_txs=None, last_txout_nonce=0, base_subsidy=None):
112         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
113         
114         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
115         assert height >= net.REAL_CHAIN_LENGTH or last is None
116         if height < net.TARGET_LOOKBEHIND:
117             pre_target3 = net.MAX_TARGET
118         else:
119             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
120             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
121             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
122             pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
123         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
124         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//30, pre_target3)))
125         
126         new_transaction_hashes = []
127         new_transaction_size = 0
128         transaction_hash_refs = []
129         other_transaction_hashes = []
130         
131         past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100)))
132         tx_hash_to_this = {}
133         for i, share in enumerate(past_shares):
134             for j, tx_hash in enumerate(share.new_transaction_hashes):
135                 if tx_hash not in tx_hash_to_this:
136                     tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count
137         for tx_hash, fee in desired_other_transaction_hashes_and_fees:
138             if tx_hash in tx_hash_to_this:
139                 this = tx_hash_to_this[tx_hash]
140             else:
141                 if known_txs is not None:
142                     if known_txs[tx_hash]['timestamp'] > desired_timestamp - 30:
143                         continue
144                     this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
145                     if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
146                         break
147                     new_transaction_size += this_size
148                 new_transaction_hashes.append(tx_hash)
149                 this = [0, len(new_transaction_hashes)-1]
150             transaction_hash_refs.extend(this)
151             other_transaction_hashes.append(tx_hash)
152         
153         included_transactions = set(other_transaction_hashes)
154         removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions]
155         definite_fees = sum(0 if fee is None else fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash in included_transactions)
156         if None not in removed_fees:
157             share_data = dict(share_data, subsidy=share_data['subsidy'])
158         else:
159             assert base_subsidy is not None
160             share_data = dict(share_data, subsidy=base_subsidy)
161         
162         weights, total_weight, donation_weight = tracker.get_cumulative_weights(previous_share.share_data['previous_share_hash'] if previous_share is not None else None,
163             max(0, min(height, net.REAL_CHAIN_LENGTH) - 1),
164             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
165         )
166         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
167         
168         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
169         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
170         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
171         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
172         
173         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
174             raise ValueError()
175         
176         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
177         
178         share_info = dict(
179             share_data=share_data,
180             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
181             max_bits=max_bits,
182             bits=bits,
183             timestamp=math.clip(desired_timestamp, (
184                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
185                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
186             )) if previous_share is not None else desired_timestamp,
187             new_transaction_hashes=new_transaction_hashes,
188             transaction_hash_refs=transaction_hash_refs,
189             absheight=((previous_share.absheight if previous_share is not None else 0) + 1) % 2**32,
190             abswork=((previous_share.abswork if previous_share is not None else 0) + bitcoin_data.target_to_average_attempts(bits.target)) % 2**128,
191         )
192         
193         gentx = dict(
194             version=1,
195             # coinbase timestamp must be older than share/block timestamp
196             # maybe there are more elegant solution, but this hack works quite well for now
197             timestamp=share_info['timestamp'],
198             tx_ins=[dict(
199                 previous_output=None,
200                 sequence=None,
201                 script=share_data['coinbase'],
202             )],
203             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
204                 value=0,
205                 script='\x6a\x28' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(64).pack(last_txout_nonce),
206             )],
207             lock_time=0,
208         )
209         
210         def get_share(header, last_txout_nonce=last_txout_nonce):
211             min_header = dict(header); del min_header['merkle_root']
212             share = cls(net, None, dict(
213                 min_header=min_header,
214                 share_info=share_info,
215                 ref_merkle_link=dict(branch=[], index=0),
216                 last_txout_nonce=last_txout_nonce,
217                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-8-4], cls.gentx_before_refhash),
218                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
219             ))
220             assert share.header == header # checks merkle_root
221             return share
222         
223         return share_info, gentx, other_transaction_hashes, get_share
224     
225     @classmethod
226     def get_ref_hash(cls, net, share_info, ref_merkle_link):
227         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
228             identifier=net.IDENTIFIER,
229             share_info=share_info,
230         ))), ref_merkle_link))
231     
232     __slots__ = 'net peer_addr 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 absheight abswork'.split(' ')
233     
234     def __init__(self, net, peer_addr, contents):
235         self.net = net
236         self.peer_addr = peer_addr
237         self.contents = contents
238         
239         self.min_header = contents['min_header']
240         self.share_info = contents['share_info']
241         self.hash_link = contents['hash_link']
242         self.merkle_link = contents['merkle_link']
243         
244         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
245             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
246         
247         if len(self.merkle_link['branch']) > 16:
248             raise ValueError('merkle branch too long!')
249         
250         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
251         
252         self.share_data = self.share_info['share_data']
253         self.max_target = self.share_info['max_bits'].target
254         self.target = self.share_info['bits'].target
255         self.timestamp = self.share_info['timestamp']
256         self.previous_hash = self.share_data['previous_share_hash']
257         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
258         self.desired_version = self.share_data['desired_version']
259         self.absheight = self.share_info['absheight']
260         self.abswork = self.share_info['abswork']
261         
262         n = set()
263         for share_count, tx_count in self.iter_transaction_hash_refs():
264             assert share_count < 110
265             if share_count == 0:
266                 n.add(tx_count)
267         assert n == set(range(len(self.share_info['new_transaction_hashes'])))
268         
269         self.gentx_hash = check_hash_link(
270             self.hash_link,
271             self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(64).pack(self.contents['last_txout_nonce']) + pack.IntType(32).pack(0),
272             self.gentx_before_refhash,
273         )
274         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
275         self.header = dict(self.min_header, merkle_root=merkle_root)
276         self.pow_hash = self.hash = self.header_hash = bitcoin_data.scrypt(bitcoin_data.block_header_type.pack(self.header))
277         
278         if self.target > net.MAX_TARGET:
279             from p2pool import p2p
280             raise p2p.PeerMisbehavingError('share target invalid')
281         
282         if self.pow_hash > self.target:
283             from p2pool import p2p
284             raise p2p.PeerMisbehavingError('share PoW invalid')
285         
286         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
287         
288         # XXX eww
289         self.time_seen = time.time()
290     
291     def __repr__(self):
292         return 'Share' + repr((self.net, self.peer_addr, self.contents))
293     
294     def as_share(self):
295         return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
296     
297     def iter_transaction_hash_refs(self):
298         return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2])
299     
300     def check(self, tracker):
301         from p2pool import p2p
302         if self.share_data['previous_share_hash'] is not None:
303             previous_share = tracker.items[self.share_data['previous_share_hash']]
304             if type(self) is type(previous_share):
305                 pass
306             elif type(self) is type(previous_share).SUCCESSOR:
307                 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
308                     from p2pool import p2p
309                     raise p2p.PeerMisbehavingError('switch without enough history')
310                 
311                 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
312                 counts = get_desired_version_counts(tracker,
313                     tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
314                 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
315                     raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
316             else:
317                 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
318         
319         other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, share_count)].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
320         
321         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'], [(h, None) for h in other_tx_hashes], self.net, last_txout_nonce=self.contents['last_txout_nonce'])
322         assert other_tx_hashes2 == other_tx_hashes
323 # workaround
324         if share_info != self.share_info:
325             raise ValueError('share_info invalid')
326         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
327             raise ValueError('''gentx doesn't match hash_link''')
328         
329         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
330             raise ValueError('merkle_link and other_tx_hashes do not match')
331         
332         return gentx # only used by as_block
333     
334     def get_other_tx_hashes(self, tracker):
335         parents_needed = max(share_count for share_count, tx_count in self.iter_transaction_hash_refs()) if self.share_info['transaction_hash_refs'] else 0
336         parents = tracker.get_height(self.hash) - 1
337         if parents < parents_needed:
338             return None
339         last_shares = list(tracker.get_chain(self.hash, parents_needed + 1))
340         return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()]
341     
342     def _get_other_txs(self, tracker, known_txs):
343         other_tx_hashes = self.get_other_tx_hashes(tracker)
344         if other_tx_hashes is None:
345             return None # not all parents present
346         
347         if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
348             return None # not all txs present
349         
350         return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
351     
352     def should_punish_reason(self, previous_block, bits, tracker, known_txs):
353         if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None:
354             return True, 'Block-stale detected! height(%x) < height(%x) or %08x != %08x' % (self.header['previous_block'], previous_block, self.header['bits'].bits, bits.bits)
355         
356         if self.pow_hash <= self.header['bits'].target:
357             return -1, 'block solution'
358         
359         other_txs = self._get_other_txs(tracker, known_txs)
360         if other_txs is None:
361             pass
362         else:
363             all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
364             if all_txs_size > 1000000:
365                 return True, 'txs over block size limit'
366             
367             new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
368             if new_txs_size > 50000:
369                 return True, 'new txs over limit'
370         
371         return False, None
372     
373     def as_block(self, tracker, known_txs):
374         other_txs = self._get_other_txs(tracker, known_txs)
375         if other_txs is None:
376             return None # not all txs present
377         return dict(header=self.header, txs=[self.check(tracker)] + other_txs, signature='')
378
379
380 class WeightsSkipList(forest.TrackerSkipList):
381     # share_count, weights, total_weight
382     
383     def get_delta(self, element):
384         from p2pool.bitcoin import data as bitcoin_data
385         share = self.tracker.items[element]
386         att = bitcoin_data.target_to_average_attempts(share.target)
387         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
388     
389     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
390         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
391     
392     def initial_solution(self, start, (max_shares, desired_weight)):
393         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
394         return 0, None, 0, 0
395     
396     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)):
397         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
398             assert (desired_weight - total_weight1) % 65535 == 0
399             script, = weights2.iterkeys()
400             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
401             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)
402         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
403     
404     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
405         if share_count > max_shares or total_weight > desired_weight:
406             return 1
407         elif share_count == max_shares or total_weight == desired_weight:
408             return 0
409         else:
410             return -1
411     
412     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
413         assert share_count <= max_shares and total_weight <= desired_weight
414         assert share_count == max_shares or total_weight == desired_weight
415         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
416
417 class OkayTracker(forest.Tracker):
418     def __init__(self, net):
419         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
420             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
421             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
422         )))
423         self.net = net
424         self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
425             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
426         )), subset_of=self)
427         self.get_cumulative_weights = WeightsSkipList(self)
428     
429     def attempt_verify(self, share):
430         if share.hash in self.verified.items:
431             return True
432         height, last = self.get_height_and_last(share.hash)
433         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
434             raise AssertionError()
435         try:
436             share.check(self)
437         except:
438             log.err(None, 'Share check failed: %064x -> %064x' % (share.hash, share.previous_hash if share.previous_hash is not None else 0))
439             return False
440         else:
441             self.verified.add(share)
442             return True
443     
444     def think(self, block_rel_height_func, previous_block, bits, known_txs):
445         desired = set()
446         bad_peer_addresses = set()
447         
448         # O(len(self.heads))
449         #   make 'unverified heads' set?
450         # for each overall head, attempt verification
451         # if it fails, attempt on parent, and repeat
452         # if no successful verification because of lack of parents, request parent
453         bads = []
454         for head in set(self.heads) - set(self.verified.heads):
455             head_height, last = self.get_height_and_last(head)
456             
457             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
458                 if self.attempt_verify(share):
459                     break
460                 bads.append(share.hash)
461             else:
462                 if last is not None:
463                     desired.add((
464                         self.items[random.choice(list(self.reverse[last]))].peer_addr,
465                         last,
466                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
467                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
468                     ))
469         for bad in bads:
470             assert bad not in self.verified.items
471             #assert bad in self.heads
472             bad_share = self.items[bad]
473             if bad_share.peer_addr is not None:
474                 bad_peer_addresses.add(bad_share.peer_addr)
475             if p2pool.DEBUG:
476                 print "BAD", bad
477             try:
478                 self.remove(bad)
479             except NotImplementedError:
480                 pass
481         
482         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
483         for head in list(self.verified.heads):
484             head_height, last_hash = self.verified.get_height_and_last(head)
485             last_height, last_last_hash = self.get_height_and_last(last_hash)
486             # XXX review boundary conditions
487             want = max(self.net.CHAIN_LENGTH - head_height, 0)
488             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
489             get = min(want, can)
490             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
491             for share in self.get_chain(last_hash, get):
492                 if not self.attempt_verify(share):
493                     break
494             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
495                 desired.add((
496                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer_addr,
497                     last_last_hash,
498                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
499                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
500                 ))
501         
502         # decide best tree
503         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)
504         if p2pool.DEBUG:
505             print len(decorated_tails), 'tails:'
506             for score, tail_hash in decorated_tails:
507                 print format_hash(tail_hash), score
508         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
509         
510         # decide best verified head
511         decorated_heads = sorted(((
512             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
513             #self.items[h].peer_addr is None,
514             -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
515             -self.items[h].time_seen,
516         ), h) for h in self.verified.tails.get(best_tail, []))
517         if p2pool.DEBUG:
518             print len(decorated_heads), 'heads. Top 10:'
519             for score, head_hash in decorated_heads[-10:]:
520                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
521         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
522         
523         if best is not None:
524             best_share = self.items[best]
525             punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
526             if punish > 0:
527                 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
528                 best = best_share.previous_hash
529             
530             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
531             target_cutoff = int(2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 + .5) if best_tail_score[1] is not None else 2**256-1
532         else:
533             timestamp_cutoff = int(time.time()) - 24*60*60
534             target_cutoff = 2**256-1
535         
536         if p2pool.DEBUG:
537             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))
538             for peer_addr, hash, ts, targ in desired:
539                 print '   ', None if peer_addr is None else '%s:%i' % peer_addr, format_hash(hash), math.format_dt(time.time() - ts), bitcoin_data.target_to_difficulty(targ), ts >= timestamp_cutoff, targ <= target_cutoff
540         
541         return best, [(peer_addr, hash) for peer_addr, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads, bad_peer_addresses
542     
543     def score(self, share_hash, block_rel_height_func):
544         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
545         
546         head_height = self.verified.get_height(share_hash)
547         if head_height < self.net.CHAIN_LENGTH:
548             return head_height, None
549         
550         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
551         
552         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
553             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
554         
555         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work/((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
556
557 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
558     assert dist >= 2
559     near = tracker.items[previous_share_hash]
560     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
561     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
562     time = near.timestamp - far.timestamp
563     if time <= 0:
564         time = 1
565     if integer:
566         return attempts//time
567     return attempts/time
568
569 def get_average_stale_prop(tracker, share_hash, lookbehind):
570     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
571     return stales/(lookbehind + stales)
572
573 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
574     res = {}
575     for share in tracker.get_chain(share_hash, lookbehind - 1):
576         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
577         s = share.share_data['stale_info']
578         if s is not None:
579             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
580     if rates:
581         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
582         res = dict((k, v/dt) for k, v in res.iteritems())
583     return res
584
585 def get_user_stale_props(tracker, share_hash, lookbehind):
586     res = {}
587     for share in tracker.get_chain(share_hash, lookbehind - 1):
588         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
589         total += 1
590         if share.share_data['stale_info'] is not None:
591             stale += 1
592             total += 1
593         res[share.share_data['pubkey_hash']] = stale, total
594     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
595
596 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
597     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))
598     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
599     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
600     return res
601
602 def get_desired_version_counts(tracker, best_share_hash, dist):
603     res = {}
604     for share in tracker.get_chain(best_share_hash, dist):
605         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
606     return res
607
608 def get_warnings(tracker, best_share, net, bitcoind_getinfo, bitcoind_work_value):
609     res = []
610     
611     desired_version_counts = get_desired_version_counts(tracker, best_share,
612         min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
613     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
614     if majority_desired_version > (Share.SUCCESSOR if Share.SUCCESSOR is not None else Share).VOTING_VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
615         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
616             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
617                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
618     
619     if bitcoind_getinfo['errors'] != '':
620         if 'This is a pre-release test build' not in bitcoind_getinfo['errors']:
621             res.append('(from bitcoind) %s' % (bitcoind_getinfo['errors'],))
622     
623     version_warning = getattr(net, 'VERSION_WARNING', lambda v: None)(bitcoind_getinfo['version'])
624     if version_warning is not None:
625         res.append(version_warning)
626     
627     if time.time() > bitcoind_work_value['last_update'] + 60:
628         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']),))
629     
630     return res
631
632 def format_hash(x):
633     if x is None:
634         return 'xxxxxxxx'
635     return '%08x' % (x % 2**32)
636
637 class ShareStore(object):
638     def __init__(self, prefix, net, share_cb, verified_hash_cb):
639         self.dirname = os.path.dirname(os.path.abspath(prefix))
640         self.filename = os.path.basename(os.path.abspath(prefix))
641         self.net = net
642         
643         known = {}
644         filenames, next = self.get_filenames_and_next()
645         for filename in filenames:
646             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
647             with open(filename, 'rb') as f:
648                 for line in f:
649                     try:
650                         type_id_str, data_hex = line.strip().split(' ')
651                         type_id = int(type_id_str)
652                         if type_id == 0:
653                             pass
654                         elif type_id == 1:
655                             pass
656                         elif type_id == 2:
657                             verified_hash = int(data_hex, 16)
658                             verified_hash_cb(verified_hash)
659                             verified_hashes.add(verified_hash)
660                         elif type_id == 5:
661                             raw_share = share_type.unpack(data_hex.decode('hex'))
662                             if raw_share['type'] < Share.VERSION:
663                                 continue
664                             share = load_share(raw_share, self.net, None)
665                             share_cb(share)
666                             share_hashes.add(share.hash)
667                         else:
668                             raise NotImplementedError("share type %i" % (type_id,))
669                     except Exception:
670                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
671         
672         self.known = known # filename -> (set of share hashes, set of verified hashes)
673         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
674     
675     def _add_line(self, line):
676         filenames, next = self.get_filenames_and_next()
677         if filenames and os.path.getsize(filenames[-1]) < 10e6:
678             filename = filenames[-1]
679         else:
680             filename = next
681         
682         with open(filename, 'ab') as f:
683             f.write(line + '\n')
684         
685         return filename
686     
687     def add_share(self, share):
688         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
689             if share.hash in share_hashes:
690                 break
691         else:
692             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
693             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
694             share_hashes.add(share.hash)
695         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
696         share_hashes.add(share.hash)
697     
698     def add_verified_hash(self, share_hash):
699         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
700             if share_hash in verified_hashes:
701                 break
702         else:
703             filename = self._add_line("%i %x" % (2, share_hash))
704             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
705             verified_hashes.add(share_hash)
706         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
707         verified_hashes.add(share_hash)
708     
709     def get_filenames_and_next(self):
710         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())
711         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)))
712     
713     def forget_share(self, share_hash):
714         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
715             if share_hash in share_hashes:
716                 share_hashes.remove(share_hash)
717         self.check_remove()
718     
719     def forget_verified_share(self, share_hash):
720         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
721             if share_hash in verified_hashes:
722                 verified_hashes.remove(share_hash)
723         self.check_remove()
724     
725     def check_remove(self):
726         to_remove = set()
727         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
728             #print filename, len(share_hashes) + len(verified_hashes)
729             if not share_hashes and not verified_hashes:
730                 to_remove.add(filename)
731         for filename in to_remove:
732             self.known.pop(filename)
733             self.known_desired.pop(filename)
734             os.remove(filename)
735             print "REMOVED", filename