1 from __future__ import division
7 from twisted.python import log
9 from p2pool.bitcoin import data as bitcoin_data
10 from p2pool.util import memoize, expiring_dict, math, skiplist
12 class CompressedList(bitcoin_data.Type):
13 def __init__(self, inner):
17 values, file = bitcoin_data.ListType(self.inner).read(file)
18 if values != sorted(set(values)):
19 raise ValueError('invalid values')
20 references, file = bitcoin_data.ListType(bitcoin_data.VarIntType()).read(file)
21 return [values[reference] for reference in references], file
23 def write(self, file, item):
24 values = sorted(set(item))
25 values_map = dict((value, i) for i, value in enumerate(values))
26 file = bitcoin_data.ListType(self.inner).write(file, values)
27 return bitcoin_data.ListType(bitcoin_data.VarIntType()).write(file, [values_map[subitem] for subitem in item])
30 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
31 ('side', bitcoin_data.StructType('<B')), # enum?
32 ('hash', bitcoin_data.HashType()),
36 share_data_type = bitcoin_data.ComposedType([
37 ('previous_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
38 ('target2', bitcoin_data.FloatingIntegerType()),
39 ('nonce', bitcoin_data.VarStrType()),
43 coinbase_type = bitcoin_data.ComposedType([
44 ('identifier', bitcoin_data.FixedStrType(8)),
45 ('share_data', share_data_type),
48 share_info_type = bitcoin_data.ComposedType([
49 ('share_data', share_data_type),
50 ('new_script', bitcoin_data.VarStrType()),
51 ('subsidy', bitcoin_data.StructType('<Q')),
55 share1a_type = bitcoin_data.ComposedType([
56 ('header', bitcoin_data.block_header_type),
57 ('share_info', share_info_type),
58 ('merkle_branch', merkle_branch_type),
61 share1b_type = bitcoin_data.ComposedType([
62 ('header', bitcoin_data.block_header_type),
63 ('share_info', share_info_type),
64 ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
67 shares_type = CompressedList(bitcoin_data.VarStrType())
69 def calculate_merkle_branch(txs, index):
70 hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
72 while len(hash_list) > 1:
75 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
77 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
79 for (left, left_f, left_l), (right, right_f, right_l) in
80 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
83 assert hash_list[0][1]
84 assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
86 return hash_list[0][2]
88 def check_merkle_branch(tx, branch):
89 hash_ = bitcoin_data.tx_type.hash256(tx)
92 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
94 hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
97 def gentx_to_share_info(gentx):
99 share_data=coinbase_type.unpack(gentx['tx_ins'][0]['script'])['share_data'],
100 subsidy=sum(tx_out['value'] for tx_out in gentx['tx_outs']),
101 new_script=gentx['tx_outs'][-1]['script'],
104 def share_info_to_gentx(share_info, block_target, tracker, net):
105 return generate_transaction(
107 previous_share_hash=share_info['share_data']['previous_share_hash'],
108 new_script=share_info['new_script'],
109 subsidy=share_info['subsidy'],
110 nonce=share_info['share_data']['nonce'],
111 block_target=block_target,
120 def from_block(cls, block):
121 return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
124 def from_share1a(cls, share1a):
125 return cls(**share1a)
128 def from_share1b(cls, share1b):
129 return cls(**share1b)
131 def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
132 if merkle_branch is None and other_txs is None:
133 raise ValueError('need either merkle_branch or other_txs')
134 if other_txs is not None:
135 new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
136 if merkle_branch is not None:
137 if merke_branch != new_merkle_branch:
138 raise ValueError('invalid merkle_branch and other_txs')
139 merkle_branch = new_merkle_branch
141 if len(merkle_branch) > 16:
142 raise ValueError('merkle_branch too long!')
145 self.share_info = share_info
146 self.merkle_branch = merkle_branch
147 self.other_txs = other_txs
149 self.timestamp = self.header['timestamp']
151 self.share_data = self.share_info['share_data']
152 self.new_script = self.share_info['new_script']
153 self.subsidy = self.share_info['subsidy']
155 if len(self.new_script) > 100:
156 raise ValueError('new_script too long!')
158 self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
159 self.target2 = self.share_data['target2']
160 self.nonce = self.share_data['nonce']
162 if len(self.nonce) > 20:
163 raise ValueError('nonce too long!')
165 self.hash = bitcoin_data.block_header_type.hash256(header)
167 if self.hash > self.target2:
168 print 'hash', hex(self.hash)
169 print 'targ', hex(self.target2)
170 raise ValueError('not enough work!')
173 self.time_seen = time.time()
177 if self.other_txs is None:
178 raise ValueError('share does not contain all txs')
180 return dict(header=self.header, txs=[self.gentx] + self.other_txs)
182 def as_share1a(self):
183 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
185 def as_share1b(self):
186 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
188 def check(self, tracker, now, net):
190 if self.previous_share_hash is not None:
191 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):
192 raise ValueError('share from too far in the past!')
194 if self.header['timestamp'] > now + 2*60*60:
195 raise ValueError('share from too far in the future!')
197 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
199 if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
200 raise ValueError('''gentx doesn't match header via merkle_branch''')
202 if self.other_txs is not None:
203 if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
204 raise ValueError('''gentx doesn't match header via other_txs''')
210 def flag_shared(self):
214 return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
216 class Share2(object):
217 '''Share with associated data'''
219 def __init__(self, share):
224 def flag_shared(self):
227 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
228 chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
229 if len(chain) < net.TARGET_LOOKBEHIND:
230 target2 = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
232 previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
233 attempts = sum(bitcoin_data.target_to_average_attempts(share.target2) for share in chain[:-1])
234 time = chain[0].timestamp - chain[-1].timestamp
237 attempts_per_second = attempts//time
238 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
239 pre_target2 = math.clip(pre_target, (previous_share.target2*9//10, previous_share.target2*11//10))
240 pre_target3 = math.clip(pre_target2, (0, 2**256//2**20 - 1))
241 target2 = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
242 print attempts_per_second//1000, 'KHASH'
243 #print 'TARGET', 2**256//target2, 2**256/pre_target
244 #print 'ATT', bitcoin_data.target_to_average_attempts(target2)//1000
247 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
248 max_weight = net.SPREAD * attempts_to_block
251 class fake_share(object):
253 fake_share.new_script = new_script
254 fake_share.target2 = target2
258 for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
259 weight = bitcoin_data.target_to_average_attempts(share.target2)
260 if weight > max_weight - total_weight:
261 weight = max_weight - total_weight
263 dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
264 total_weight += weight
266 if total_weight == max_weight:
270 this_weight = min(bitcoin_data.target_to_average_attempts(target2), max_weight)
271 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]])
272 total_weight = sum(dest_weights.itervalues())
273 #assert dest_weights == dest_weights2
275 amounts = dict((script, subsidy*(199*weight)//(200*total_weight)) for (script, weight) in dest_weights.iteritems())
276 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*1//200
277 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
279 dests = sorted(amounts.iterkeys(), key=lambda script: (script == new_script, script))
280 assert dests[-1] == new_script
285 previous_output=None,
287 script=coinbase_type.pack(dict(
288 identifier=net.IDENTIFIER,
290 previous_share_hash=previous_share_hash,
296 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
302 class OkayTracker(bitcoin_data.Tracker):
303 def __init__(self, net):
304 bitcoin_data.Tracker.__init__(self)
306 self.verified = bitcoin_data.Tracker()
308 self.get_cumulative_weights = skiplist.WeightsSkipList(self)
310 def attempt_verify(self, share, now):
311 if share.hash in self.verified.shares:
313 height, last = self.get_height_and_last(share.hash)
314 if height < self.net.CHAIN_LENGTH and last is not None:
315 raise AssertionError()
317 share.check(self, now, self.net)
320 print 'Share check failed:'
325 self.verified.add(share)
328 def think(self, ht, now):
332 # make 'unverified heads' set?
333 # for each overall head, attempt verification
334 # if it fails, attempt on parent, and repeat
335 # if no successful verification because of lack of parents, request parent
336 for head in self.heads:
337 head_height, last = self.get_height_and_last(head)
339 for share in itertools.islice(self.get_chain_known(head), None if last is None else max(0, head_height - self.net.CHAIN_LENGTH)):
340 if self.attempt_verify(share, now):
344 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
346 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
347 for head in list(self.verified.heads):
348 head_height, last_hash = self.verified.get_height_and_last(head)
349 last_height, last_last_hash = self.get_height_and_last(last_hash)
350 # XXX review boundary conditions
351 want = max(self.net.CHAIN_LENGTH - head_height, 0)
352 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
354 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
355 for share in itertools.islice(self.get_chain_known(last_hash), get):
356 if not self.attempt_verify(share, now):
358 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
359 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
361 # decide best verified head
362 scores = sorted(self.verified.heads, key=lambda h: self.score(h, ht))
367 print '%x'%a, self.score(a, ht)
370 for share_hash in scores[:-5]:
371 if self.shares[share_hash].time_seen > time.time() - 30:
373 self.remove(share_hash)
374 self.verified.remove(share_hash)
376 best = scores[-1] if scores else None
380 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
381 def score(self, share_hash, ht):
382 head_height, last = self.verified.get_height_and_last(share_hash)
386 # XXX should only look past a certain share, not at recent ones
387 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
388 # XXX this must go in the opposite direction for max_height to make sense
389 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
390 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
391 attempts += bitcoin_data.target_to_average_attempts(share.target2)
392 this_score = attempts//(ht.get_highest_height() - max_height + 1)
393 #this_score = -(ht.get_highest_height() - max_height + 1)//attempts
394 if this_score > score2:
396 res = (min(head_height, self.net.CHAIN_LENGTH), score2, -self.verified.shares[share_hash].time_seen)
401 class Mainnet(bitcoin_data.Mainnet):
402 SHARE_PERIOD = 5 # seconds
403 CHAIN_LENGTH = 24*60*60//5 # shares
404 TARGET_LOOKBEHIND = 200 # shares
406 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
407 IDENTIFIER = '7452839666e1f8f8'.decode('hex')
408 PREFIX = '2d4224bf18c87b87'.decode('hex')
409 ADDRS_TABLE = 'addrs'
412 class Testnet(bitcoin_data.Testnet):
413 SHARE_PERIOD = 1 # seconds
414 CHAIN_LENGTH = 24*60*60//5 # shares
415 TARGET_LOOKBEHIND = 200 # shares
417 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
418 IDENTIFIER = '1ae3479e4eb6700a'.decode('hex')
419 PREFIX = 'd19778c812754854'.decode('hex')
420 ADDRS_TABLE = 'addrs_testnet'