1 from __future__ import division
7 from twisted.python import log
9 from p2pool.util import math
10 from p2pool.bitcoin import data as bitcoin_data
11 from p2pool.util import memoize, expiring_dict
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!')
174 self.time_seen = time.time()
178 if self.other_txs is None:
179 raise ValueError('share does not contain all txs')
181 return dict(header=self.header, txs=[self.gentx] + self.other_txs)
183 def as_share1a(self):
184 return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
186 def as_share1b(self):
187 return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
189 def check(self, tracker, net):
191 if self.previous_share_hash is not None:
192 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):
193 raise ValueError('share from too far in the past!')
195 # XXX use adjusted time
196 if self.header['timestamp'] > time.time() + 2*60*60:
197 raise ValueError('share from too far in the future!')
199 gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
201 if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
202 raise ValueError('''gentx doesn't match header via merkle_branch''')
204 if self.other_txs is not None:
205 if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
206 raise ValueError('''gentx doesn't match header via other_txs''')
212 def flag_shared(self):
216 return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
218 class Share2(object):
219 '''Share with associated data'''
221 def __init__(self, share):
226 def flag_shared(self):
229 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
230 previous_share2 = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
232 chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
233 if len(chain) < net.TARGET_LOOKBEHIND:
234 target2 = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
236 attempts = sum(bitcoin_data.target_to_average_attempts(share.target2) for share in chain[:-1])
237 time = chain[0].timestamp - chain[-1].timestamp
240 attempts_per_second = attempts//time
241 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
242 pre_target2 = math.clip(pre_target, (previous_share2.target2*9//10, previous_share2.target2*11//10))
243 pre_target3 = math.clip(pre_target2, (0, 2**256//2**20 - 1))
244 target2 = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
245 print attempts_per_second//1000, 'KHASH'
246 #print 'TARGET', 2**256//target2, 2**256/pre_target
247 #print 'ATT', bitcoin_data.target_to_average_attempts(target2)//1000
250 attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
251 max_weight = net.SPREAD * attempts_to_block
254 class fake_share(object):
256 fake_share.new_script = new_script
257 fake_share.target2 = target2
260 for i, share in enumerate(itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH))):
261 weight = bitcoin_data.target_to_average_attempts(share.target2)
262 if weight > max_weight - total_weight:
263 weight = max_weight - total_weight
265 dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
266 total_weight += weight
268 if total_weight == max_weight:
271 amounts = dict((script, subsidy*(199*weight)//(200*total_weight)) for (script, weight) in dest_weights.iteritems())
272 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*1//200
273 amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
275 dests = sorted(amounts.iterkeys(), key=lambda script: (script == new_script, script))
276 assert dests[-1] == new_script
281 previous_output=None,
283 script=coinbase_type.pack(dict(
284 identifier=net.IDENTIFIER,
286 previous_share_hash=previous_share_hash,
292 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
298 class OkayTracker(bitcoin_data.Tracker):
299 def __init__(self, net):
300 bitcoin_data.Tracker.__init__(self)
302 self.verified = bitcoin_data.Tracker()
304 self.okay_cache = {} # hash -> height
306 def attempt_verify(self, share):
307 height, last = self.get_height_and_last(share.hash)
308 if height < self.net.CHAIN_LENGTH and last is not None:
309 raise AssertionError()
310 if share.hash in self.verified.shares:
313 share.check(self, self.net)
316 print 'Share check failed:'
321 self.verified.add(share)
328 # make 'unverified heads' set?
329 # for each overall head, attempt verification
330 # if it fails, attempt on parent, and repeat
331 # if no successful verification because of lack of parents, request parent
332 for head in self.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 max(0, head_height - self.net.CHAIN_LENGTH)):
336 if self.attempt_verify(share):
339 desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
341 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
342 for head in list(self.verified.heads):
343 head_height, last_hash = self.verified.get_height_and_last(head)
344 last_height, last_last_hash = self.get_height_and_last(last_hash)
345 # XXX review boundary conditions
346 want = max(self.net.CHAIN_LENGTH - head_height, 0)
347 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
349 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
350 for share in itertools.islice(self.get_chain_known(last_hash), get):
351 if not self.attempt_verify(share):
353 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
354 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
356 # decide best verified head
357 scores = sorted(self.verified.heads, key=lambda h: self.score(h, ht))
362 print '%x'%a, self.score(a, ht)
365 for share_hash in scores[:-5]:
366 if self.shares[share_hash].time_seen > time.time() - 30:
368 self.remove(share_hash)
369 self.verified.remove(share_hash)
371 best = scores[-1] if scores else None
375 @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
376 def score(self, share_hash, ht):
377 head_height, last = self.verified.get_height_and_last(share_hash)
381 # XXX should only look past a certain share, not at recent ones
382 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
383 # XXX this must go in the opposite direction for max_height to make sense
384 for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
385 max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
386 attempts += bitcoin_data.target_to_average_attempts(share.target2)
387 this_score = attempts//(ht.get_highest_height() - max_height + 1)
388 #this_score = -(ht.get_highest_height() - max_height + 1)//attempts
389 if this_score > score2:
391 res = (min(head_height, self.net.CHAIN_LENGTH), score2, -self.verified.shares[share_hash].time_seen)
396 class Mainnet(bitcoin_data.Mainnet):
397 SHARE_PERIOD = 5 # seconds
398 CHAIN_LENGTH = 24*60*60//5 # shares
399 TARGET_LOOKBEHIND = 200 # shares
401 SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
402 IDENTIFIER = '7452839666e1f8f8'.decode('hex')
403 PREFIX = '2d4224bf18c87b87'.decode('hex')
404 ADDRS_TABLE = 'addrs'
407 class Testnet(bitcoin_data.Testnet):
408 SHARE_PERIOD = 1 # seconds
409 CHAIN_LENGTH = 24*60*60//5 # shares
410 TARGET_LOOKBEHIND = 200 # shares
412 SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
413 IDENTIFIER = '1ae3479e4eb6700a'.decode('hex')
414 PREFIX = 'd19778c812754854'.decode('hex')
415 ADDRS_TABLE = 'addrs_testnet'