1 from __future__ import division
7 from twisted.python import log
9 from p2pool.bitcoin import data as bitcoin_data
10 from p2pool.bitcoin import script
11 from p2pool.util import memoize, expiring_dict, math, skiplist
14 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
15 ('side', bitcoin_data.StructType('<B')), # enum?
16 ('hash', bitcoin_data.HashType()),
20 share_data_type = bitcoin_data.ComposedType([
21 ('previous_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
22 ('target', bitcoin_data.FloatingIntegerType()),
23 ('nonce', bitcoin_data.VarStrType()),
27 coinbase_type = bitcoin_data.ComposedType([
28 ('identifier', bitcoin_data.FixedStrType(8)),
29 ('share_data', share_data_type),
32 share_info_type = bitcoin_data.ComposedType([
33 ('share_data', share_data_type),
34 ('new_script', bitcoin_data.VarStrType()),
35 ('subsidy', bitcoin_data.StructType('<Q')),
39 share1a_type = bitcoin_data.ComposedType([
40 ('header', bitcoin_data.block_header_type),
41 ('share_info', share_info_type),
42 ('merkle_branch', merkle_branch_type),
45 share1b_type = bitcoin_data.ComposedType([
46 ('header', bitcoin_data.block_header_type),
47 ('share_info', share_info_type),
48 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
51 def calculate_merkle_branch(txs, index):
52 hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
54 while len(hash_list) > 1:
57 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
59 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
61 for (left, left_f, left_l), (right, right_f, right_l) in
62 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
65 assert hash_list[0][1]
66 assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
68 return hash_list[0][2]
70 def check_merkle_branch(tx, branch):
71 hash_ = bitcoin_data.tx_type.hash256(tx)
74 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
76 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
79 def gentx_to_share_info(gentx):
81 share_data=coinbase_type.unpack(gentx['tx_ins'][0]['script'])['share_data'],
82 subsidy=sum(tx_out['value'] for tx_out in gentx['tx_outs']),
83 new_script=gentx['tx_outs'][-1]['script'],
86 def share_info_to_gentx(share_info, block_target, tracker, net):
87 return generate_transaction(
89 previous_share_hash=share_info['share_data']['previous_share_hash'],
90 new_script=share_info['new_script'],
91 subsidy=share_info['subsidy'],
92 nonce=share_info['share_data']['nonce'],
93 block_target=block_target,
99 highest_block_on_arrival = None
102 def from_block(cls, block):
103 return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
106 def from_share1a(cls, share1a):
107 return cls(**share1a)
110 def from_share1b(cls, share1b):
111 return cls(**share1b)
113 def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
114 if merkle_branch is None and other_txs is None:
115 raise ValueError('need either merkle_branch or other_txs')
116 if other_txs is not None:
117 new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
118 if merkle_branch is not None:
119 if merke_branch != new_merkle_branch:
120 raise ValueError('invalid merkle_branch and other_txs')
121 merkle_branch = new_merkle_branch
123 if len(merkle_branch) > 16:
124 raise ValueError('merkle_branch too long!')
127 self.previous_block = header['previous_block']
128 self.share_info = share_info
129 self.merkle_branch = merkle_branch
130 self.other_txs = other_txs
132 self.timestamp = self.header['timestamp']
134 self.share_data = self.share_info['share_data']
135 self.new_script = self.share_info['new_script']
136 self.subsidy = self.share_info['subsidy']
138 if len(self.new_script) > 100:
139 raise ValueError('new_script too long!')
141 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
142 self.target = self.share_data['target']
143 self.nonce = self.share_data['nonce']
145 if len(self.nonce) > 20:
146 raise ValueError('nonce too long!')
148 self.bitcoin_hash = bitcoin_data.block_header_type.hash256(header)
149 self.hash = share1a_type.hash256(self.as_share1a())
151 if self.bitcoin_hash > self.target:
152 print 'hash', hex(self.bitcoin_hash)
153 print 'targ', hex(self.target)
154 raise ValueError('not enough work!')
156 if script.get_sigop_count(self.new_script) > 1:
157 raise ValueError('too many sigops!')
159 self.time_seen = time.time()
162 def as_block(self, tracker, net):
163 if self.other_txs is None:
164 raise ValueError('share does not contain all txs')
166 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
168 return dict(header=self.header, txs=[gentx] + self.other_txs)
170 def as_share1a(self):
171 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
173 def as_share1b(self):
174 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
176 def check(self, tracker, now, net):
178 if self.previous_share_hash is not None:
179 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):
180 raise ValueError('share from too far in the past!')
182 if self.header['timestamp'] > now + 2*60*60:
183 raise ValueError('share from too far in the future!')
185 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
187 if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
188 raise ValueError('''gentx doesn't match header via merkle_branch''')
190 if self.other_txs is not None:
191 if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
192 raise ValueError('''gentx doesn't match header via other_txs''')
194 if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
195 raise ValueError('''block size too large''')
199 def flag_shared(self):
203 return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
205 def get_pool_attempts_per_second(tracker, previous_share_hash, net):
206 # XXX could be optimized to use nth_parent and cumulative_weights
207 chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
208 attempts = sum(bitcoin_data.target_to_average_attempts(share.target) for share in chain[:-1])
209 time = chain[0].timestamp - chain[-1].timestamp
212 return attempts//time
214 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
216 print "start generate_transaction"
217 height, last = tracker.get_height_and_last(previous_share_hash)
218 if height < net.TARGET_LOOKBEHIND:
219 target = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
221 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
222 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
223 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
224 pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
225 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
226 target = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
228 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
229 max_weight = net.SPREAD * attempts_to_block
232 class fake_share(object):
234 fake_share.new_script = new_script
235 fake_share.target = target
239 for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
240 weight = bitcoin_data.target_to_average_attempts(share.target)
241 if weight > max_weight - total_weight:
242 weight = max_weight - total_weight
244 dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
245 total_weight += weight
247 if total_weight == max_weight:
251 this_weight = min(bitcoin_data.target_to_average_attempts(target), max_weight)
252 other_weights, other_weights_total = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), max(0, max_weight - this_weight))
253 dest_weights, total_weight = math.add_dicts([{new_script: this_weight}, other_weights]), this_weight + other_weights_total
254 total_weight = sum(dest_weights.itervalues())
256 amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
257 amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
258 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*2//400
259 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
260 if sum(amounts.itervalues()) != subsidy:
262 if any(x < 0 for x in amounts.itervalues()):
265 pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
266 pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
268 dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
269 assert dests[-1] == new_script
272 print "end generate_transaction"
277 previous_output=None,
279 script=coinbase_type.pack(dict(
280 identifier=net.IDENTIFIER,
282 previous_share_hash=previous_share_hash,
288 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
294 class OkayTracker(bitcoin_data.Tracker):
295 def __init__(self, net):
296 bitcoin_data.Tracker.__init__(self)
298 self.verified = bitcoin_data.Tracker()
300 self.get_cumulative_weights = skiplist.WeightsSkipList(self)
302 def attempt_verify(self, share, now):
303 if share.hash in self.verified.shares:
305 height, last = self.get_height_and_last(share.hash)
306 if height < self.net.CHAIN_LENGTH and last is not None:
307 raise AssertionError()
309 share.check(self, now, self.net)
312 print 'Share check failed:'
317 self.verified.add(share)
320 def think(self, ht, previous_block, now):
327 # make 'unverified heads' set?
328 # for each overall head, attempt verification
329 # if it fails, attempt on parent, and repeat
330 # if no successful verification because of lack of parents, request parent
332 for head in set(self.heads) - set(self.verified.heads):
333 head_height, last = self.get_height_and_last(head)
335 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))):
336 if self.attempt_verify(share, now):
338 if share.hash in self.heads:
342 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
344 assert bad not in self.verified.shares
345 assert bad in self.heads
348 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
349 for head in list(self.verified.heads):
350 head_height, last_hash = self.verified.get_height_and_last(head)
351 last_height, last_last_hash = self.get_height_and_last(last_hash)
352 # XXX review boundary conditions
353 want = max(self.net.CHAIN_LENGTH - head_height, 0)
354 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
356 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
357 for share in itertools.islice(self.get_chain_known(last_hash), get):
358 if not self.attempt_verify(share, now):
360 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
361 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
364 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
365 # decide best verified head
366 scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (self.verified.get_work(h), ht.get_min_height(self.verified.shares[h].previous_block), -self.verified.shares[h].time_seen))
370 #print len(self.verified.tails.get(best_tail, []))
372 # print ' ', '%x'%a, self.score(a, ht)
374 for share_hash in scores[:-5]:
375 if self.shares[share_hash].time_seen > time.time() - 30:
377 self.remove(share_hash)
378 self.verified.remove(share_hash)
380 #for tail, heads in list(self.tails.iteritems()):
381 # if min(self.get_height(head) for head in heads) > 2*net.CHAIN_LENGTH + 10:
383 # self.verified.remove(tail)
385 best = scores[-1] if scores else None
388 best_share = self.verified.shares[best]
389 if ht.get_min_height(best_share.header['previous_block']) < ht.get_min_height(previous_block) and best_share.bitcoin_hash != previous_block and best_share.peer is not None:
391 print "stale detected!"
392 best = best_share.previous_hash
399 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
400 def score(self, share_hash, ht):
401 head_height, last = self.verified.get_height_and_last(share_hash)
405 # XXX should only look past a certain share, not at recent ones
406 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
407 # XXX this must go in the opposite direction for max_height to make sense
408 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
409 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
410 attempts += bitcoin_data.target_to_average_attempts(share.target)
411 this_score = attempts//(ht.get_highest_height() - max_height + 1)
412 if this_score > score2:
414 return min(head_height, self.net.CHAIN_LENGTH), score2
417 class Mainnet(bitcoin_data.Mainnet):
418 SHARE_PERIOD = 5 # seconds
419 CHAIN_LENGTH = 24*60*60//5 # shares
420 TARGET_LOOKBEHIND = 200 # shares
422 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
423 IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
424 PREFIX = '2472ef181efcd37b'.decode('hex')
425 ADDRS_TABLE = 'addrs'
427 MAX_TARGET = 2**256//2**32 - 1
429 class Testnet(bitcoin_data.Testnet):
430 SHARE_PERIOD = 1 # seconds
431 CHAIN_LENGTH = 24*60*60//5 # shares
432 TARGET_LOOKBEHIND = 200 # shares
434 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
435 IDENTIFIER = '5fc2be2d4f0d6bfb'.decode('hex')
436 PREFIX = '3f6057a15036f441'.decode('hex')
437 ADDRS_TABLE = 'addrs_testnet'
439 MAX_TARGET = 2**256//2**20 - 1