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