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())
40 share_type = pack.ComposedType([
41 ('type', pack.VarIntType()),
42 ('contents', pack.VarStrType()),
45 def load_share(share, net, peer):
46 if share['type'] in [0, 1]:
47 from p2pool import p2p
48 raise p2p.PeerMisbehavingError('sent an obsolete share')
49 elif share['type'] == 2:
50 return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
51 elif share['type'] == 3:
52 share1b = Share.share1b_type.unpack(share['contents'])
53 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)
54 elif share['type'] == 4:
55 return NewShare(net, peer, other_txs=None, **NewShare.share1a_type.unpack(share['contents']))
56 elif share['type'] == 5:
57 share1b = NewShare.share1b_type.unpack(share['contents'])
58 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)
60 raise ValueError('unknown share type: %r' % (share['type'],))
62 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
65 small_block_header_type = pack.ComposedType([
66 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
67 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
68 ('timestamp', pack.IntType(32)),
69 ('bits', bitcoin_data.FloatingIntegerType()),
70 ('nonce', pack.IntType(32)),
73 share_data_type = pack.ComposedType([
74 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
75 ('coinbase', pack.VarStrType()),
76 ('nonce', pack.IntType(32)),
77 ('pubkey_hash', pack.IntType(160)),
78 ('subsidy', pack.IntType(64)),
79 ('donation', pack.IntType(16)),
80 ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
83 share_info_type = pack.ComposedType([
84 ('share_data', share_data_type),
85 ('max_bits', bitcoin_data.FloatingIntegerType()),
86 ('bits', bitcoin_data.FloatingIntegerType()),
87 ('timestamp', pack.IntType(32)),
90 share1a_type = pack.ComposedType([
91 ('min_header', small_block_header_type),
92 ('share_info', share_info_type),
93 ('hash_link', hash_link_type),
94 ('merkle_link', pack.ComposedType([
95 ('branch', pack.ListType(pack.IntType(256))),
96 ('index', pack.IntType(0)), # it will always be 0
100 share1b_type = pack.ComposedType([
101 ('min_header', small_block_header_type),
102 ('share_info', share_info_type),
103 ('hash_link', hash_link_type),
104 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
107 ref_type = pack.ComposedType([
108 ('identifier', pack.FixedStrType(64//8)),
109 ('share_info', share_info_type),
112 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
115 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, net):
116 previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
118 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
119 assert height >= net.REAL_CHAIN_LENGTH or last is None
120 if height < net.TARGET_LOOKBEHIND:
121 pre_target3 = net.MAX_TARGET
123 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
124 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
125 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
126 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
127 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
128 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
130 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
131 min(height, net.REAL_CHAIN_LENGTH),
132 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
135 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
137 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
138 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
139 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
140 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
142 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
145 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
148 share_data=share_data,
151 timestamp=math.clip(desired_timestamp, (
152 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
153 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
154 )) if previous_share is not None else desired_timestamp,
157 return share_info, dict(
160 previous_output=None,
162 script=share_data['coinbase'].ljust(2, '\x00'),
164 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]] + [dict(
166 script='\x20' + pack.IntType(256).pack(bitcoin_data.hash256(cls.ref_type.pack(dict(
167 identifier=net.IDENTIFIER,
168 share_info=share_info,
174 __slots__ = 'net 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 peer'.split(' ')
176 def __init__(self, net, peer, min_header, share_info, hash_link, merkle_link, other_txs):
177 if len(share_info['share_data']['coinbase']) > 100:
178 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
180 if len(merkle_link['branch']) > 16:
181 raise ValueError('merkle_branch too long!')
183 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:
184 raise ValueError('merkle_link and other_txs do not match')
186 assert not hash_link['extra_data'], repr(hash_link['extra_data'])
190 self.min_header = min_header
191 self.share_info = share_info
192 self.hash_link = hash_link
193 self.merkle_link = merkle_link
194 self.other_txs = other_txs
196 self.share_data = self.share_info['share_data']
197 self.max_target = self.share_info['max_bits'].target
198 self.target = self.share_info['bits'].target
199 self.timestamp = self.share_info['timestamp']
200 self.previous_hash = self.share_data['previous_share_hash']
201 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
202 self.desired_version = 0
204 if self.timestamp > net.SWITCH_TIME:
205 from p2pool import p2p
206 raise p2p.PeerMisbehavingError('peer sent an old-style share with a timestamp after the switch time')
208 self.gentx_hash = check_hash_link(
210 pack.IntType(256).pack(bitcoin_data.hash256(self.ref_type.pack(dict(
211 identifier=net.IDENTIFIER,
212 share_info=share_info,
213 )))) + 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(min_header, merkle_root=merkle_root)
218 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
219 self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
221 if self.pow_hash > self.target:
222 raise p2p.PeerMisbehavingError('share PoW invalid')
224 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
225 raise ValueError('other_txs provided when not a block solution')
226 if other_txs is None and self.pow_hash <= self.header['bits'].target:
227 raise ValueError('other_txs not provided when a block solution')
229 self.hash = bitcoin_data.hash256(share_type.pack(self.as_share()))
232 self.time_seen = time.time()
235 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
237 def check(self, tracker):
238 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.net)
239 if share_info != self.share_info:
240 raise ValueError('share difficulty invalid')
241 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
242 raise ValueError('''gentx doesn't match hash_link''')
245 if not self.pow_hash <= self.header['bits'].target: # share1a
246 return dict(type=2, contents=self.share1a_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, merkle_link=self.merkle_link)))
248 return dict(type=3, contents=self.share1b_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, other_txs=self.other_txs)))
250 def as_block(self, tracker):
251 if self.other_txs is None:
252 raise ValueError('share does not contain all txs')
254 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.net)
255 assert share_info == self.share_info
257 return dict(header=self.header, txs=[gentx] + self.other_txs)
259 class NewShare(Share):
260 share_data_type = pack.ComposedType([
261 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
262 ('coinbase', pack.VarStrType()),
263 ('nonce', pack.IntType(32)),
264 ('pubkey_hash', pack.IntType(160)),
265 ('subsidy', pack.IntType(64)),
266 ('donation', pack.IntType(16)),
267 ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
268 ('desired_version', pack.VarIntType()),
271 share_info_type = pack.ComposedType([
272 ('share_data', share_data_type),
273 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
274 ('max_bits', bitcoin_data.FloatingIntegerType()),
275 ('bits', bitcoin_data.FloatingIntegerType()),
276 ('timestamp', pack.IntType(32)),
279 share_common_type = pack.ComposedType([
280 ('min_header', Share.small_block_header_type),
281 ('share_info', share_info_type),
282 ('ref_merkle_link', pack.ComposedType([
283 ('branch', pack.ListType(pack.IntType(256))),
284 ('index', pack.VarIntType()),
286 ('hash_link', hash_link_type),
288 share1a_type = pack.ComposedType([
289 ('common', share_common_type),
290 ('merkle_link', pack.ComposedType([
291 ('branch', pack.ListType(pack.IntType(256))),
292 ('index', pack.IntType(0)), # it will always be 0
295 share1b_type = pack.ComposedType([
296 ('common', share_common_type),
297 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
300 ref_type = pack.ComposedType([
301 ('identifier', pack.FixedStrType(64//8)),
302 ('share_info', share_info_type),
306 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, net):
307 previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
309 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
310 assert height >= net.REAL_CHAIN_LENGTH or last is None
311 if height < net.TARGET_LOOKBEHIND:
312 pre_target3 = net.MAX_TARGET
314 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
315 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
316 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
317 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
318 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
319 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
321 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
322 min(height, net.REAL_CHAIN_LENGTH),
323 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
326 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
328 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
329 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
330 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
331 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
333 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
336 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
339 share_data=share_data,
340 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
343 timestamp=math.clip(desired_timestamp, (
344 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
345 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
346 )) if previous_share is not None else desired_timestamp,
349 return share_info, dict(
352 previous_output=None,
354 script=share_data['coinbase'].ljust(2, '\x00'),
356 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]] + [dict(
358 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
364 def get_ref_hash(cls, net, share_info, ref_merkle_link):
365 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
366 identifier=net.IDENTIFIER,
367 share_info=share_info,
368 ))), ref_merkle_link))
370 __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(' ')
372 def __init__(self, net, peer, common, merkle_link, other_txs):
376 self.min_header = common['min_header']
377 self.share_info = common['share_info']
378 self.hash_link = common['hash_link']
379 self.merkle_link = merkle_link
380 self.other_txs = other_txs
382 if len(self.share_info['share_data']['coinbase']) > 100:
383 raise ValueError('''coinbase too large! %i bytes''' % (len(self.self.share_data['coinbase']),))
385 if len(merkle_link['branch']) > 16:
386 raise ValueError('merkle branch too long!')
388 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:
389 raise ValueError('merkle_link and other_txs do not match')
391 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
393 self.share_data = self.share_info['share_data']
394 self.max_target = self.share_info['max_bits'].target
395 self.target = self.share_info['bits'].target
396 self.timestamp = self.share_info['timestamp']
397 self.previous_hash = self.share_data['previous_share_hash']
398 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
399 self.desired_version = self.share_data['desired_version']
401 if self.timestamp < net.SWITCH_TIME:
402 from p2pool import p2p
403 raise p2p.PeerMisbehavingError('peer sent a new-style share with a timestamp before the switch time')
405 self.gentx_hash = check_hash_link(
407 self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
408 self.gentx_before_refhash,
410 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
411 self.header = dict(self.min_header, merkle_root=merkle_root)
412 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
413 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
415 if self.pow_hash > self.target:
416 raise p2p.PeerMisbehavingError('share PoW invalid')
418 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
419 raise ValueError('other_txs provided when not a block solution')
420 if other_txs is None and self.pow_hash <= self.header['bits'].target:
421 raise ValueError('other_txs not provided when a block solution')
424 self.time_seen = time.time()
427 if not self.pow_hash <= self.header['bits'].target: # share1a
428 return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
430 return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
432 def check(self, tracker):
433 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)
434 if share_info != self.share_info:
435 raise ValueError('share_info invalid')
436 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
437 raise ValueError('''gentx doesn't match hash_link''')
438 return gentx # only used by as_block
440 def as_block(self, tracker):
441 if self.other_txs is None:
442 raise ValueError('share does not contain all txs')
443 return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
445 class WeightsSkipList(forest.TrackerSkipList):
446 # share_count, weights, total_weight
448 def get_delta(self, element):
449 from p2pool.bitcoin import data as bitcoin_data
450 share = self.tracker.shares[element]
451 att = bitcoin_data.target_to_average_attempts(share.target)
452 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
454 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
455 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
457 def initial_solution(self, start, (max_shares, desired_weight, broken_mode)):
458 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
461 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, broken_mode)):
462 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
463 assert (desired_weight - total_weight1) % 65535 == 0
464 script, = weights2.iterkeys()
466 new_weights = dict(script=(desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535))
468 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
469 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)
470 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
472 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight, broken_mode)):
473 if share_count > max_shares or total_weight > desired_weight:
475 elif share_count == max_shares or total_weight == desired_weight:
480 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight, broken_mode)):
481 assert share_count <= max_shares and total_weight <= desired_weight
482 assert share_count == max_shares or total_weight == desired_weight
483 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
485 class OkayTracker(forest.Tracker):
486 def __init__(self, net, my_share_hashes, my_doa_share_hashes):
487 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
488 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
489 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
492 self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
493 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
494 my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
495 my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
496 my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 253 else 0,
497 my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 254 else 0,
499 self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
501 self.get_cumulative_weights = WeightsSkipList(self)
503 def attempt_verify(self, share):
504 if share.hash in self.verified.shares:
506 height, last = self.get_height_and_last(share.hash)
507 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
508 raise AssertionError()
512 log.err(None, 'Share check failed:')
515 self.verified.add(share)
518 def think(self, block_rel_height_func, previous_block, bits):
522 # make 'unverified heads' set?
523 # for each overall head, attempt verification
524 # if it fails, attempt on parent, and repeat
525 # if no successful verification because of lack of parents, request parent
527 for head in set(self.heads) - set(self.verified.heads):
528 head_height, last = self.get_height_and_last(head)
530 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
531 if self.attempt_verify(share):
533 if share.hash in self.heads:
538 self.shares[random.choice(list(self.reverse_shares[last]))].peer,
540 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
541 min(x.target for x in self.get_chain(head, min(head_height, 5))),
544 assert bad not in self.verified.shares
545 assert bad in self.heads
550 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
551 for head in list(self.verified.heads):
552 head_height, last_hash = self.verified.get_height_and_last(head)
553 last_height, last_last_hash = self.get_height_and_last(last_hash)
554 # XXX review boundary conditions
555 want = max(self.net.CHAIN_LENGTH - head_height, 0)
556 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
558 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
559 for share in self.get_chain(last_hash, get):
560 if not self.attempt_verify(share):
562 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
564 self.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
566 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
567 min(x.target for x in self.get_chain(head, min(head_height, 5))),
571 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)
573 print len(decorated_tails), 'tails:'
574 for score, tail_hash in decorated_tails:
575 print format_hash(tail_hash), score
576 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
578 # decide best verified head
579 decorated_heads = sorted(((
580 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
581 #self.shares[h].peer is None,
582 self.shares[h].pow_hash <= self.shares[h].header['bits'].target, # is block solution
583 (self.shares[h].header['previous_block'], self.shares[h].header['bits']) == (previous_block, bits) or self.shares[h].peer is None,
584 -self.shares[h].time_seen,
585 ), h) for h in self.verified.tails.get(best_tail, []))
587 print len(decorated_heads), 'heads. Top 10:'
588 for score, head_hash in decorated_heads[-10:]:
589 print ' ', format_hash(head_hash), format_hash(self.shares[head_hash].previous_hash), score
590 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
594 for i in xrange(1000):
596 for share_hash, tail in self.heads.iteritems():
597 if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
600 if self.shares[share_hash].time_seen > time.time() - 300:
603 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
606 to_remove.add(share_hash)
609 for share_hash in to_remove:
610 self.remove(share_hash)
611 if share_hash in self.verified.shares:
612 self.verified.remove(share_hash)
613 #print "_________", to_remove
616 for i in xrange(1000):
618 for tail, heads in self.tails.iteritems():
619 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
621 for aftertail in self.reverse_shares.get(tail, set()):
622 if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
625 to_remove.add(aftertail)
628 # if removed from this, it must be removed from verified
630 for aftertail in to_remove:
631 if self.shares[aftertail].previous_hash not in self.tails:
632 print "erk", aftertail, self.shares[aftertail].previous_hash
634 self.remove(aftertail)
635 if aftertail in self.verified.shares:
636 self.verified.remove(aftertail)
638 #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
641 best_share = self.shares[best]
642 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:
644 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
645 best = best_share.previous_hash
647 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
648 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
650 timestamp_cutoff = int(time.time()) - 24*60*60
651 target_cutoff = 2**256-1
654 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))
655 for peer, hash, ts, targ in desired:
656 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
658 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
660 def score(self, share_hash, block_rel_height_func):
661 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
663 head_height = self.verified.get_height(share_hash)
664 if head_height < self.net.CHAIN_LENGTH:
665 return head_height, None
667 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
669 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
670 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
672 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)
674 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
676 near = tracker.shares[previous_share_hash]
677 far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
678 attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash) if not min_work else tracker.get_delta(near.hash).min_work - tracker.get_delta(far.hash).min_work
679 time = near.timestamp - far.timestamp
683 return attempts//time
686 def get_average_stale_prop(tracker, share_hash, lookbehind):
687 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] != 0)
688 return stales/(lookbehind + stales)
690 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
691 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), False)
692 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
693 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
696 def get_desired_version_counts(tracker, best_share_hash, dist):
698 for share in tracker.get_chain(best_share_hash, dist):
699 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
705 return '%08x' % (x % 2**32)
707 class ShareStore(object):
708 def __init__(self, prefix, net):
709 self.filename = prefix
710 self.dirname = os.path.dirname(os.path.abspath(prefix))
711 self.filename = os.path.basename(os.path.abspath(prefix))
713 self.known = None # will be filename -> set of share hashes, set of verified hashes
714 self.known_desired = None
716 def get_shares(self):
717 if self.known is not None:
718 raise AssertionError()
720 filenames, next = self.get_filenames_and_next()
721 for filename in filenames:
722 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
723 with open(filename, 'rb') as f:
726 type_id_str, data_hex = line.strip().split(' ')
727 type_id = int(type_id_str)
733 verified_hash = int(data_hex, 16)
734 yield 'verified_hash', verified_hash
735 verified_hashes.add(verified_hash)
737 raw_share = share_type.unpack(data_hex.decode('hex'))
738 if raw_share['type'] in [0, 1]:
740 share = load_share(raw_share, self.net, None)
742 share_hashes.add(share.hash)
744 raise NotImplementedError("share type %i" % (type_id,))
746 log.err(None, "Error while reading saved shares, continuing where left off:")
748 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
750 def _add_line(self, line):
751 filenames, next = self.get_filenames_and_next()
752 if filenames and os.path.getsize(filenames[-1]) < 10e6:
753 filename = filenames[-1]
757 with open(filename, 'ab') as f:
762 def add_share(self, share):
763 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
764 if share.hash in share_hashes:
767 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
768 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
769 share_hashes.add(share.hash)
770 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
771 share_hashes.add(share.hash)
773 def add_verified_hash(self, share_hash):
774 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
775 if share_hash in verified_hashes:
778 filename = self._add_line("%i %x" % (2, share_hash))
779 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
780 verified_hashes.add(share_hash)
781 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
782 verified_hashes.add(share_hash)
784 def get_filenames_and_next(self):
785 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())
786 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)))
788 def forget_share(self, share_hash):
789 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
790 if share_hash in share_hashes:
791 share_hashes.remove(share_hash)
794 def forget_verified_share(self, share_hash):
795 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
796 if share_hash in verified_hashes:
797 verified_hashes.remove(share_hash)
800 def check_remove(self):
802 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
803 #print filename, len(share_hashes) + len(verified_hashes)
804 if not share_hashes and not verified_hashes:
805 to_remove.add(filename)
806 for filename in to_remove:
807 self.known.pop(filename)
808 self.known_desired.pop(filename)
810 print "REMOVED", filename