1 from __future__ import division
8 from twisted.python import log
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
16 new_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')),
26 new_share_info_type = bitcoin_data.ComposedType([
27 ('new_share_data', new_share_data_type),
28 ('target', bitcoin_data.FloatingIntegerType()),
29 ('timestamp', bitcoin_data.StructType('<I')),
32 new_share1a_type = bitcoin_data.ComposedType([
33 ('header', bitcoin_data.block_header_type),
34 ('share_info', new_share_info_type),
35 ('merkle_branch', bitcoin_data.merkle_branch_type),
38 new_share1b_type = bitcoin_data.ComposedType([
39 ('header', bitcoin_data.block_header_type),
40 ('share_info', new_share_info_type),
41 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
48 new_share_type = bitcoin_data.ComposedType([
49 ('type', bitcoin_data.VarIntType()),
50 ('contents', bitcoin_data.VarStrType()),
53 class NewShare(object):
55 def from_share1a(cls, share1a, net):
56 return cls(net, **share1a)
59 def from_share1b(cls, share1b, net):
60 return cls(net, **share1b)
63 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
66 if self.other_txs is None:
67 raise ValueError('share does not contain all txs')
69 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
72 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
74 __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 def from_share(cls, share, net):
78 if share['type'] == 0:
79 res = cls.from_share1a(new_share1a_type.unpack(share['contents']), net)
80 if not (res.pow_hash > res.header['target']):
81 raise ValueError('invalid share type')
83 elif share['type'] == 1:
84 res = cls.from_share1b(new_share1b_type.unpack(share['contents']), net)
85 if not (res.pow_hash <= res.header['target']):
86 raise ValueError('invalid share type')
89 raise ValueError('unknown share type: %r' % (share['type'],))
92 if self.pow_hash > self.header['target']: # new_share1a
93 return dict(type=0, contents=new_share1a_type.pack(self.as_share1a()))
94 elif self.pow_hash <= self.header['target']: # new_share1b
95 return dict(type=1, contents=new_share1b_type.pack(self.as_share1b()))
97 raise AssertionError()
99 def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
100 if merkle_branch is None and other_txs is None:
101 raise ValueError('need either merkle_branch or other_txs')
102 if other_txs is not None:
103 new_merkle_branch = bitcoin_data.calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
104 if merkle_branch is not None:
105 if merke_branch != new_merkle_branch:
106 raise ValueError('invalid merkle_branch and other_txs')
107 merkle_branch = new_merkle_branch
109 if len(merkle_branch) > 16:
110 raise ValueError('merkle_branch too long!')
113 self.previous_block = header['previous_block']
114 self.share_info = share_info
115 self.merkle_branch = merkle_branch
116 self.other_txs = other_txs
118 self.share_data = self.share_info['new_share_data']
119 self.target = self.share_info['target']
120 self.timestamp = self.share_info['timestamp']
122 self.new_script = self.share_data['new_script']
123 self.subsidy = self.share_data['subsidy']
124 self.donation = self.share_data['donation']
126 if len(self.new_script) > 100:
127 raise ValueError('new_script too long!')
129 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
130 self.nonce = self.share_data['nonce']
132 if len(self.nonce) > 100:
133 raise ValueError('nonce too long!')
135 if len(self.share_data['coinbase']) > 100:
136 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
138 self.pow_hash = net.BITCOIN_POW_FUNC(header)
139 self.header_hash = bitcoin_data.block_header_type.hash256(header)
141 self.hash = new_share1a_type.hash256(self.as_share1a())
143 if self.pow_hash > self.target:
144 print 'hash %x' % self.pow_hash
145 print 'targ %x' % self.target
146 raise ValueError('not enough work!')
148 if script.get_sigop_count(self.new_script) > 1:
149 raise ValueError('too many sigops!')
151 self.stale_frac = self.share_data['stale_frac']/254 if self.share_data['stale_frac'] != 255 else None
154 self.time_seen = time.time()
157 def check(self, tracker, now, net):
158 share_info, gentx = new_generate_transaction(tracker, self.share_info['new_share_data'], self.header['target'], self.share_info['timestamp'], net)
159 if share_info != self.share_info:
160 raise ValueError('share difficulty invalid')
162 if bitcoin_data.check_merkle_branch(gentx, 0, self.merkle_branch) != self.header['merkle_root']:
163 raise ValueError('''gentx doesn't match header via merkle_branch''')
165 def as_block(self, tracker, net):
166 if self.other_txs is None:
167 raise ValueError('share does not contain all txs')
169 share_info, gentx = new_generate_transaction(tracker, self.share_info['new_share_data'], self.header['target'], self.share_info['timestamp'], net)
170 assert share_info == self.share_info
172 return dict(header=self.header, txs=[gentx] + self.other_txs)
174 def get_pool_attempts_per_second(tracker, previous_share_hash, net, dist=None):
176 dist = net.TARGET_LOOKBEHIND
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
183 return attempts//time
185 def new_generate_transaction(tracker, new_share_data, block_target, desired_timestamp, net):
186 previous_share_hash = new_share_data['previous_share_hash']
187 new_script = new_share_data['new_script']
188 subsidy = new_share_data['subsidy']
189 donation = new_share_data['donation']
190 assert 0 <= donation <= 65535
192 if len(new_share_data['coinbase']) > 100:
193 raise ValueError('coinbase too long!')
195 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
197 height, last = tracker.get_height_and_last(previous_share_hash)
198 assert height >= net.CHAIN_LENGTH or last is None
199 if height < net.TARGET_LOOKBEHIND:
200 target = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
202 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
203 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
204 pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
205 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
206 target = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
208 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
209 max_att = net.SPREAD * attempts_to_block
211 this_att = min(bitcoin_data.target_to_average_attempts(target), max_att)
212 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))
213 assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
214 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
215 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
217 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
219 # 1 satoshi is always donated so that a list of p2pool generated blocks can be easily found by looking at the donation address
220 amounts = dict((script, (subsidy-1)*(199*weight)//(200*total_weight)) for (script, weight) in weights.iteritems())
221 amounts[new_script] = amounts.get(new_script, 0) + (subsidy-1)//200
222 amounts[SCRIPT] = amounts.get(SCRIPT, 0) + (subsidy-1)*(199*donation_weight)//(200*total_weight)
223 amounts[SCRIPT] = amounts.get(SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra satoshis :P
225 if sum(amounts.itervalues()) != subsidy:
227 if any(x < 0 for x in amounts.itervalues()):
230 dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
231 dests = dests[-4000:] # block length limit, unlikely to ever be hit
234 new_share_data=new_share_data,
236 timestamp=math.clip(desired_timestamp, (previous_share.timestamp - 60, previous_share.timestamp + 60)) if previous_share is not None else desired_timestamp,
239 return share_info, dict(
242 previous_output=None,
244 script=new_share_data['coinbase'].ljust(2, '\x00'),
246 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]],
251 class OkayTracker(forest.Tracker):
252 def __init__(self, net):
253 forest.Tracker.__init__(self)
255 self.verified = forest.Tracker()
256 self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
258 self.get_cumulative_weights = skiplists.WeightsSkipList(self)
260 def add(self, share, known_verified=False):
261 forest.Tracker.add(self, share)
263 self.verified.add(share)
265 def attempt_verify(self, share, now):
266 if share.hash in self.verified.shares:
268 height, last = self.get_height_and_last(share.hash)
269 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
270 raise AssertionError()
272 share.check(self, now, self.net)
274 log.err(None, 'Share check failed:')
277 self.verified.add(share)
280 def think(self, ht, previous_block, now):
284 # make 'unverified heads' set?
285 # for each overall head, attempt verification
286 # if it fails, attempt on parent, and repeat
287 # if no successful verification because of lack of parents, request parent
289 for head in set(self.heads) - set(self.verified.heads):
290 head_height, last = self.get_height_and_last(head)
292 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))):
293 if self.attempt_verify(share, now):
295 if share.hash in self.heads:
299 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
301 assert bad not in self.verified.shares
302 assert bad in self.heads
307 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
308 for head in list(self.verified.heads):
309 head_height, last_hash = self.verified.get_height_and_last(head)
310 last_height, last_last_hash = self.get_height_and_last(last_hash)
311 # XXX review boundary conditions
312 want = max(self.net.CHAIN_LENGTH - head_height, 0)
313 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
315 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
316 for share in itertools.islice(self.get_chain_known(last_hash), get):
317 if not self.attempt_verify(share, now):
319 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
320 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
323 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
324 # decide best verified head
325 scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
326 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
327 #self.verified.shares[h].peer is None,
328 ht.get_min_height(self.verified.shares[h].previous_block),
329 -self.verified.shares[h].time_seen
334 print len(self.verified.tails), "chain tails and", len(self.verified.tails.get(best_tail, [])), 'chain heads. Top 10 heads:'
337 for h in scores[-10:]:
338 print ' ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
339 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
340 self.verified.shares[h].peer is None,
341 ht.get_min_height(self.verified.shares[h].previous_block),
342 -self.verified.shares[h].time_seen
347 for i in xrange(1000):
349 for share_hash, tail in self.heads.iteritems():
350 if share_hash in scores[-5:]:
353 if self.shares[share_hash].time_seen > time.time() - 300:
356 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 to_remove.add(share_hash)
362 for share_hash in to_remove:
363 self.remove(share_hash)
364 if share_hash in self.verified.shares:
365 self.verified.remove(share_hash)
366 #print "_________", to_remove
369 for i in xrange(1000):
371 for tail, heads in self.tails.iteritems():
372 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
374 for aftertail in self.reverse_shares.get(tail, set()):
375 if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
378 to_remove.add(aftertail)
381 # if removed from this, it must be removed from verified
383 for aftertail in to_remove:
384 if self.shares[aftertail].previous_hash not in self.tails:
385 print "erk", aftertail, self.shares[aftertail].previous_hash
387 self.remove(aftertail)
388 if aftertail in self.verified.shares:
389 self.verified.remove(aftertail)
391 #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
393 best = scores[-1] if scores else None
396 best_share = self.verified.shares[best]
397 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:
399 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
400 best = best_share.previous_hash
404 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
405 def score(self, share_hash, ht):
406 head_height, last = self.verified.get_height_and_last(share_hash)
410 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
411 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
412 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
413 attempts += bitcoin_data.target_to_average_attempts(share.target)
414 this_score = attempts//(ht.get_highest_height() - max_height + 1)
415 if this_score > score2:
417 return min(head_height, self.net.CHAIN_LENGTH), score2
422 return '%08x' % (x % 2**32)
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))
430 self.known = None # will be filename -> set of share hashes, set of verified hashes
432 def get_shares(self):
433 if self.known is not None:
434 raise AssertionError()
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:
442 type_id_str, data_hex = line.strip().split(' ')
443 type_id = int(type_id_str)
449 verified_hash = int(data_hex, 16)
450 yield 'verified_hash', verified_hash
451 verified_hashes.add(verified_hash)
453 share = NewShare.from_share(new_share_type.unpack(data_hex.decode('hex')), self.net)
455 share_hashes.add(share.hash)
457 raise NotImplementedError("share type %i" % (type_id,))
459 log.err(None, "Error while reading saved shares, continuing where left off:")
462 def _add_line(self, line):
463 filenames, next = self.get_filenames_and_next()
464 if filenames and os.path.getsize(filenames[-1]) < 10e6:
465 filename = filenames[-1]
469 with open(filename, 'ab') as f:
474 def add_share(self, share):
475 type_id, data = 5, new_share_type.pack(share.as_share())
476 filename = self._add_line("%i %s" % (type_id, data.encode('hex')))
477 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
478 share_hashes.add(share.hash)
480 def add_verified_hash(self, share_hash):
481 filename = self._add_line("%i %x" % (2, share_hash))
482 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
483 verified_hashes.add(share_hash)
485 def get_filenames_and_next(self):
486 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())
487 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)))
489 def forget_share(self, share_hash):
490 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
491 if share_hash in share_hashes:
492 share_hashes.remove(share_hash)
495 def forget_verified_share(self, share_hash):
496 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
497 if share_hash in verified_hashes:
498 verified_hashes.remove(share_hash)
501 def check_remove(self):
503 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
504 #print filename, len(share_hashes) + len(verified_hashes)
505 if not share_hashes and not verified_hashes:
506 to_remove.add(filename)
507 for filename in to_remove:
508 self.known.pop(filename)
510 print "REMOVED", filename