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
13 class CompressedList(bitcoin_data.Type):
14 def __init__(self, inner):
18 values, file = bitcoin_data.ListType(self.inner).read(file)
19 if values != sorted(set(values)):
20 raise ValueError('invalid values')
21 references, file = bitcoin_data.ListType(bitcoin_data.VarIntType()).read(file)
22 return [values[reference] for reference in references], file
24 def write(self, file, item):
25 values = sorted(set(item))
26 values_map = dict((value, i) for i, value in enumerate(values))
27 file = bitcoin_data.ListType(self.inner).write(file, values)
28 return bitcoin_data.ListType(bitcoin_data.VarIntType()).write(file, [values_map[subitem] for subitem in item])
31 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
32 ('side', bitcoin_data.StructType('<B')), # enum?
33 ('hash', bitcoin_data.HashType()),
37 share_data_type = bitcoin_data.ComposedType([
38 ('previous_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
39 ('target2', bitcoin_data.FloatingIntegerType()),
40 ('nonce', bitcoin_data.VarStrType()),
44 coinbase_type = bitcoin_data.ComposedType([
45 ('identifier', bitcoin_data.FixedStrType(8)),
46 ('share_data', share_data_type),
49 share_info_type = bitcoin_data.ComposedType([
50 ('share_data', share_data_type),
51 ('new_script', bitcoin_data.VarStrType()),
52 ('subsidy', bitcoin_data.StructType('<Q')),
56 share1a_type = bitcoin_data.ComposedType([
57 ('header', bitcoin_data.block_header_type),
58 ('share_info', share_info_type),
59 ('merkle_branch', merkle_branch_type),
62 share1b_type = bitcoin_data.ComposedType([
63 ('header', bitcoin_data.block_header_type),
64 ('share_info', share_info_type),
65 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
68 shares_type = CompressedList(bitcoin_data.VarStrType())
70 def calculate_merkle_branch(txs, index):
71 hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
73 while len(hash_list) > 1:
76 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
78 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
80 for (left, left_f, left_l), (right, right_f, right_l) in
81 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
84 assert hash_list[0][1]
85 assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
87 return hash_list[0][2]
89 def check_merkle_branch(tx, branch):
90 hash_ = bitcoin_data.tx_type.hash256(tx)
93 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
95 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
98 def gentx_to_share_info(gentx):
100 share_data=coinbase_type.unpack(gentx['tx_ins'][0]['script'])['share_data'],
101 subsidy=sum(tx_out['value'] for tx_out in gentx['tx_outs']),
102 new_script=gentx['tx_outs'][-1]['script'],
105 def share_info_to_gentx(share_info, block_target, tracker, net):
106 return generate_transaction(
108 previous_share_hash=share_info['share_data']['previous_share_hash'],
109 new_script=share_info['new_script'],
110 subsidy=share_info['subsidy'],
111 nonce=share_info['share_data']['nonce'],
112 block_target=block_target,
121 def from_block(cls, block):
122 return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
125 def from_share1a(cls, share1a):
126 return cls(**share1a)
129 def from_share1b(cls, share1b):
130 return cls(**share1b)
132 def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
133 if merkle_branch is None and other_txs is None:
134 raise ValueError('need either merkle_branch or other_txs')
135 if other_txs is not None:
136 new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
137 if merkle_branch is not None:
138 if merke_branch != new_merkle_branch:
139 raise ValueError('invalid merkle_branch and other_txs')
140 merkle_branch = new_merkle_branch
142 if len(merkle_branch) > 16:
143 raise ValueError('merkle_branch too long!')
146 self.share_info = share_info
147 self.merkle_branch = merkle_branch
148 self.other_txs = other_txs
150 self.timestamp = self.header['timestamp']
152 self.share_data = self.share_info['share_data']
153 self.new_script = self.share_info['new_script']
154 self.subsidy = self.share_info['subsidy']
156 if len(self.new_script) > 100:
157 raise ValueError('new_script too long!')
159 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
160 self.target2 = self.share_data['target2']
161 self.nonce = self.share_data['nonce']
163 if len(self.nonce) > 20:
164 raise ValueError('nonce too long!')
166 self.hash = bitcoin_data.block_header_type.hash256(header)
168 if self.hash > self.target2:
169 print 'hash', hex(self.hash)
170 print 'targ', hex(self.target2)
171 raise ValueError('not enough work!')
173 if script.get_sigop_count(self.new_script) > 1:
174 raise ValueError('too many sigops!')
176 self.time_seen = time.time()
180 if self.other_txs is None:
181 raise ValueError('share does not contain all txs')
183 return dict(header=self.header, txs=[self.gentx] + self.other_txs)
185 def as_share1a(self):
186 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
188 def as_share1b(self):
189 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
191 def check(self, tracker, now, net):
193 if self.previous_share_hash is not None:
194 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):
195 raise ValueError('share from too far in the past!')
197 if self.header['timestamp'] > now + 2*60*60:
198 raise ValueError('share from too far in the future!')
200 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
202 if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
203 raise ValueError('''gentx doesn't match header via merkle_branch''')
205 if self.other_txs is not None:
206 if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
207 raise ValueError('''gentx doesn't match header via other_txs''')
209 if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
210 raise ValueError('''block size too large''')
216 def flag_shared(self):
220 return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
222 class Share2(object):
223 '''Share with associated data'''
225 def __init__(self, share):
230 def flag_shared(self):
233 def get_pool_attempts_per_second(tracker, previous_share_hash, net):
234 chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
235 attempts = sum(bitcoin_data.target_to_average_attempts(share.target2) for share in chain[:-1])
236 time = chain[0].timestamp - chain[-1].timestamp
239 return attempts//time
241 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
243 print "start generate_transaction"
244 height, last = tracker.get_height_and_last(previous_share_hash)
245 if height < net.TARGET_LOOKBEHIND:
246 target2 = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
248 attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
249 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
250 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
251 pre_target2 = math.clip(pre_target, (previous_share.target2*9//10, previous_share.target2*11//10))
252 pre_target3 = math.clip(pre_target2, (0, 2**256//2**32 - 1))
253 target2 = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
255 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
256 max_weight = net.SPREAD * attempts_to_block
259 class fake_share(object):
261 fake_share.new_script = new_script
262 fake_share.target2 = target2
266 for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
267 weight = bitcoin_data.target_to_average_attempts(share.target2)
268 if weight > max_weight - total_weight:
269 weight = max_weight - total_weight
271 dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
272 total_weight += weight
274 if total_weight == max_weight:
278 this_weight = min(bitcoin_data.target_to_average_attempts(target2), max_weight)
279 dest_weights = math.add_dicts([{new_script: this_weight}, tracker.get_cumulative_weights(previous_share_hash, min(tracker.get_height_and_last(previous_share_hash)[0], net.CHAIN_LENGTH), max(0, max_weight - this_weight))[0]])
280 total_weight = sum(dest_weights.itervalues())
281 #assert dest_weights == dest_weights2
283 amounts = dict((script, subsidy*(198*weight)//(200*total_weight)) for (script, weight) in dest_weights.iteritems())
284 amounts[net_script] = amounts.get(new_script, 0) + subsidy*1//200
285 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*1//200
286 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
287 if sum(amounts.itervalues()) != subsidy:
289 if any(x < 0 for x in amounts.itervalues()):
292 pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
293 pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
295 dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
296 assert dests[-1] == new_script
299 print "end generate_transaction"
304 previous_output=None,
306 script=coinbase_type.pack(dict(
307 identifier=net.IDENTIFIER,
309 previous_share_hash=previous_share_hash,
315 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
321 class OkayTracker(bitcoin_data.Tracker):
322 def __init__(self, net):
323 bitcoin_data.Tracker.__init__(self)
325 self.verified = bitcoin_data.Tracker()
327 self.get_cumulative_weights = skiplist.WeightsSkipList(self)
329 def attempt_verify(self, share, now):
330 if share.hash in self.verified.shares:
332 height, last = self.get_height_and_last(share.hash)
333 if height < self.net.CHAIN_LENGTH and last is not None:
334 raise AssertionError()
336 share.check(self, now, self.net)
339 print 'Share check failed:'
344 self.verified.add(share)
347 def think(self, ht, now):
354 # make 'unverified heads' set?
355 # for each overall head, attempt verification
356 # if it fails, attempt on parent, and repeat
357 # if no successful verification because of lack of parents, request parent
359 for head in set(self.heads) - set(self.verified.heads):
360 head_height, last = self.get_height_and_last(head)
362 for share in itertools.islice(self.get_chain_known(head), None if last is None else max(0, head_height - self.net.CHAIN_LENGTH)):
363 if self.attempt_verify(share, now):
365 if share.hash in self.heads:
369 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
371 assert bad not in self.verified.shares
372 assert bad in self.heads
375 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
376 for head in list(self.verified.heads):
377 head_height, last_hash = self.verified.get_height_and_last(head)
378 last_height, last_last_hash = self.get_height_and_last(last_hash)
379 # XXX review boundary conditions
380 want = max(self.net.CHAIN_LENGTH - head_height, 0)
381 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
383 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
384 for share in itertools.islice(self.get_chain_known(last_hash), get):
385 if not self.attempt_verify(share, now):
387 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
388 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
390 # decide best verified head
391 scores = sorted(self.verified.heads, key=lambda h: self.score(h, ht))
395 print ' ', '%x'%a, self.score(a, ht)
397 for share_hash in scores[:-5]:
398 if self.shares[share_hash].time_seen > time.time() - 30:
400 self.remove(share_hash)
401 self.verified.remove(share_hash)
403 best = scores[-1] if scores else None
410 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
411 def score(self, share_hash, ht):
412 head_height, last = self.verified.get_height_and_last(share_hash)
416 # XXX should only look past a certain share, not at recent ones
417 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
418 # XXX this must go in the opposite direction for max_height to make sense
419 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
420 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
421 attempts += bitcoin_data.target_to_average_attempts(share.target2)
422 this_score = attempts//(ht.get_highest_height() - max_height + 1)
423 #this_score = -(ht.get_highest_height() - max_height + 1)//attempts
424 if this_score > score2:
426 res = (min(head_height, self.net.CHAIN_LENGTH), score2, -self.verified.shares[share_hash].time_seen)
431 class Mainnet(bitcoin_data.Mainnet):
432 SHARE_PERIOD = 5 # seconds
433 CHAIN_LENGTH = 24*60*60//5 # shares
434 TARGET_LOOKBEHIND = 200 # shares
436 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
437 IDENTIFIER = '7452839666e1f8f8'.decode('hex')
438 PREFIX = '2d4224bf18c87b87'.decode('hex')
439 ADDRS_TABLE = 'addrs'
442 class Testnet(bitcoin_data.Testnet):
443 SHARE_PERIOD = 1 # seconds
444 CHAIN_LENGTH = 24*60*60//5 # shares
445 TARGET_LOOKBEHIND = 200 # shares
447 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
448 IDENTIFIER = '1ae3479e4eb6700a'.decode('hex')
449 PREFIX = 'd19778c812754854'.decode('hex')
450 ADDRS_TABLE = 'addrs_testnet'