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, sha256
13 from p2pool.util import math, forest, pack
17 hash_link_type = pack.ComposedType([
18 ('state', pack.FixedStrType(32)),
19 ('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
20 ('length', pack.VarIntType()),
23 def prefix_to_hash_link(prefix, const_ending=''):
24 assert prefix.endswith(const_ending), (prefix, const_ending)
25 x = sha256.sha256(prefix)
26 return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
28 def check_hash_link(hash_link, data, const_ending=''):
29 extra_length = hash_link['length'] % (512//8)
30 assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
31 extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
32 assert len(extra) == extra_length
33 return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
37 share_data_type = pack.ComposedType([
38 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
39 ('coinbase', pack.VarStrType()),
40 ('nonce', pack.VarStrType()),
41 ('new_script', pack.VarStrType()),
42 ('subsidy', pack.IntType(64)),
43 ('donation', pack.IntType(16)),
44 ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
47 share_info_type = pack.ComposedType([
48 ('share_data', share_data_type),
49 ('bits', bitcoin_data.FloatingIntegerType()),
50 ('timestamp', pack.IntType(32)),
53 share1a_type = pack.ComposedType([
54 ('header', bitcoin_data.block_header_type),
55 ('share_info', share_info_type),
56 ('merkle_branch', bitcoin_data.merkle_branch_type),
59 share1b_type = pack.ComposedType([
60 ('header', bitcoin_data.block_header_type),
61 ('share_info', share_info_type),
62 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
67 small_block_header_type = pack.ComposedType([
68 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
69 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
70 ('timestamp', pack.IntType(32)),
71 ('bits', bitcoin_data.FloatingIntegerType()),
72 ('nonce', pack.IntType(32)),
75 new_share_data_type = pack.ComposedType([
76 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
77 ('coinbase', pack.VarStrType()),
78 ('nonce', pack.IntType(32)),
79 ('pubkey_hash', pack.IntType(160)),
80 ('subsidy', pack.IntType(64)),
81 ('donation', pack.IntType(16)),
82 ('stale_info', pack.IntType(8)), # 0 nothing, 253 orphan, 254 doa
85 new_share_info_type = pack.ComposedType([
86 ('share_data', new_share_data_type),
87 ('max_bits', bitcoin_data.FloatingIntegerType()),
88 ('bits', bitcoin_data.FloatingIntegerType()),
89 ('timestamp', pack.IntType(32)),
92 new_share1a_type = pack.ComposedType([
93 ('min_header', small_block_header_type),
94 ('share_info', new_share_info_type),
95 ('hash_link', hash_link_type),
96 ('merkle_branch', bitcoin_data.merkle_branch_type),
99 new_share1b_type = pack.ComposedType([
100 ('min_header', small_block_header_type),
101 ('share_info', new_share_info_type),
102 ('hash_link', hash_link_type),
103 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
113 share_type = pack.ComposedType([
114 ('type', pack.VarIntType()),
115 ('contents', pack.VarStrType()),
119 __slots__ = 'header share_info merkle_branch other_txs timestamp share_data previous_hash target pow_hash header_hash hash time_seen peer net new_script max_target'.split(' ')
122 def from_share(cls, share, net):
123 if share['type'] == 0:
124 res = cls(net, **share1a_type.unpack(share['contents']))
125 if not (res.pow_hash > res.header['bits'].target):
126 raise ValueError('invalid share type')
128 elif share['type'] == 1:
129 share1b = share1b_type.unpack(share['contents'])
130 res = cls(net, merkle_branch=bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
131 if not (res.pow_hash <= res.header['bits'].target):
132 raise ValueError('invalid share type')
134 elif share['type'] == 2:
135 res = NewShare(net, **new_share1a_type.unpack(share['contents']))
136 if not (res.pow_hash > res.header['bits'].target):
137 raise ValueError('invalid share type')
139 elif share['type'] == 3:
140 share1b = new_share1b_type.unpack(share['contents'])
141 res = NewShare(net, merkle_branch=bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
142 if not (res.pow_hash <= res.header['bits'].target):
143 raise ValueError('invalid share type')
146 raise ValueError('unknown share type: %r' % (share['type'],))
148 def __init__(self, net, header, share_info, merkle_branch, other_txs=None):
151 if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_branch:
152 raise ValueError('merkle_branch and other_txs do not match')
154 if len(merkle_branch) > 16:
155 raise ValueError('merkle_branch too long!')
158 self.share_info = share_info
159 self.merkle_branch = merkle_branch
161 self.share_data = self.share_info['share_data']
162 self.target = self.max_target = self.share_info['bits'].target
163 self.timestamp = self.share_info['timestamp']
164 if self.timestamp > net.SWITCH_TIME + 60*60:
165 raise ValueError('old share an hour after switch time')
167 if len(self.share_data['new_script']) > 100:
168 raise ValueError('new_script too long!')
169 if script.get_sigop_count(self.share_data['new_script']) > 1:
170 raise ValueError('too many sigops!')
171 self.new_script = self.share_data['new_script']
173 self.previous_hash = self.share_data['previous_share_hash']
175 if len(self.share_data['nonce']) > 100:
176 raise ValueError('nonce too long!')
178 if len(self.share_data['coinbase']) > 100:
179 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
181 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
182 self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(header))
184 self.hash = bitcoin_data.hash256(share1a_type.pack(self.as_share1a()))
186 if self.pow_hash > self.target:
187 print 'hash %x' % self.pow_hash
188 print 'targ %x' % self.target
189 raise ValueError('not enough work!')
191 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
192 raise ValueError('other_txs provided when not a block solution')
193 if other_txs is None and self.pow_hash <= self.header['bits'].target:
194 raise ValueError('other_txs not provided when a block solution')
196 self.other_txs = other_txs
199 self.time_seen = time.time()
203 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
205 def check(self, tracker):
206 share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.net)
207 if share_info != self.share_info:
208 raise ValueError('share difficulty invalid')
210 if bitcoin_data.check_merkle_branch(bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)), 0, self.merkle_branch) != self.header['merkle_root']:
211 raise ValueError('''gentx doesn't match header via merkle_branch''')
214 if self.pow_hash > self.header['bits'].target: # share1a
215 return dict(type=0, contents=share1a_type.pack(self.as_share1a()))
216 elif self.pow_hash <= self.header['bits'].target: # share1b
217 if self.other_txs is None:
218 raise ValueError('share does not contain all txs')
219 return dict(type=1, contents=share1b_type.pack(dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)))
221 raise AssertionError()
223 def as_share1a(self):
224 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
226 def as_block(self, tracker):
227 if self.other_txs is None:
228 raise ValueError('share does not contain all txs')
230 share_info, gentx = generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.net)
231 assert share_info == self.share_info
233 return dict(header=self.header, txs=[gentx] + self.other_txs)
235 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False):
237 near = tracker.shares[previous_share_hash]
238 far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
239 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
240 time = near.timestamp - far.timestamp
243 return attempts//time
245 def get_average_stale_prop(tracker, share_hash, lookbehind):
246 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] in [253, 254])
247 return stales/(lookbehind + stales)
249 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
251 def generate_transaction(tracker, share_data, block_target, desired_timestamp, net):
252 previous_share_hash = share_data['previous_share_hash']
253 new_script = share_data['new_script']
254 subsidy = share_data['subsidy']
255 donation = share_data['donation']
256 assert 0 <= donation <= 65535
258 if len(share_data['coinbase']) > 100:
259 raise ValueError('coinbase too long!')
261 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
263 chain_length = getattr(net, 'REAL_CHAIN_LENGTH_FUNC', lambda _: net.REAL_CHAIN_LENGTH)(previous_share.timestamp if previous_share is not None else None)
265 height, last = tracker.get_height_and_last(previous_share_hash)
266 assert height >= chain_length or last is None
267 if height < net.TARGET_LOOKBEHIND:
268 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
270 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net.TARGET_LOOKBEHIND)
271 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
272 pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
273 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
274 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
276 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
277 max_att = net.SPREAD * attempts_to_block
279 this_att = min(bitcoin_data.target_to_average_attempts(bits.target), max_att)
280 other_weights, other_total_weight, other_donation_weight = tracker.get_cumulative_weights(previous_share_hash, min(height, chain_length), 65535*max(0, max_att - this_att))
281 assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
282 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
283 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
285 # 1 satoshi is always donated so that a list of p2pool generated blocks can be easily found by looking at the donation address
286 amounts = dict((script, (subsidy-1)*(199*weight)//(200*total_weight)) for (script, weight) in weights.iteritems())
287 amounts[new_script] = amounts.get(new_script, 0) + (subsidy-1)//200
288 amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + (subsidy-1)*(199*donation_weight)//(200*total_weight)
289 amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra satoshis :P
291 if sum(amounts.itervalues()) != subsidy:
293 if any(x < 0 for x in amounts.itervalues()):
296 dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
297 dests = dests[-4000:] # block length limit, unlikely to ever be hit
300 share_data=share_data,
302 timestamp=math.clip(desired_timestamp, (previous_share.timestamp - 60, previous_share.timestamp + 60)) if previous_share is not None else desired_timestamp,
305 return share_info, dict(
308 previous_output=None,
310 script=share_data['coinbase'].ljust(2, '\x00'),
312 tx_outs=[dict(value=0, script='\x20' + pack.IntType(256).pack(bitcoin_data.hash256(share_info_type.pack(share_info))))] + [dict(value=amounts[script], script=script) for script in dests if amounts[script]],
316 ref_type = pack.ComposedType([
317 ('identifier', pack.FixedStrType(64//8)),
318 ('share_info', new_share_info_type),
321 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
323 def new_generate_transaction(tracker, share_data, block_target, desired_timestamp, desired_target, net):
324 previous_share = tracker.shares[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
326 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
327 assert height >= net.REAL_CHAIN_LENGTH or last is None
328 if height < net.TARGET_LOOKBEHIND:
329 pre_target3 = net.MAX_TARGET
331 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True)
332 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
333 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
334 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
335 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
336 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
338 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
339 min(height, net.REAL_CHAIN_LENGTH),
340 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
342 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
344 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
345 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
346 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
347 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
349 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
352 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
355 share_data=share_data,
358 timestamp=math.clip(desired_timestamp, (
359 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
360 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
361 )) if previous_share is not None else desired_timestamp,
364 return share_info, dict(
367 previous_output=None,
369 script=share_data['coinbase'].ljust(2, '\x00'),
371 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]] + [dict(
373 script='\x20' + pack.IntType(256).pack(bitcoin_data.hash256(ref_type.pack(dict(
374 identifier=net.IDENTIFIER,
375 share_info=share_info,
381 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
382 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))
383 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
384 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
387 class NewShare(object):
388 __slots__ = 'net min_header share_info hash_link merkle_branch other_txs hash share_data max_target target timestamp previous_hash new_script gentx_hash header pow_hash header_hash time_seen peer'.split(' ')
390 def __init__(self, net, min_header, share_info, hash_link, merkle_branch, other_txs=None):
391 if len(share_info['share_data']['coinbase']) > 100:
392 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
394 if len(merkle_branch) > 16:
395 raise ValueError('merkle_branch too long!')
397 if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_branch([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_branch:
398 raise ValueError('merkle_branch and other_txs do not match')
400 assert not hash_link['extra_data'], repr(hash_link['extra_data'])
403 self.min_header = min_header
404 self.share_info = share_info
405 self.hash_link = hash_link
406 self.merkle_branch = merkle_branch
407 self.other_txs = other_txs
409 self.hash = bitcoin_data.hash256(share_type.pack(self.as_share(block_hint=other_txs is not None)))
410 self.share_data = self.share_info['share_data']
411 self.max_target = self.share_info['max_bits'].target
412 self.target = self.share_info['bits'].target
413 self.timestamp = self.share_info['timestamp']
414 self.previous_hash = self.share_data['previous_share_hash']
415 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
416 if self.timestamp < net.SWITCH_TIME - 60*60:
417 raise ValueError('new share an hour before switch time')
419 self.gentx_hash = check_hash_link(
421 pack.IntType(256).pack(bitcoin_data.hash256(ref_type.pack(dict(
422 identifier=net.IDENTIFIER,
423 share_info=share_info,
424 )))) + pack.IntType(32).pack(0),
425 gentx_before_refhash,
427 merkle_root = bitcoin_data.check_merkle_branch(self.gentx_hash, 0, merkle_branch)
428 self.header = dict(min_header, merkle_root=merkle_root)
429 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
430 self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
432 if self.pow_hash > self.target:
433 print 'hash %x' % self.pow_hash
434 print 'targ %x' % self.target
435 raise ValueError('not enough work!')
437 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
438 raise ValueError('other_txs provided when not a block solution')
439 if other_txs is None and self.pow_hash <= self.header['bits'].target:
440 raise ValueError('other_txs not provided when a block solution')
443 self.time_seen = time.time()
447 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
449 def check(self, tracker):
450 share_info, gentx = new_generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
451 if share_info != self.share_info:
452 raise ValueError('share difficulty invalid')
453 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
454 raise ValueError('''gentx doesn't match hash_link''')
456 def as_share(self, block_hint=None):
457 if block_hint is None:
458 block_hint = self.pow_hash <= self.header['bits'].target
459 if not block_hint: # share1a
460 return dict(type=2, contents=new_share1a_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, merkle_branch=self.merkle_branch)))
462 if self.other_txs is None:
463 raise ValueError('share does not contain all txs')
464 return dict(type=3, contents=new_share1b_type.pack(dict(min_header=self.min_header, share_info=self.share_info, hash_link=self.hash_link, other_txs=self.other_txs)))
466 def as_block(self, tracker):
467 if self.other_txs is None:
468 raise ValueError('share does not contain all txs')
470 share_info, gentx = new_generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.net)
471 assert share_info == self.share_info
473 return dict(header=self.header, txs=[gentx] + self.other_txs)
475 class OkayTracker(forest.Tracker):
476 def __init__(self, net, my_share_hashes, my_doa_share_hashes):
477 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
478 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
479 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
482 self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
483 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
484 my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
485 my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
486 my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 253 else 0,
487 my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 254 else 0,
489 self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
491 self.get_cumulative_weights = skiplists.WeightsSkipList(self)
493 def attempt_verify(self, share):
494 if share.hash in self.verified.shares:
496 height, last = self.get_height_and_last(share.hash)
497 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
498 raise AssertionError()
502 log.err(None, 'Share check failed:')
505 self.verified.add(share)
508 def think(self, block_rel_height_func, previous_block, bits):
512 # make 'unverified heads' set?
513 # for each overall head, attempt verification
514 # if it fails, attempt on parent, and repeat
515 # if no successful verification because of lack of parents, request parent
517 for head in set(self.heads) - set(self.verified.heads):
518 head_height, last = self.get_height_and_last(head)
520 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
521 if self.attempt_verify(share):
523 if share.hash in self.heads:
528 self.shares[random.choice(list(self.reverse_shares[last]))].peer,
530 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
531 min(x.target for x in self.get_chain(head, min(head_height, 5))),
534 assert bad not in self.verified.shares
535 assert bad in self.heads
540 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
541 for head in list(self.verified.heads):
542 head_height, last_hash = self.verified.get_height_and_last(head)
543 last_height, last_last_hash = self.get_height_and_last(last_hash)
544 # XXX review boundary conditions
545 want = max(self.net.CHAIN_LENGTH - head_height, 0)
546 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
548 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
549 for share in self.get_chain(last_hash, get):
550 if not self.attempt_verify(share):
552 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
554 self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer,
556 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
557 min(x.target for x in self.get_chain(head, min(head_height, 5))),
561 decorated_tails = sorted((self.score(max(self.verified.tails[tail_hash], key=self.verified.get_height), block_rel_height_func), tail_hash) for tail_hash in self.verified.tails) # XXX using get_height here is quite possibly incorrect and vulnerable
563 print len(decorated_tails), 'tails:'
564 for score, tail_hash in decorated_tails:
565 print format_hash(tail_hash), score
566 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
568 # decide best verified head
569 decorated_heads = sorted(((
570 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
571 #self.verified.shares[h].peer is None,
572 (self.verified.shares[h].header['previous_block'], self.verified.shares[h].header['bits']) == (previous_block, bits) or self.verified.shares[h].peer is None,
573 -self.verified.shares[h].time_seen,
574 ), h) for h in self.verified.tails.get(best_tail, []))
576 print len(decorated_heads), 'heads. Top 10:'
577 for score, head_hash in decorated_heads[-10:]:
578 print ' ', format_hash(head_hash), format_hash(self.verified.shares[head_hash].previous_hash), score
579 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
583 for i in xrange(1000):
585 for share_hash, tail in self.heads.iteritems():
586 if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
589 if self.shares[share_hash].time_seen > time.time() - 300:
592 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
595 to_remove.add(share_hash)
598 for share_hash in to_remove:
599 self.remove(share_hash)
600 if share_hash in self.verified.shares:
601 self.verified.remove(share_hash)
602 #print "_________", to_remove
605 for i in xrange(1000):
607 for tail, heads in self.tails.iteritems():
608 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
610 for aftertail in self.reverse_shares.get(tail, set()):
611 if len(self.reverse_shares[self.shares[aftertail].previous_hash]) > 1: # XXX
614 to_remove.add(aftertail)
617 # if removed from this, it must be removed from verified
619 for aftertail in to_remove:
620 if self.shares[aftertail].previous_hash not in self.tails:
621 print "erk", aftertail, self.shares[aftertail].previous_hash
623 self.remove(aftertail)
624 if aftertail in self.verified.shares:
625 self.verified.remove(aftertail)
627 #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
630 best_share = self.verified.shares[best]
631 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:
633 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
634 best = best_share.previous_hash
636 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
637 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
639 timestamp_cutoff = int(time.time()) - 24*60*60
640 target_cutoff = 2**256-1
643 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))
644 for peer, hash, ts, targ in desired:
645 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
647 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff and targ <= target_cutoff]
649 def score(self, share_hash, block_rel_height_func):
650 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
652 head_height = self.verified.get_height(share_hash)
653 if head_height < self.net.CHAIN_LENGTH:
654 return head_height, None
656 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
658 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
659 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
661 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)
666 return '%08x' % (x % 2**32)
668 class ShareStore(object):
669 def __init__(self, prefix, net):
670 self.filename = prefix
671 self.dirname = os.path.dirname(os.path.abspath(prefix))
672 self.filename = os.path.basename(os.path.abspath(prefix))
674 self.known = None # will be filename -> set of share hashes, set of verified hashes
675 self.known_desired = None
677 def get_shares(self):
678 if self.known is not None:
679 raise AssertionError()
681 filenames, next = self.get_filenames_and_next()
682 for filename in filenames:
683 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
684 with open(filename, 'rb') as f:
687 type_id_str, data_hex = line.strip().split(' ')
688 type_id = int(type_id_str)
694 verified_hash = int(data_hex, 16)
695 yield 'verified_hash', verified_hash
696 verified_hashes.add(verified_hash)
698 share = Share.from_share(share_type.unpack(data_hex.decode('hex')), self.net)
700 share_hashes.add(share.hash)
702 raise NotImplementedError("share type %i" % (type_id,))
704 log.err(None, "Error while reading saved shares, continuing where left off:")
706 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
708 def _add_line(self, line):
709 filenames, next = self.get_filenames_and_next()
710 if filenames and os.path.getsize(filenames[-1]) < 10e6:
711 filename = filenames[-1]
715 with open(filename, 'ab') as f:
720 def add_share(self, share):
721 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
722 if share.hash in share_hashes:
725 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
726 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
727 share_hashes.add(share.hash)
728 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
729 share_hashes.add(share.hash)
731 def add_verified_hash(self, share_hash):
732 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
733 if share_hash in verified_hashes:
736 filename = self._add_line("%i %x" % (2, share_hash))
737 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
738 verified_hashes.add(share_hash)
739 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
740 verified_hashes.add(share_hash)
742 def get_filenames_and_next(self):
743 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())
744 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)))
746 def forget_share(self, share_hash):
747 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
748 if share_hash in share_hashes:
749 share_hashes.remove(share_hash)
752 def forget_verified_share(self, share_hash):
753 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
754 if share_hash in verified_hashes:
755 verified_hashes.remove(share_hash)
758 def check_remove(self):
760 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
761 #print filename, len(share_hashes) + len(verified_hashes)
762 if not share_hashes and not verified_hashes:
763 to_remove.add(filename)
764 for filename in to_remove:
765 self.known.pop(filename)
766 self.known_desired.pop(filename)
768 print "REMOVED", filename