fix bug introduced with using relative block heights
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import itertools
4 import random
5 import time
6 import os
7
8 from twisted.python import log
9
10 import p2pool
11 from p2pool import skiplists
12 from p2pool.bitcoin import data as bitcoin_data, script
13 from p2pool.util import memoize, expiring_dict, math, forest
14
15
16 share_data_type = bitcoin_data.ComposedType([
17     ('previous_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
18     ('coinbase', bitcoin_data.VarStrType()),
19     ('nonce', bitcoin_data.VarStrType()),
20     ('new_script', bitcoin_data.VarStrType()),
21     ('subsidy', bitcoin_data.StructType('<Q')),
22     ('donation', bitcoin_data.StructType('<H')),
23     ('stale_frac', bitcoin_data.StructType('<B')),
24 ])
25
26 share_info_type = bitcoin_data.ComposedType([
27     ('share_data', share_data_type),
28     ('target', bitcoin_data.FloatingIntegerType()),
29     ('timestamp', bitcoin_data.StructType('<I')),
30 ])
31
32 share1a_type = bitcoin_data.ComposedType([
33     ('header', bitcoin_data.block_header_type),
34     ('share_info', share_info_type),
35     ('merkle_branch', bitcoin_data.merkle_branch_type),
36 ])
37
38 share1b_type = bitcoin_data.ComposedType([
39     ('header', bitcoin_data.block_header_type),
40     ('share_info', share_info_type),
41     ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
42 ])
43
44 # type:
45 # 0: share1a
46 # 1: share1b
47
48 share_type = bitcoin_data.ComposedType([
49     ('type', bitcoin_data.VarIntType()),
50     ('contents', bitcoin_data.VarStrType()),
51 ])
52
53 class Share(object):
54     __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce pow_hash header_hash hash time_seen peer donation stale_frac net'.split(' ')
55     
56     @classmethod
57     def from_share(cls, share, net):
58         if share['type'] == 0:
59             res = cls.from_share1a(share1a_type.unpack(share['contents']), net)
60             if not (res.pow_hash > res.header['target']):
61                 raise ValueError('invalid share type')
62             return res
63         elif share['type'] == 1:
64             res = cls.from_share1b(share1b_type.unpack(share['contents']), net)
65             if not (res.pow_hash <= res.header['target']):
66                 raise ValueError('invalid share type')
67             return res
68         else:
69             raise ValueError('unknown share type: %r' % (share['type'],))
70     
71     @classmethod
72     def from_share1a(cls, share1a, net):
73         return cls(net, **share1a)
74     
75     @classmethod
76     def from_share1b(cls, share1b, net):
77         return cls(net, **share1b)
78     
79     def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
80         self.net = net
81         
82         if merkle_branch is None and other_txs is None:
83             raise ValueError('need either merkle_branch or other_txs')
84         if other_txs is not None:
85             new_merkle_branch = bitcoin_data.calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
86             if merkle_branch is not None:
87                 if merke_branch != new_merkle_branch:
88                     raise ValueError('invalid merkle_branch and other_txs')
89             merkle_branch = new_merkle_branch
90         
91         if len(merkle_branch) > 16:
92             raise ValueError('merkle_branch too long!')
93         
94         self.header = header
95         self.previous_block = header['previous_block']
96         self.share_info = share_info
97         self.merkle_branch = merkle_branch
98         
99         self.share_data = self.share_info['share_data']
100         self.target = self.share_info['target']
101         self.timestamp = self.share_info['timestamp']
102         
103         self.new_script = self.share_data['new_script']
104         self.subsidy = self.share_data['subsidy']
105         self.donation = self.share_data['donation']
106         
107         if len(self.new_script) > 100:
108             raise ValueError('new_script too long!')
109         
110         self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
111         self.nonce = self.share_data['nonce']
112         
113         if len(self.nonce) > 100:
114             raise ValueError('nonce too long!')
115         
116         if len(self.share_data['coinbase']) > 100:
117             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
118         
119         self.pow_hash = net.BITCOIN_POW_FUNC(header)
120         self.header_hash = bitcoin_data.block_header_type.hash256(header)
121         
122         self.hash = share1a_type.hash256(self.as_share1a())
123         
124         if self.pow_hash > self.target:
125             print 'hash %x' % self.pow_hash
126             print 'targ %x' % self.target
127             raise ValueError('not enough work!')
128         
129         self.stale_frac = self.share_data['stale_frac']/254 if self.share_data['stale_frac'] != 255 else None
130         
131         self.other_txs = other_txs if self.pow_hash <= self.header['target'] else None
132         
133         # XXX eww
134         self.time_seen = time.time()
135         self.peer = None
136     
137     def __repr__(self):
138         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
139     
140     def check(self, tracker):
141         if script.get_sigop_count(self.new_script) > 1:
142             raise ValueError('too many sigops!')
143         
144         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['target'], self.share_info['timestamp'], self.net)
145         if share_info != self.share_info:
146             raise ValueError('share difficulty invalid')
147         
148         if bitcoin_data.check_merkle_branch(gentx, 0, self.merkle_branch) != self.header['merkle_root']:
149             raise ValueError('''gentx doesn't match header via merkle_branch''')
150     
151     def as_share(self):
152         if self.pow_hash > self.header['target']: # share1a
153             return dict(type=0, contents=share1a_type.pack(self.as_share1a()))
154         elif self.pow_hash <= self.header['target']: # share1b
155             return dict(type=1, contents=share1b_type.pack(self.as_share1b()))
156         else:
157             raise AssertionError()
158     
159     def as_share1a(self):
160         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
161     
162     def as_share1b(self):
163         if self.other_txs is None:
164             raise ValueError('share does not contain all txs')
165         
166         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
167     
168     def as_block(self, tracker):
169         if self.other_txs is None:
170             raise ValueError('share does not contain all txs')
171         
172         share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['target'], self.share_info['timestamp'], self.net)
173         assert share_info == self.share_info
174         
175         return dict(header=self.header, txs=[gentx] + self.other_txs)
176
177 def get_pool_attempts_per_second(tracker, previous_share_hash, dist):
178     near = tracker.shares[previous_share_hash]
179     far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
180     attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash)
181     time = near.timestamp - far.timestamp
182     if time == 0:
183         time = 1
184     return attempts//time
185
186 def generate_transaction(tracker, share_data, block_target, desired_timestamp, net):
187     previous_share_hash = share_data['previous_share_hash']
188     new_script = share_data['new_script']
189     subsidy = share_data['subsidy']
190     donation = share_data['donation']
191     assert 0 <= donation <= 65535
192     
193     if len(share_data['coinbase']) > 100:
194         raise ValueError('coinbase too long!')
195     
196     previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
197     
198     chain_length = getattr(net, 'REAL_CHAIN_LENGTH_FUNC', lambda _: net.REAL_CHAIN_LENGTH)(previous_share.timestamp if previous_share is not None else None)
199     
200     height, last = tracker.get_height_and_last(previous_share_hash)
201     assert height >= chain_length or last is None
202     if height < net.TARGET_LOOKBEHIND:
203         target = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
204     else:
205         attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net.TARGET_LOOKBEHIND)
206         pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
207         pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
208         pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
209         target = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
210     
211     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
212     max_att = net.SPREAD * attempts_to_block
213     
214     this_att = min(bitcoin_data.target_to_average_attempts(target), max_att)
215     other_weights, other_total_weight, other_donation_weight = tracker.get_cumulative_weights(previous_share_hash, min(height, chain_length), 65535*max(0, max_att - this_att))
216     assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
217     weights, total_weight, donation_weight = math.add_dicts([{new_script: this_att*(65535-donation)}, other_weights]), this_att*65535 + other_total_weight, this_att*donation + other_donation_weight
218     assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
219     
220     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
221     
222     # 1 satoshi is always donated so that a list of p2pool generated blocks can be easily found by looking at the donation address
223     amounts = dict((script, (subsidy-1)*(199*weight)//(200*total_weight)) for (script, weight) in weights.iteritems())
224     amounts[new_script] = amounts.get(new_script, 0) + (subsidy-1)//200
225     amounts[SCRIPT] = amounts.get(SCRIPT, 0) + (subsidy-1)*(199*donation_weight)//(200*total_weight)
226     amounts[SCRIPT] = amounts.get(SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra satoshis :P
227     
228     if sum(amounts.itervalues()) != subsidy:
229         raise ValueError()
230     if any(x < 0 for x in amounts.itervalues()):
231         raise ValueError()
232     
233     dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
234     dests = dests[-4000:] # block length limit, unlikely to ever be hit
235     
236     share_info = dict(
237         share_data=share_data,
238         target=target,
239         timestamp=math.clip(desired_timestamp, (previous_share.timestamp - 60, previous_share.timestamp + 60)) if previous_share is not None else desired_timestamp,
240     )
241     
242     return share_info, dict(
243         version=1,
244         tx_ins=[dict(
245             previous_output=None,
246             sequence=None,
247             script=share_data['coinbase'].ljust(2, '\x00'),
248         )],
249         tx_outs=[dict(value=0, script='\x20' + bitcoin_data.HashType().pack(share_info_type.hash256(share_info)))] + [dict(value=amounts[script], script=script) for script in dests if amounts[script]],
250         lock_time=0,
251     )
252
253
254 class OkayTracker(forest.Tracker):
255     def __init__(self, net):
256         forest.Tracker.__init__(self)
257         self.net = net
258         self.verified = forest.Tracker()
259         self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
260         
261         self.get_cumulative_weights = skiplists.WeightsSkipList(self)
262     
263     def attempt_verify(self, share, now):
264         if share.hash in self.verified.shares:
265             return True
266         height, last = self.get_height_and_last(share.hash)
267         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
268             raise AssertionError()
269         try:
270             share.check(self)
271         except:
272             log.err(None, 'Share check failed:')
273             return False
274         else:
275             self.verified.add(share)
276             return True
277     
278     def think(self, ht, previous_block, now):
279         desired = set()
280         
281         # O(len(self.heads))
282         #   make 'unverified heads' set?
283         # for each overall head, attempt verification
284         # if it fails, attempt on parent, and repeat
285         # if no successful verification because of lack of parents, request parent
286         bads = set()
287         for head in set(self.heads) - set(self.verified.heads):
288             head_height, last = self.get_height_and_last(head)
289             
290             for share in itertools.islice(self.get_chain_known(head), None if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
291                 if self.attempt_verify(share, now):
292                     break
293                 if share.hash in self.heads:
294                     bads.add(share.hash)
295             else:
296                 if last is not None:
297                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
298         for bad in bads:
299             assert bad not in self.verified.shares
300             assert bad in self.heads
301             if p2pool.DEBUG:
302                 print "BAD", bad
303             self.remove(bad)
304         
305         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
306         for head in list(self.verified.heads):
307             head_height, last_hash = self.verified.get_height_and_last(head)
308             last_height, last_last_hash = self.get_height_and_last(last_hash)
309             # XXX review boundary conditions
310             want = max(self.net.CHAIN_LENGTH - head_height, 0)
311             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
312             get = min(want, can)
313             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
314             for share in itertools.islice(self.get_chain_known(last_hash), get):
315                 if not self.attempt_verify(share, now):
316                     break
317             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
318                 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
319         if p2pool.DEBUG:
320             print len(self.verified.tails), "tails:"
321             for x in self.verified.tails:
322                 print format_hash(x), self.score(max(self.verified.tails[x], key=self.verified.get_height), ht)
323         
324         # decide best tree
325         best_tail = max(self.verified.tails, key=lambda h: self.score(max(self.verified.tails[h], key=self.verified.get_height), ht)) if self.verified.tails else None
326         # decide best verified head
327         scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
328             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
329             #self.verified.shares[h].peer is None,
330             ht.get_height_rel_highest(self.verified.shares[h].previous_block),
331             -self.verified.shares[h].time_seen
332         ))
333         
334         
335         if p2pool.DEBUG:
336             print len(self.verified.tails), "chain tails and", len(self.verified.tails.get(best_tail, [])), 'chain heads. Top 10 heads:'
337             if len(scores) > 10:
338                 print '    ...'
339             for h in scores[-10:]:
340                 print '   ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
341                     self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
342                     self.verified.shares[h].peer is None,
343                     ht.get_height_rel_highest(self.verified.shares[h].previous_block),
344                     -self.verified.shares[h].time_seen
345                 )
346         
347         # eat away at heads
348         if scores:
349             for i in xrange(1000):
350                 to_remove = set()
351                 for share_hash, tail in self.heads.iteritems():
352                     if share_hash in scores[-5:]:
353                         #print 1
354                         continue
355                     if self.shares[share_hash].time_seen > time.time() - 300:
356                         #print 2
357                         continue
358                     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
359                         #print 3
360                         continue
361                     to_remove.add(share_hash)
362                 if not to_remove:
363                     break
364                 for share_hash in to_remove:
365                     self.remove(share_hash)
366                     if share_hash in self.verified.shares:
367                         self.verified.remove(share_hash)
368                 #print "_________", to_remove
369         
370         # drop tails
371         for i in xrange(1000):
372             to_remove = set()
373             for tail, heads in self.tails.iteritems():
374                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
375                     continue
376                 for aftertail in self.reverse_shares.get(tail, set()):
377                     if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
378                         print "raw"
379                         continue
380                     to_remove.add(aftertail)
381             if not to_remove:
382                 break
383             # if removed from this, it must be removed from verified
384             #start = time.time()
385             for aftertail in to_remove:
386                 if self.shares[aftertail].previous_hash not in self.tails:
387                     print "erk", aftertail, self.shares[aftertail].previous_hash
388                     continue
389                 self.remove(aftertail)
390                 if aftertail in self.verified.shares:
391                     self.verified.remove(aftertail)
392             #end = time.time()
393             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
394         
395         best = scores[-1] if scores else None
396         
397         if best is not None:
398             best_share = self.verified.shares[best]
399             if ht.get_height_rel_highest(best_share.header['previous_block']) < ht.get_height_rel_highest(previous_block) and best_share.header_hash != previous_block and best_share.peer is not None:
400                 if p2pool.DEBUG:
401                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
402                 best = best_share.previous_hash
403         
404         return best, desired
405     
406     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
407     def score(self, share_hash, ht):
408         head_height, last = self.verified.get_height_and_last(share_hash)
409         score2 = 0
410         block_height = -1000000
411         max_height = min(self.net.CHAIN_LENGTH, head_height)
412         for share in reversed(list(itertools.islice(self.verified.get_chain_known(self.verified.get_nth_parent_hash(share_hash, max_height//2)), max_height//2))):
413             block_height = max(block_height, ht.get_height_rel_highest(share.header['previous_block']))
414             this_score = (self.verified.get_work(share_hash) - self.verified.get_work(share.hash))//(0 - block_height + 1)
415             if this_score > score2:
416                 score2 = this_score
417         return min(head_height, self.net.CHAIN_LENGTH), score2
418
419 def format_hash(x):
420     if x is None:
421         return 'xxxxxxxx'
422     return '%08x' % (x % 2**32)
423
424 class ShareStore(object):
425     def __init__(self, prefix, net):
426         self.filename = prefix
427         self.dirname = os.path.dirname(os.path.abspath(prefix))
428         self.filename = os.path.basename(os.path.abspath(prefix))
429         self.net = net
430         self.known = None # will be filename -> set of share hashes, set of verified hashes
431         self.known_desired = None
432     
433     def get_shares(self):
434         if self.known is not None:
435             raise AssertionError()
436         known = {}
437         filenames, next = self.get_filenames_and_next()
438         for filename in filenames:
439             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
440             with open(filename, 'rb') as f:
441                 for line in f:
442                     try:
443                         type_id_str, data_hex = line.strip().split(' ')
444                         type_id = int(type_id_str)
445                         if type_id == 0:
446                             pass
447                         elif type_id == 1:
448                             pass
449                         elif type_id == 2:
450                             verified_hash = int(data_hex, 16)
451                             yield 'verified_hash', verified_hash
452                             verified_hashes.add(verified_hash)
453                         elif type_id == 5:
454                             share = Share.from_share(share_type.unpack(data_hex.decode('hex')), self.net)
455                             yield 'share', share
456                             share_hashes.add(share.hash)
457                         else:
458                             raise NotImplementedError("share type %i" % (type_id,))
459                     except Exception:
460                         log.err(None, "Error while reading saved shares, continuing where left off:")
461         self.known = known
462         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
463     
464     def _add_line(self, line):
465         filenames, next = self.get_filenames_and_next()
466         if filenames and os.path.getsize(filenames[-1]) < 10e6:
467             filename = filenames[-1]
468         else:
469             filename = next
470         
471         with open(filename, 'ab') as f:
472             f.write(line + '\n')
473         
474         return filename
475     
476     def add_share(self, share):
477         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
478             if share.hash in share_hashes:
479                 break
480         else:
481             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
482             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
483             share_hashes.add(share.hash)
484         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
485         share_hashes.add(share.hash)
486     
487     def add_verified_hash(self, share_hash):
488         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
489             if share_hash in verified_hashes:
490                 break
491         else:
492             filename = self._add_line("%i %x" % (2, share_hash))
493             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
494             verified_hashes.add(share_hash)
495         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
496         verified_hashes.add(share_hash)
497     
498     def get_filenames_and_next(self):
499         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())
500         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)))
501     
502     def forget_share(self, share_hash):
503         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
504             if share_hash in share_hashes:
505                 share_hashes.remove(share_hash)
506         self.check_remove()
507     
508     def forget_verified_share(self, share_hash):
509         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
510             if share_hash in verified_hashes:
511                 verified_hashes.remove(share_hash)
512         self.check_remove()
513     
514     def check_remove(self):
515         to_remove = set()
516         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
517             #print filename, len(share_hashes) + len(verified_hashes)
518             if not share_hashes and not verified_hashes:
519                 to_remove.add(filename)
520         for filename in to_remove:
521             self.known.pop(filename)
522             self.known_desired.pop(filename)
523             os.remove(filename)
524             print "REMOVED", filename