1 from __future__ import division
8 from twisted.python import log
11 from p2pool.bitcoin import data as bitcoin_data, script, sha256
12 from p2pool.util import math, forest, pack
16 hash_link_type = pack.ComposedType([
17 ('state', pack.FixedStrType(32)),
18 ('extra_data', pack.FixedStrType(0)), # bit of a hack, but since the donation script is at the end, const_ending is long enough to always make this empty
19 ('length', pack.VarIntType()),
22 def prefix_to_hash_link(prefix, const_ending=''):
23 assert prefix.endswith(const_ending), (prefix, const_ending)
24 x = sha256.sha256(prefix)
25 return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
27 def check_hash_link(hash_link, data, const_ending=''):
28 extra_length = hash_link['length'] % (512//8)
29 assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
30 extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
31 assert len(extra) == extra_length
32 return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
36 share_type = pack.ComposedType([
37 ('type', pack.VarIntType()),
38 ('contents', pack.VarStrType()),
41 def load_share(share, net, peer):
42 if share['type'] in [0, 1, 2, 3]:
43 from p2pool import p2p
44 raise p2p.PeerMisbehavingError('sent an obsolete share')
45 elif share['type'] == 4:
46 return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
47 elif share['type'] == 5:
48 share1b = Share.share1b_type.unpack(share['contents'])
49 return Share(net, peer, merkle_link=bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
50 elif share['type'] == 6:
51 return NewShare(net, peer, other_txs=None, **NewShare.share1a_type.unpack(share['contents']))
52 elif share['type'] == 7:
53 share1b = NewShare.share1b_type.unpack(share['contents'])
54 return NewShare(net, peer, merkle_link=bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
56 raise ValueError('unknown share type: %r' % (share['type'],))
58 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
61 small_block_header_type = pack.ComposedType([
62 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
63 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
64 ('timestamp', pack.IntType(32)),
65 ('bits', bitcoin_data.FloatingIntegerType()),
66 ('nonce', pack.IntType(32)),
69 share_data_type = pack.ComposedType([
70 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
71 ('coinbase', pack.VarStrType()),
72 ('nonce', pack.IntType(32)),
73 ('pubkey_hash', pack.IntType(160)),
74 ('subsidy', pack.IntType(64)),
75 ('donation', pack.IntType(16)),
76 ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))),
77 ('desired_version', pack.VarIntType()),
80 share_info_type = pack.ComposedType([
81 ('share_data', share_data_type),
82 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
83 ('max_bits', bitcoin_data.FloatingIntegerType()),
84 ('bits', bitcoin_data.FloatingIntegerType()),
85 ('timestamp', pack.IntType(32)),
88 share_common_type = pack.ComposedType([
89 ('min_header', small_block_header_type),
90 ('share_info', share_info_type),
91 ('ref_merkle_link', pack.ComposedType([
92 ('branch', pack.ListType(pack.IntType(256))),
93 ('index', pack.VarIntType()),
95 ('hash_link', hash_link_type),
97 share1a_type = pack.ComposedType([
98 ('common', share_common_type),
99 ('merkle_link', pack.ComposedType([
100 ('branch', pack.ListType(pack.IntType(256))),
101 ('index', pack.IntType(0)), # it will always be 0
104 share1b_type = pack.ComposedType([
105 ('common', share_common_type),
106 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
109 ref_type = pack.ComposedType([
110 ('identifier', pack.FixedStrType(64//8)),
111 ('share_info', share_info_type),
114 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
117 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, net):
118 previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
120 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
121 assert height >= net.REAL_CHAIN_LENGTH or last is None
122 if height < net.TARGET_LOOKBEHIND:
123 pre_target3 = net.MAX_TARGET
125 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
126 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
127 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
128 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
129 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
130 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
132 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
133 min(height, net.REAL_CHAIN_LENGTH),
134 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
136 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
138 amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share
139 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
140 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
141 amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding
143 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
146 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
149 share_data=share_data,
150 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
153 timestamp=math.clip(desired_timestamp, (
154 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
155 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
156 )) if previous_share is not None else desired_timestamp,
159 return share_info, dict(
162 previous_output=None,
164 script=share_data['coinbase'].ljust(2, '\x00'),
166 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
168 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
174 def get_ref_hash(cls, net, share_info, ref_merkle_link):
175 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
176 identifier=net.IDENTIFIER,
177 share_info=share_info,
178 ))), ref_merkle_link))
180 __slots__ = 'net peer common min_header share_info hash_link merkle_link other_txs hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash time_seen'.split(' ')
182 def __init__(self, net, peer, common, merkle_link, other_txs):
186 self.min_header = common['min_header']
187 self.share_info = common['share_info']
188 self.hash_link = common['hash_link']
189 self.merkle_link = merkle_link
190 self.other_txs = other_txs
192 if len(self.share_info['share_data']['coinbase']) > 100:
193 raise ValueError('''coinbase too large! %i bytes''' % (len(self.self.share_data['coinbase']),))
195 if len(merkle_link['branch']) > 16:
196 raise ValueError('merkle branch too long!')
198 if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_link:
199 raise ValueError('merkle_link and other_txs do not match')
201 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
203 self.share_data = self.share_info['share_data']
204 self.max_target = self.share_info['max_bits'].target
205 self.target = self.share_info['bits'].target
206 self.timestamp = self.share_info['timestamp']
207 self.previous_hash = self.share_data['previous_share_hash']
208 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
209 self.desired_version = self.share_data['desired_version']
211 self.gentx_hash = check_hash_link(
213 self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
214 self.gentx_before_refhash,
216 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
217 self.header = dict(self.min_header, merkle_root=merkle_root)
218 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
219 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
221 if self.pow_hash > self.target:
222 from p2pool import p2p
223 raise p2p.PeerMisbehavingError('share PoW invalid')
225 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
226 raise ValueError('other_txs provided when not a block solution')
227 if other_txs is None and self.pow_hash <= self.header['bits'].target:
228 raise ValueError('other_txs not provided when a block solution')
231 self.time_seen = time.time()
234 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
237 if not self.pow_hash <= self.header['bits'].target: # share1a
238 return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
240 return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
242 def check(self, tracker):
243 if self.share_data['previous_share_hash'] is not None:
244 previous_share = tracker.shares[self.share_data['previous_share_hash']]
245 if isinstance(previous_share, NewShare):
246 from p2pool import p2p
247 raise p2p.PeerMisbehavingError('''Share can't follow NewShare''')
248 share_info, gentx = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.common['ref_merkle_link'], self.net)
249 if share_info != self.share_info:
250 raise ValueError('share_info invalid')
251 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
252 raise ValueError('''gentx doesn't match hash_link''')
253 return gentx # only used by as_block
255 def as_block(self, tracker):
256 if self.other_txs is None:
257 raise ValueError('share does not contain all txs')
258 return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
260 class NewShare(Share):
261 def __init__(self, *args, **kwargs):
262 Share.__init__(self, *args, **kwargs)
263 self.hash = bitcoin_data.hash256(share_type.pack(self.as_share()))
265 def check(self, tracker):
266 if self.share_data['previous_share_hash'] is not None:
267 previous_share = tracker.shares[self.share_data['previous_share_hash']]
268 if isinstance(previous_share, Share):
269 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
270 from p2pool import p2p
271 raise p2p.PeerMisbehavingError('NewShare without enough history')
273 # Share -> NewShare only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
274 counts = get_desired_version_counts(tracker,
275 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
276 if counts.get(2, 0) < sum(counts.itervalues())*85//100:
277 from p2pool import p2p
278 raise p2p.PeerMisbehavingError('NewShare without enough hash power upgraded')
279 share_info, gentx = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.common['ref_merkle_link'], self.net)
280 if share_info != self.share_info:
281 raise ValueError('share_info invalid')
282 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
283 raise ValueError('''gentx doesn't match hash_link''')
284 return gentx # only used by as_block
287 if not self.pow_hash <= self.header['bits'].target: # share1a
288 return dict(type=6, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
290 return dict(type=7, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
293 class WeightsSkipList(forest.TrackerSkipList):
294 # share_count, weights, total_weight
296 def get_delta(self, element):
297 from p2pool.bitcoin import data as bitcoin_data
298 share = self.tracker.shares[element]
299 att = bitcoin_data.target_to_average_attempts(share.target)
300 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
302 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
303 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
305 def initial_solution(self, start, (max_shares, desired_weight)):
306 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
309 def apply_delta(self, (share_count1, weights_list, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2), (max_shares, desired_weight)):
310 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
311 assert (desired_weight - total_weight1) % 65535 == 0
312 script, = weights2.iterkeys()
313 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
314 return share_count1 + share_count2, (weights_list, new_weights), desired_weight, total_donation_weight1 + (desired_weight - total_weight1)//65535*total_donation_weight2//(total_weight2//65535)
315 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
317 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
318 if share_count > max_shares or total_weight > desired_weight:
320 elif share_count == max_shares or total_weight == desired_weight:
325 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
326 assert share_count <= max_shares and total_weight <= desired_weight
327 assert share_count == max_shares or total_weight == desired_weight
328 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
330 class OkayTracker(forest.Tracker):
331 def __init__(self, net, my_share_hashes, my_doa_share_hashes):
332 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
333 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
334 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
337 self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
338 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
339 my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
340 my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
341 my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'orphan' else 0,
342 my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'doa' else 0,
344 self.get_cumulative_weights = WeightsSkipList(self)
346 def attempt_verify(self, share):
347 if share.hash in self.verified.shares:
349 height, last = self.get_height_and_last(share.hash)
350 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
351 raise AssertionError()
355 log.err(None, 'Share check failed:')
358 self.verified.add(share)
361 def think(self, block_rel_height_func, previous_block, bits):
365 # make 'unverified heads' set?
366 # for each overall head, attempt verification
367 # if it fails, attempt on parent, and repeat
368 # if no successful verification because of lack of parents, request parent
370 for head in set(self.heads) - set(self.verified.heads):
371 head_height, last = self.get_height_and_last(head)
373 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
374 if self.attempt_verify(share):
376 if share.hash in self.heads:
381 self.shares[random.choice(list(self.reverse_shares[last]))].peer,
383 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
384 min(x.target for x in self.get_chain(head, min(head_height, 5))),
387 assert bad not in self.verified.shares
388 assert bad in self.heads
393 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
394 for head in list(self.verified.heads):
395 head_height, last_hash = self.verified.get_height_and_last(head)
396 last_height, last_last_hash = self.get_height_and_last(last_hash)
397 # XXX review boundary conditions
398 want = max(self.net.CHAIN_LENGTH - head_height, 0)
399 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
401 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
402 for share in self.get_chain(last_hash, get):
403 if not self.attempt_verify(share):
405 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
407 self.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
409 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
410 min(x.target for x in self.get_chain(head, min(head_height, 5))),
414 decorated_tails = sorted((self.score(max(self.verified.tails[tail_hash], key=self.verified.get_work), block_rel_height_func), tail_hash) for tail_hash in self.verified.tails)
416 print len(decorated_tails), 'tails:'
417 for score, tail_hash in decorated_tails:
418 print format_hash(tail_hash), score
419 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
421 # decide best verified head
422 decorated_heads = sorted(((
423 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
424 #self.shares[h].peer is None,
425 self.shares[h].pow_hash <= self.shares[h].header['bits'].target, # is block solution
426 (self.shares[h].header['previous_block'], self.shares[h].header['bits']) == (previous_block, bits) or self.shares[h].peer is None,
427 -self.shares[h].time_seen,
428 ), h) for h in self.verified.tails.get(best_tail, []))
430 print len(decorated_heads), 'heads. Top 10:'
431 for score, head_hash in decorated_heads[-10:]:
432 print ' ', format_hash(head_hash), format_hash(self.shares[head_hash].previous_hash), score
433 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
437 for i in xrange(1000):
439 for share_hash, tail in self.heads.iteritems():
440 if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
443 if self.shares[share_hash].time_seen > time.time() - 300:
446 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
449 to_remove.add(share_hash)
452 for share_hash in to_remove:
453 if share_hash in self.verified.shares:
454 self.verified.remove(share_hash)
455 self.remove(share_hash)
456 #print "_________", to_remove
459 for i in xrange(1000):
461 for tail, heads in self.tails.iteritems():
462 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
464 for aftertail in self.reverse_shares.get(tail, set()):
465 if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
468 to_remove.add(aftertail)
471 # if removed from this, it must be removed from verified
473 for aftertail in to_remove:
474 if self.shares[aftertail].previous_hash not in self.tails:
475 print "erk", aftertail, self.shares[aftertail].previous_hash
477 if aftertail in self.verified.shares:
478 self.verified.remove(aftertail)
479 self.remove(aftertail)
481 #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
484 best_share = self.shares[best]
485 if (best_share.header['previous_block'], best_share.header['bits']) != (previous_block, bits) and best_share.header_hash != previous_block and best_share.peer is not None:
487 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
488 best = best_share.previous_hash
490 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
491 target_cutoff = 2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 if best_tail_score[1] is not None else 2**256-1
493 timestamp_cutoff = int(time.time()) - 24*60*60
494 target_cutoff = 2**256-1
497 print 'Desire %i shares. Cutoff: %s old diff>%.2f' % (len(desired), math.format_dt(time.time() - timestamp_cutoff), bitcoin_data.target_to_difficulty(target_cutoff))
498 for peer, hash, ts, targ in desired:
499 print ' ', '%s:%i' % peer.addr if peer is not None else None, format_hash(hash), math.format_dt(time.time() - ts), bitcoin_data.target_to_difficulty(targ), ts >= timestamp_cutoff, targ <= target_cutoff
501 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
503 def score(self, share_hash, block_rel_height_func):
504 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
506 head_height = self.verified.get_height(share_hash)
507 if head_height < self.net.CHAIN_LENGTH:
508 return head_height, None
510 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
512 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
513 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
515 return self.net.CHAIN_LENGTH, (self.verified.get_work(share_hash) - self.verified.get_work(end_point))//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
517 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
519 near = tracker.shares[previous_share_hash]
520 far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
521 attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
522 time = near.timestamp - far.timestamp
526 return attempts//time
529 def get_average_stale_prop(tracker, share_hash, lookbehind):
530 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
531 return stales/(lookbehind + stales)
533 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
535 for share in tracker.get_chain(share_hash, lookbehind - 1):
536 res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
537 s = share.share_data['stale_info']
539 res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
541 dt = tracker.shares[share_hash].timestamp - tracker.shares[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
542 res = dict((k, v/dt) for k, v in res.iteritems())
545 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
546 weights, total_weight, donation_weight = tracker.get_cumulative_weights(best_share_hash, min(tracker.get_height(best_share_hash), net.REAL_CHAIN_LENGTH), 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target))
547 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
548 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
551 def get_desired_version_counts(tracker, best_share_hash, dist):
553 for share in tracker.get_chain(best_share_hash, dist):
554 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
557 def get_warnings(tracker, current_work, net):
560 desired_version_counts = get_desired_version_counts(tracker, current_work.value['best_share_hash'],
561 min(60*60//net.SHARE_PERIOD, tracker.get_height(current_work.value['best_share_hash'])))
562 majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
563 if majority_desired_version not in [0, 1, 2] and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
564 res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
565 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
566 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
573 return '%08x' % (x % 2**32)
575 class ShareStore(object):
576 def __init__(self, prefix, net):
577 self.filename = prefix
578 self.dirname = os.path.dirname(os.path.abspath(prefix))
579 self.filename = os.path.basename(os.path.abspath(prefix))
581 self.known = None # will be filename -> set of share hashes, set of verified hashes
582 self.known_desired = None
584 def get_shares(self):
585 if self.known is not None:
586 raise AssertionError()
588 filenames, next = self.get_filenames_and_next()
589 for filename in filenames:
590 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
591 with open(filename, 'rb') as f:
594 type_id_str, data_hex = line.strip().split(' ')
595 type_id = int(type_id_str)
601 verified_hash = int(data_hex, 16)
602 yield 'verified_hash', verified_hash
603 verified_hashes.add(verified_hash)
605 raw_share = share_type.unpack(data_hex.decode('hex'))
606 if raw_share['type'] in [0, 1, 2, 3]:
608 share = load_share(raw_share, self.net, None)
610 share_hashes.add(share.hash)
612 raise NotImplementedError("share type %i" % (type_id,))
614 log.err(None, "Error while reading saved shares, continuing where left off:")
616 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
618 def _add_line(self, line):
619 filenames, next = self.get_filenames_and_next()
620 if filenames and os.path.getsize(filenames[-1]) < 10e6:
621 filename = filenames[-1]
625 with open(filename, 'ab') as f:
630 def add_share(self, share):
631 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
632 if share.hash in share_hashes:
635 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
636 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
637 share_hashes.add(share.hash)
638 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
639 share_hashes.add(share.hash)
641 def add_verified_hash(self, share_hash):
642 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
643 if share_hash in verified_hashes:
646 filename = self._add_line("%i %x" % (2, share_hash))
647 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
648 verified_hashes.add(share_hash)
649 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
650 verified_hashes.add(share_hash)
652 def get_filenames_and_next(self):
653 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())
654 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)))
656 def forget_share(self, share_hash):
657 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
658 if share_hash in share_hashes:
659 share_hashes.remove(share_hash)
662 def forget_verified_share(self, share_hash):
663 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
664 if share_hash in verified_hashes:
665 verified_hashes.remove(share_hash)
668 def check_remove(self):
670 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
671 #print filename, len(share_hashes) + len(verified_hashes)
672 if not share_hashes and not verified_hashes:
673 to_remove.add(filename)
674 for filename in to_remove:
675 self.known.pop(filename)
676 self.known_desired.pop(filename)
678 print "REMOVED", filename