1 from __future__ import division
3 TRANSITION_TIME = 1322561023
10 from twisted.python import log
13 from p2pool import skiplists
14 from p2pool.bitcoin import data as bitcoin_data, script, networks
15 from p2pool.util import memoize, expiring_dict, math
18 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
19 ('side', bitcoin_data.StructType('<B')), # enum?
20 ('hash', bitcoin_data.HashType()),
24 share_data_type = bitcoin_data.ComposedType([
25 ('previous_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
26 ('target', bitcoin_data.FloatingIntegerType()),
27 ('nonce', bitcoin_data.VarStrType()),
31 coinbase_type = bitcoin_data.ComposedType([
32 ('identifier', bitcoin_data.FixedStrType(8)),
33 ('share_data', share_data_type),
36 share_info_type = bitcoin_data.ComposedType([
37 ('share_data', share_data_type),
38 ('new_script', bitcoin_data.VarStrType()),
39 ('subsidy', bitcoin_data.StructType('<Q')),
43 share1a_type = bitcoin_data.ComposedType([
44 ('header', bitcoin_data.block_header_type),
45 ('share_info', share_info_type),
46 ('merkle_branch', merkle_branch_type),
49 share1b_type = bitcoin_data.ComposedType([
50 ('header', bitcoin_data.block_header_type),
51 ('share_info', share_info_type),
52 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
55 new_share_data_type = bitcoin_data.ComposedType([
56 ('previous_share_hash', bitcoin_data.PossiblyNoneType(0, bitcoin_data.HashType())),
57 ('coinbase', bitcoin_data.VarStrType()),
58 ('nonce', bitcoin_data.VarStrType()),
59 ('new_script', bitcoin_data.VarStrType()),
60 ('subsidy', bitcoin_data.StructType('<Q')),
61 ('donation', bitcoin_data.StructType('<H')),
62 ('stale_frac', bitcoin_data.StructType('<B')),
65 new_share_info_type = bitcoin_data.ComposedType([
66 ('new_share_data', new_share_data_type),
67 ('target', bitcoin_data.FloatingIntegerType()),
68 ('timestamp', bitcoin_data.StructType('<I')),
71 new_share1a_type = bitcoin_data.ComposedType([
72 ('header', bitcoin_data.block_header_type),
73 ('share_info', new_share_info_type),
74 ('merkle_branch', bitcoin_data.merkle_branch_type),
77 new_share1b_type = bitcoin_data.ComposedType([
78 ('header', bitcoin_data.block_header_type),
79 ('share_info', new_share_info_type),
80 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
87 new_share_type = bitcoin_data.ComposedType([
88 ('type', bitcoin_data.VarIntType()),
89 ('contents', bitcoin_data.VarStrType()),
92 def calculate_merkle_branch(txs, index):
93 hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
95 while len(hash_list) > 1:
98 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
100 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
102 for (left, left_f, left_l), (right, right_f, right_l) in
103 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
106 assert hash_list[0][1]
107 assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
109 return hash_list[0][2]
111 def check_merkle_branch(tx, branch):
112 hash_ = bitcoin_data.tx_type.hash256(tx)
115 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
117 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
120 def share_info_to_gentx(share_info, block_target, tracker, net):
121 return generate_transaction(
123 previous_share_hash=share_info['share_data']['previous_share_hash'],
124 new_script=share_info['new_script'],
125 subsidy=share_info['subsidy'],
126 nonce=share_info['share_data']['nonce'],
127 block_target=block_target,
132 donation = int(0.005*65535 + 0.5)
135 def from_share1a(cls, share1a, net):
136 return cls(net, **share1a)
139 def from_share1b(cls, share1b, net):
140 return cls(net, **share1b)
142 __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce pow_hash header_hash hash time_seen peer'.split(' ')
144 def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
145 if merkle_branch is None and other_txs is None:
146 raise ValueError('need either merkle_branch or other_txs')
147 if other_txs is not None:
148 new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
149 if merkle_branch is not None:
150 if merke_branch != new_merkle_branch:
151 raise ValueError('invalid merkle_branch and other_txs')
152 merkle_branch = new_merkle_branch
154 if len(merkle_branch) > 16:
155 raise ValueError('merkle_branch too long!')
158 self.previous_block = header['previous_block']
159 self.share_info = share_info
160 self.merkle_branch = merkle_branch
161 self.other_txs = other_txs
163 self.timestamp = self.header['timestamp']
165 self.share_data = self.share_info['share_data']
166 self.new_script = self.share_info['new_script']
167 self.subsidy = self.share_info['subsidy']
169 if len(self.new_script) > 100:
170 raise ValueError('new_script too long!')
172 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
173 self.target = self.share_data['target']
174 self.nonce = self.share_data['nonce']
176 if len(self.nonce) > 100:
177 raise ValueError('nonce too long!')
179 self.pow_hash = net.BITCOIN_POW_FUNC(header)
180 self.header_hash = bitcoin_data.block_header_type.hash256(header)
182 if net.BITCOIN_POW_FUNC == bitcoin_data.block_header_type.scrypt:
184 self.hash = share1a_type.scrypt(self.as_share1a())
186 self.hash = share1a_type.hash256(self.as_share1a())
188 if self.pow_hash > self.target:
189 print 'hash %x' % self.pow_hash
190 print 'targ %x' % self.target
191 raise ValueError('not enough work!')
193 if script.get_sigop_count(self.new_script) > 1:
194 raise ValueError('too many sigops!')
197 self.time_seen = time.time()
200 def as_block(self, tracker, net):
201 if self.other_txs is None:
202 raise ValueError('share does not contain all txs')
204 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
206 return dict(header=self.header, txs=[gentx] + self.other_txs)
208 def as_share1a(self):
209 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
211 def as_share1b(self):
212 if self.other_txs is None:
213 raise ValueError('share does not contain all txs')
215 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
217 def check(self, tracker, now, net):
218 if self.header['timestamp'] >= TRANSITION_TIME:
219 raise AssertionError('transitioning...')
221 if self.previous_share_hash is not None:
222 if self.header['timestamp'] <= math.median((s.timestamp for s in itertools.islice(tracker.get_chain_to_root(self.previous_share_hash), 11)), use_float=False):
223 raise ValueError('share from too far in the past!')
225 if self.header['timestamp'] > now + 2*60*60:
226 raise ValueError('share from too far in the future!')
228 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
230 if len(gentx['tx_ins'][0]['script']) > 100:
231 raise ValueError('coinbase too large! %i bytes' % (len(gentx['tx_ins'][0]['script']),))
233 if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
234 raise ValueError('''gentx doesn't match header via merkle_branch''')
236 if self.other_txs is not None:
237 if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
238 raise ValueError('''gentx doesn't match header via other_txs''')
240 if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
241 raise ValueError('block size too large')
244 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
246 class NewShare(Share):
247 __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce pow_hash header_hash hash time_seen peer donation'.split(' ')
250 def from_share(cls, share, net):
251 if share['type'] == 0:
252 res = cls.from_share1a(new_share1a_type.unpack(share['contents']), net)
253 if not (res.pow_hash > res.header['target']):
254 raise ValueError('invalid share type')
256 elif share['type'] == 1:
257 res = cls.from_share1b(new_share1b_type.unpack(share['contents']), net)
258 if not (res.pow_hash <= res.header['target']):
259 raise ValueError('invalid share type')
262 raise ValueError('unknown share type: %r' % (share['type'],))
265 if self.pow_hash > self.header['target']: # new_share1a
266 return dict(type=0, contents=new_share1a_type.pack(self.as_share1a()))
267 elif self.pow_hash <= self.header['target']: # new_share1b
268 return dict(type=1, contents=new_share1b_type.pack(self.as_share1b()))
270 raise AssertionError()
272 def __init__(self, net, header, share_info, merkle_branch=None, other_txs=None):
273 if merkle_branch is None and other_txs is None:
274 raise ValueError('need either merkle_branch or other_txs')
275 if other_txs is not None:
276 new_merkle_branch = bitcoin_data.calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
277 if merkle_branch is not None:
278 if merke_branch != new_merkle_branch:
279 raise ValueError('invalid merkle_branch and other_txs')
280 merkle_branch = new_merkle_branch
282 if len(merkle_branch) > 16:
283 raise ValueError('merkle_branch too long!')
286 self.previous_block = header['previous_block']
287 self.share_info = share_info
288 self.merkle_branch = merkle_branch
289 self.other_txs = other_txs
291 self.share_data = self.share_info['new_share_data']
292 self.target = self.share_info['target']
293 self.timestamp = self.share_info['timestamp']
295 self.new_script = self.share_data['new_script']
296 self.subsidy = self.share_data['subsidy']
297 self.donation = self.share_data['donation']
299 if len(self.new_script) > 100:
300 raise ValueError('new_script too long!')
302 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
303 self.nonce = self.share_data['nonce']
305 if len(self.nonce) > 100:
306 raise ValueError('nonce too long!')
308 if len(self.share_data['coinbase']) > 100:
309 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_data['coinbase']),))
311 self.pow_hash = net.BITCOIN_POW_FUNC(header)
312 self.header_hash = bitcoin_data.block_header_type.hash256(header)
314 self.hash = new_share1a_type.hash256(self.as_share1a())
316 if self.pow_hash > self.target:
317 print 'hash %x' % self.pow_hash
318 print 'targ %x' % self.target
319 raise ValueError('not enough work!')
321 if script.get_sigop_count(self.new_script) > 1:
322 raise ValueError('too many sigops!')
325 self.time_seen = time.time()
328 def check(self, tracker, now, net):
329 if self.header['timestamp'] < TRANSITION_TIME:
330 raise AssertionError('transitioning...')
332 share_info, gentx = new_generate_transaction(tracker, self.share_info['new_share_data'], self.header['target'], self.share_info['timestamp'], net)
333 if share_info != self.share_info:
334 raise ValueError('share difficulty invalid')
336 if bitcoin_data.check_merkle_branch(gentx, 0, self.merkle_branch) != self.header['merkle_root']:
337 raise ValueError('''gentx doesn't match header via merkle_branch''')
339 def as_block(self, tracker, net):
340 if self.other_txs is None:
341 raise ValueError('share does not contain all txs')
343 share_info, gentx = new_generate_transaction(tracker, self.share_info['new_share_data'], self.header['target'], self.share_info['timestamp'], net)
344 assert share_info == self.share_info
346 return dict(header=self.header, txs=[gentx] + self.other_txs)
348 def get_pool_attempts_per_second(tracker, previous_share_hash, net, dist=None):
350 dist = net.TARGET_LOOKBEHIND
351 near = tracker.shares[previous_share_hash]
352 far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
353 attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash)
354 time = near.timestamp - far.timestamp
357 return attempts//time
359 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
360 donation = int(0.005*65535 + 0.5)
362 height, last = tracker.get_height_and_last(previous_share_hash)
363 assert height >= net.CHAIN_LENGTH or last is None
364 if height < net.TARGET_LOOKBEHIND:
365 target = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
367 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
368 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
369 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
370 pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
371 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
372 target = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
374 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
375 max_att = net.SPREAD * attempts_to_block
377 this_att = min(bitcoin_data.target_to_average_attempts(target), max_att)
378 other_weights, other_total_weight, other_donation_weight = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), 65535*max(0, max_att - this_att))
379 assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
380 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
381 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
383 total_weight -= donation_weight # ignore donation
386 amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in weights.iteritems())
387 amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
388 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*2//400
389 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
391 amounts = dict((script, subsidy*(398*weight)//(400*total_weight)) for (script, weight) in weights.iteritems())
392 amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
393 amounts[new_script] = amounts.get(new_script, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
395 if sum(amounts.itervalues()) != subsidy:
397 if any(x < 0 for x in amounts.itervalues()):
400 pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
401 pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
403 dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
404 assert dests[-1] == new_script
407 previous_share_hash=previous_share_hash,
413 share_data=share_data,
414 new_script=new_script,
418 return share_info, dict(
421 previous_output=None,
423 script=coinbase_type.pack(dict(
424 identifier=net.IDENTIFIER,
425 share_data=share_data,
428 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
432 def new_generate_transaction(tracker, new_share_data, block_target, desired_timestamp, net):
433 previous_share_hash = new_share_data['previous_share_hash']
434 new_script = new_share_data['new_script']
435 subsidy = new_share_data['subsidy']
436 donation = new_share_data['donation']
437 assert 0 <= donation <= 65535
439 if len(new_share_data['coinbase']) > 100:
440 raise ValueError('coinbase too long!')
442 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
444 height, last = tracker.get_height_and_last(previous_share_hash)
445 assert height >= net.CHAIN_LENGTH or last is None
446 if height < net.TARGET_LOOKBEHIND:
447 target = bitcoin_data.FloatingInteger.from_target_upper_bound(net.MAX_TARGET)
449 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
450 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
451 pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
452 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
453 target = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
455 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
456 max_att = net.SPREAD * attempts_to_block
458 this_att = min(bitcoin_data.target_to_average_attempts(target), max_att)
459 other_weights, other_total_weight, other_donation_weight = tracker.get_cumulative_weights(previous_share_hash, min(height, getattr(net, 'CHAIN_LENGTH2', net.CHAIN_LENGTH)), 65535*max(0, max_att - this_att))
460 assert other_total_weight == sum(other_weights.itervalues()) + other_donation_weight, (other_total_weight, sum(other_weights.itervalues()) + other_donation_weight)
461 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
462 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
464 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
466 # 1 satoshi is always donated so that a list of p2pool generated blocks can be easily found by looking at the donation address
467 amounts = dict((script, (subsidy-1)*(199*weight)//(200*total_weight)) for (script, weight) in weights.iteritems())
468 amounts[new_script] = amounts.get(new_script, 0) + (subsidy-1)//200
469 amounts[SCRIPT] = amounts.get(SCRIPT, 0) + (subsidy-1)*(199*donation_weight)//(200*total_weight)
470 amounts[SCRIPT] = amounts.get(SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra satoshis :P
472 if sum(amounts.itervalues()) != subsidy:
474 if any(x < 0 for x in amounts.itervalues()):
477 dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
478 dests = dests[-4000:] # block length limit, unlikely to ever be hit
481 new_share_data=new_share_data,
483 timestamp=math.clip(desired_timestamp, (previous_share.timestamp - 60, previous_share.timestamp + 60)) if previous_share is not None else desired_timestamp,
486 return share_info, dict(
489 previous_output=None,
491 script=new_share_data['coinbase'].ljust(2, '\x00'),
493 tx_outs=[dict(value=0, script='\x20' + bitcoin_data.HashType().pack(new_share_info_type.hash256(share_info)))] + [dict(value=amounts[script], script=script) for script in dests if amounts[script]],
498 class OkayTracker(bitcoin_data.Tracker):
499 def __init__(self, net):
500 bitcoin_data.Tracker.__init__(self)
502 self.verified = bitcoin_data.Tracker()
503 self.verified.get_nth_parent_hash = self.get_nth_parent_hash # self is a superset of self.verified
505 self.get_cumulative_weights = skiplists.WeightsSkipList(self)
507 def add(self, share, known_verified=False):
508 bitcoin_data.Tracker.add(self, share)
510 self.verified.add(share)
512 def attempt_verify(self, share, now):
513 if share.hash in self.verified.shares:
515 height, last = self.get_height_and_last(share.hash)
516 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
517 raise AssertionError()
519 share.check(self, now, self.net)
521 log.err(None, 'Share check failed:')
524 self.verified.add(share)
527 def think(self, ht, previous_block, now):
531 # make 'unverified heads' set?
532 # for each overall head, attempt verification
533 # if it fails, attempt on parent, and repeat
534 # if no successful verification because of lack of parents, request parent
536 for head in set(self.heads) - set(self.verified.heads):
537 head_height, last = self.get_height_and_last(head)
539 for share in itertools.islice(self.get_chain_known(head), None if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
540 if self.attempt_verify(share, now):
542 if share.hash in self.heads:
546 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
548 assert bad not in self.verified.shares
549 assert bad in self.heads
554 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
555 for head in list(self.verified.heads):
556 head_height, last_hash = self.verified.get_height_and_last(head)
557 last_height, last_last_hash = self.get_height_and_last(last_hash)
558 # XXX review boundary conditions
559 want = max(self.net.CHAIN_LENGTH - head_height, 0)
560 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
562 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
563 for share in itertools.islice(self.get_chain_known(last_hash), get):
564 if not self.attempt_verify(share, now):
566 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
567 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
570 best_tail = max(self.verified.tails, key=lambda h: self.score(max(self.verified.tails[h], key=self.verified.get_height), ht)) if self.verified.tails else None
571 # decide best verified head
572 scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
573 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
574 #self.verified.shares[h].peer is None,
575 ht.get_min_height(self.verified.shares[h].previous_block),
576 -self.verified.shares[h].time_seen
581 print len(self.verified.tails), "chain tails and", len(self.verified.tails.get(best_tail, [])), 'chain heads. Top 10 tails:'
584 for h in scores[-10:]:
585 print ' ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
586 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
587 self.verified.shares[h].peer is None,
588 ht.get_min_height(self.verified.shares[h].previous_block),
589 -self.verified.shares[h].time_seen
594 for i in xrange(1000):
596 for share_hash, tail in self.heads.iteritems():
597 if share_hash in scores[-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))
640 best = scores[-1] if scores else None
643 best_share = self.verified.shares[best]
644 if ht.get_min_height(best_share.header['previous_block']) < ht.get_min_height(previous_block) and best_share.header_hash != previous_block and best_share.peer is not None:
646 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
647 best = best_share.previous_hash
651 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
652 def score(self, share_hash, ht):
653 head_height, last = self.verified.get_height_and_last(share_hash)
657 share2_hash = self.verified.get_nth_parent_hash(share_hash, min(self.net.CHAIN_LENGTH//2, head_height//2)) if last is not None else share_hash
658 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
659 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
660 attempts += bitcoin_data.target_to_average_attempts(share.target)
661 this_score = attempts//(ht.get_highest_height() - max_height + 1)
662 if this_score > score2:
664 return min(head_height, self.net.CHAIN_LENGTH), score2
669 return '%08x' % (x % 2**32)
671 class ShareStore(object):
672 def __init__(self, prefix, net):
673 self.filename = prefix
674 self.dirname = os.path.dirname(os.path.abspath(prefix))
675 self.filename = os.path.basename(os.path.abspath(prefix))
677 self.known = None # will be filename -> set of share hashes, set of verified hashes
679 def get_shares(self):
680 if self.known is not None:
681 raise AssertionError()
683 filenames, next = self.get_filenames_and_next()
684 for filename in filenames:
685 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
686 with open(filename, 'rb') as f:
689 type_id_str, data_hex = line.strip().split(' ')
690 type_id = int(type_id_str)
692 share = Share.from_share1a(share1a_type.unpack(data_hex.decode('hex')), self.net)
694 share_hashes.add(share.hash)
696 share = Share.from_share1b(share1b_type.unpack(data_hex.decode('hex')), self.net)
698 share_hashes.add(share.hash)
700 verified_hash = int(data_hex, 16)
701 yield 'verified_hash', verified_hash
702 verified_hashes.add(verified_hash)
704 share = NewShare.from_share(new_share_type.unpack(data_hex.decode('hex')), self.net)
706 share_hashes.add(share.hash)
708 raise NotImplementedError("share type %i" % (type_id,))
710 log.err(None, "Error while reading saved shares, continuing where left off:")
713 def _add_line(self, line):
714 filenames, next = self.get_filenames_and_next()
715 if filenames and os.path.getsize(filenames[-1]) < 10e6:
716 filename = filenames[-1]
720 with open(filename, 'ab') as f:
725 def add_share(self, share):
726 if isinstance(share, NewShare):
727 type_id, data = 5, new_share_type.pack(share.as_share())
728 elif share.pow_hash <= share.header['target']:
729 type_id, data = 1, share1b_type.pack(share.as_share1b())
731 type_id, data = 0, share1a_type.pack(share.as_share1a())
732 filename = self._add_line("%i %s" % (type_id, data.encode('hex')))
733 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
734 share_hashes.add(share.hash)
736 def add_verified_hash(self, share_hash):
737 filename = self._add_line("%i %x" % (2, share_hash))
738 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
739 verified_hashes.add(share_hash)
741 def get_filenames_and_next(self):
742 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())
743 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)))
745 def forget_share(self, share_hash):
746 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
747 if share_hash in share_hashes:
748 share_hashes.remove(share_hash)
751 def forget_verified_share(self, share_hash):
752 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
753 if share_hash in verified_hashes:
754 verified_hashes.remove(share_hash)
757 def check_remove(self):
759 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
760 #print filename, len(share_hashes) + len(verified_hashes)
761 if not share_hashes and not verified_hashes:
762 to_remove.add(filename)
763 for filename in to_remove:
764 self.known.pop(filename)
766 print "REMOVED", filename
768 class BitcoinMainnet(networks.BitcoinMainnet):
769 SHARE_PERIOD = 10 # seconds
770 CHAIN_LENGTH = 24*60*60//5 # shares
771 CHAIN_LENGTH2 = 24*60*60//10//2 # shares
772 TARGET_LOOKBEHIND = 200 # shares
774 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
775 IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
776 PREFIX = '2472ef181efcd37b'.decode('hex')
779 MAX_TARGET = 2**256//2**32 - 1
783 class BitcoinTestnet(networks.BitcoinTestnet):
784 SHARE_PERIOD = 1 # seconds
785 CHAIN_LENGTH = 24*60*60//5 # shares
786 CHAIN_LENGTH2 = 24*60*60//10//2 # shares
787 TARGET_LOOKBEHIND = 200 # shares
789 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
790 IDENTIFIER = '5fc2be2d4f0d6bfb'.decode('hex')
791 PREFIX = '3f6057a15036f441'.decode('hex')
792 NAME = 'bitcoin_testnet'
794 MAX_TARGET = 2**256//2**32 - 1
798 class NamecoinMainnet(networks.NamecoinMainnet):
799 SHARE_PERIOD = 10 # seconds
800 CHAIN_LENGTH = 24*60*60//10 # shares
801 TARGET_LOOKBEHIND = 3600//10 # shares
803 SCRIPT = '41043da5beb73f8f18cede1a41b0ed953123f1342b8e0216ab5bf71ed3e024201b4017f472bddb6041f17978d89ed8f8ed84f9e726b0bca80cacf96347c7153e8df0ac'.decode('hex')
804 IDENTIFIER = 'd5b1192062c4c454'.decode('hex')
805 PREFIX = 'b56f3d0fb24fc982'.decode('hex')
808 MAX_TARGET = 2**256//2**32 - 1
812 class NamecoinTestnet(networks.NamecoinTestnet):
813 SHARE_PERIOD = 1 # seconds
814 CHAIN_LENGTH = 24*60*60//5 # shares
815 TARGET_LOOKBEHIND = 200 # shares
817 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
818 IDENTIFIER = '8dd303d014a01a60'.decode('hex')
819 PREFIX = '4d6581d24f51acbf'.decode('hex')
820 NAME = 'namecoin_testnet'
822 MAX_TARGET = 2**256//2**20 - 1
826 class IxcoinMainnet(networks.IxcoinMainnet):
827 SHARE_PERIOD = 10 # seconds
828 CHAIN_LENGTH = 24*60*60//10 # shares
829 TARGET_LOOKBEHIND = 3600//10 # shares
831 SCRIPT = '41043da5beb73f8f18cede1a41b0ed953123f1342b8e0216ab5bf71ed3e024201b4017f472bddb6041f17978d89ed8f8ed84f9e726b0bca80cacf96347c7153e8df0ac'.decode('hex')
832 IDENTIFIER = '27b564116e2a2666'.decode('hex')
833 PREFIX = '9dd6c4a619401f2f'.decode('hex')
836 MAX_TARGET = 2**256//2**32 - 1
840 class IxcoinTestnet(networks.IxcoinTestnet):
841 SHARE_PERIOD = 1 # seconds
842 CHAIN_LENGTH = 24*60*60//5 # shares
843 TARGET_LOOKBEHIND = 200 # shares
845 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
846 IDENTIFIER = '7430cbeb01249e44'.decode('hex')
847 PREFIX = '7cfffda946709c1f'.decode('hex')
848 NAME = 'ixcoin_testnet'
850 MAX_TARGET = 2**256//2**20 - 1
854 class I0coinMainnet(networks.I0coinMainnet):
855 SHARE_PERIOD = 10 # seconds
856 CHAIN_LENGTH = 24*60*60//10 # shares
857 TARGET_LOOKBEHIND = 3600//10 # shares
859 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
860 IDENTIFIER = 'b32e3f10c2ff221b'.decode('hex')
861 PREFIX = '6155537ed977a3b5'.decode('hex')
864 MAX_TARGET = 2**256//2**32 - 1
868 class I0coinTestnet(networks.I0coinTestnet):
869 SHARE_PERIOD = 1 # seconds
870 CHAIN_LENGTH = 24*60*60//5 # shares
871 TARGET_LOOKBEHIND = 200 # shares
873 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
874 IDENTIFIER = '7712c1a8181b5f2e'.decode('hex')
875 PREFIX = '792d2e7d770fbe68'.decode('hex')
876 NAME = 'i0coin_testnet'
878 MAX_TARGET = 2**256//2**20 - 1
882 class SolidcoinMainnet(networks.SolidcoinMainnet):
884 CHAIN_LENGTH = 24*60*60//10 # shares
885 TARGET_LOOKBEHIND = 3600//10 # shares
887 SCRIPT = bitcoin_data.pubkey_hash_to_script2(bitcoin_data.address_to_pubkey_hash('sMKZ1yxHETxPYKh4Z2anWnwZDJZU7ztroy', networks.SolidcoinMainnet))
888 IDENTIFIER = '9cc9c421cca258cd'.decode('hex')
889 PREFIX = 'c059125b8070f00a'.decode('hex')
892 MAX_TARGET = 2**256//2**32 - 1
896 class LitecoinMainnet(networks.LitecoinMainnet):
897 SHARE_PERIOD = 10 # seconds
898 CHAIN_LENGTH = 24*60*60//5 # shares
899 CHAIN_LENGTH2 = 24*60*60//10//2 # shares
900 TARGET_LOOKBEHIND = 200 # shares
902 SCRIPT = None # no fee
903 IDENTIFIER = 'e037d5b8c6923410'.decode('hex')
904 PREFIX = '7208c1a53ef629b0'.decode('hex')
907 MAX_TARGET = 2**256//2**20 - 1
911 class LitecoinTestnet(networks.LitecoinTestnet):
912 SHARE_PERIOD = 1 # seconds
913 CHAIN_LENGTH = 24*60*60//5 # shares
914 TARGET_LOOKBEHIND = 200 # shares
916 SCRIPT = None # no fee
917 IDENTIFIER = 'cca5e24ec6408b1e'.decode('hex')
918 PREFIX = 'ad9614f6466a39cf'.decode('hex')
919 NAME = 'litecoin_testnet'
921 MAX_TARGET = 2**256//2**17 - 1
925 nets = dict((net.NAME, net) for net in set([BitcoinMainnet, BitcoinTestnet, NamecoinMainnet, NamecoinTestnet, IxcoinMainnet, IxcoinTestnet, I0coinMainnet, I0coinTestnet, SolidcoinMainnet, LitecoinMainnet, LitecoinTestnet]))