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