49859c296d057a32df88fd57a5b18ded119d689d
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import itertools
4 import random
5 import time
6
7 from twisted.python import log
8
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
12
13
14 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
15     ('side', bitcoin_data.StructType('<B')), # enum?
16     ('hash', bitcoin_data.HashType()),
17 ]))
18
19
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()),
24 ])
25
26
27 coinbase_type = bitcoin_data.ComposedType([
28     ('identifier', bitcoin_data.FixedStrType(8)),
29     ('share_data', share_data_type),
30 ])
31
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')),
36 ])
37
38
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),
43 ])
44
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)),
49 ])
50
51 def calculate_merkle_branch(txs, index):
52     hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
53     
54     while len(hash_list) > 1:
55         hash_list = [
56             (
57                 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
58                 left_f or right_f,
59                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
60             )
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]])
63         ]
64     
65     assert hash_list[0][1]
66     assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
67     
68     return hash_list[0][2]
69
70 def check_merkle_branch(tx, branch):
71     hash_ = bitcoin_data.tx_type.hash256(tx)
72     for step in branch:
73         if not step['side']:
74             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
75         else:
76             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
77     return hash_
78
79 def gentx_to_share_info(gentx):
80     return dict(
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'],
84     )
85
86 def share_info_to_gentx(share_info, block_target, tracker, net):
87     return generate_transaction(
88         tracker=tracker,
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,
94         net=net,
95     )
96
97 class Share(object):
98     peer = None
99     highest_block_on_arrival = None
100     
101     @classmethod
102     def from_block(cls, block):
103         return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
104     
105     @classmethod
106     def from_share1a(cls, share1a):
107         return cls(**share1a)
108     
109     @classmethod
110     def from_share1b(cls, share1b):
111         return cls(**share1b)
112     
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
122         
123         if len(merkle_branch) > 16:
124             raise ValueError('merkle_branch too long!')
125         
126         self.header = header
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
131         
132         self.timestamp = self.header['timestamp']
133         
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']
137         
138         if len(self.new_script) > 100:
139             raise ValueError('new_script too long!')
140         
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']
144         
145         if len(self.nonce) > 20:
146             raise ValueError('nonce too long!')
147         
148         self.bitcoin_hash = bitcoin_data.block_header_type.hash256(header)
149         self.hash = share1a_type.hash256(self.as_share1a())
150         
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!')
155         
156         if script.get_sigop_count(self.new_script) > 1:
157             raise ValueError('too many sigops!')
158         
159         self.time_seen = time.time()
160         self.shared = False
161     
162     def as_block(self, tracker, net):
163         if self.other_txs is None:
164             raise ValueError('share does not contain all txs')
165         
166         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
167         
168         return dict(header=self.header, txs=[gentx] + self.other_txs)
169     
170     def as_share1a(self):
171         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
172     
173     def as_share1b(self):
174         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
175     
176     def check(self, tracker, now, net):
177         import time
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!')
181         
182         if self.header['timestamp'] > now + 2*60*60:
183             raise ValueError('share from too far in the future!')
184         
185         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
186         
187         if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
188             raise ValueError('''gentx doesn't match header via merkle_branch''')
189         
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''')
193             
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''')
196         
197         self.gentx = gentx
198     
199     def flag_shared(self):
200         self.shared = True
201     
202     def __repr__(self):
203         return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
204
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
210     if time == 0:
211         time = 1
212     return attempts//time
213
214 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
215     if __debug__:
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)
220     else:
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)
227     
228     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
229     max_weight = net.SPREAD * attempts_to_block
230     
231     '''
232     class fake_share(object):
233         pass
234     fake_share.new_script = new_script
235     fake_share.target = target
236     
237     dest_weights = {}
238     total_weight = 0
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
243         
244         dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
245         total_weight += weight
246         
247         if total_weight == max_weight:
248             break
249     '''
250     
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())
255     
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:
261         raise ValueError()
262     if any(x < 0 for x in amounts.itervalues()):
263         raise ValueError()
264     
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
267     
268     dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
269     assert dests[-1] == new_script
270     
271     if __debug__:
272         print "end generate_transaction"
273     
274     return dict(
275         version=1,
276         tx_ins=[dict(
277             previous_output=None,
278             sequence=None,
279             script=coinbase_type.pack(dict(
280                 identifier=net.IDENTIFIER,
281                 share_data=dict(
282                     previous_share_hash=previous_share_hash,
283                     nonce=nonce,
284                     target=target,
285                 ),
286             )),
287         )],
288         tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
289         lock_time=0,
290     )
291
292
293
294 class OkayTracker(bitcoin_data.Tracker):
295     def __init__(self, net):
296         bitcoin_data.Tracker.__init__(self)
297         self.net = net
298         self.verified = bitcoin_data.Tracker()
299         
300         self.get_cumulative_weights = skiplist.WeightsSkipList(self)
301     
302     def attempt_verify(self, share, now):
303         if share.hash in self.verified.shares:
304             return True
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()
308         try:
309             share.check(self, now, self.net)
310         except:
311             print
312             print 'Share check failed:'
313             log.err()
314             print
315             return False
316         else:
317             self.verified.add(share)
318             return True
319     
320     def think(self, ht, previous_block, now):
321         if __debug__:
322             print "start think"
323         
324         desired = set()
325         
326         # O(len(self.heads))
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
331         bads = set()
332         for head in set(self.heads) - set(self.verified.heads):
333             head_height, last = self.get_height_and_last(head)
334             
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):
337                     break
338                 if share.hash in self.heads:
339                     bads.add(share.hash)
340             else:
341                 if last is not None:
342                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
343         for bad in bads:
344             assert bad not in self.verified.shares
345             assert bad in self.heads
346             self.remove(bad)
347         
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
355             get = min(want, can)
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):
359                     break
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))
362         
363         # decide best tree
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))
367         
368         
369         #if __debug__:
370             #print len(self.verified.tails.get(best_tail, []))
371             #for a in scores:
372             #    print '   ', '%x'%a, self.score(a, ht)
373         
374         for share_hash in scores[:-5]:
375             if self.shares[share_hash].time_seen > time.time() - 30:
376                 continue
377             self.remove(share_hash)
378             self.verified.remove(share_hash)
379         
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:
382         #        self.remove(tail)
383         #        self.verified.remove(tail)
384         
385         best = scores[-1] if scores else None
386         
387         if best is not 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:
390                 if __debug__:
391                     print "stale detected!"
392                 best = best_share.previous_hash
393         
394         if __debug__:
395             print "end think"
396         
397         return best, desired
398     
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)
402         score2 = 0
403         attempts = 0
404         max_height = 0
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:
413                 score2 = this_score
414         return min(head_height, self.net.CHAIN_LENGTH), score2
415
416
417 class Mainnet(bitcoin_data.Mainnet):
418     SHARE_PERIOD = 5 # seconds
419     CHAIN_LENGTH = 24*60*60//5 # shares
420     TARGET_LOOKBEHIND = 200 # shares
421     SPREAD = 3 # blocks
422     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
423     IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
424     PREFIX = '2472ef181efcd37b'.decode('hex')
425     ADDRS_TABLE = 'addrs'
426     P2P_PORT = 9333
427     MAX_TARGET = 2**256//2**32 - 1
428
429 class Testnet(bitcoin_data.Testnet):
430     SHARE_PERIOD = 1 # seconds
431     CHAIN_LENGTH = 24*60*60//5 # shares
432     TARGET_LOOKBEHIND = 200 # shares
433     SPREAD = 3 # blocks
434     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
435     IDENTIFIER = '5fc2be2d4f0d6bfb'.decode('hex')
436     PREFIX = '3f6057a15036f441'.decode('hex')
437     ADDRS_TABLE = 'addrs_testnet'
438     P2P_PORT = 19333
439     MAX_TARGET = 2**256//2**20 - 1