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