increase maximum nonce size to make way for merged mining
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import itertools
4 import random
5 import time
6
7 from twisted.internet import defer
8 from twisted.python import log
9
10 from p2pool.bitcoin import data as bitcoin_data
11 from p2pool.bitcoin import script
12 from p2pool.util import memoize, expiring_dict, math, skiplist, deferral
13 import p2pool
14
15
16 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
17     ('side', bitcoin_data.StructType('<B')), # enum?
18     ('hash', bitcoin_data.HashType()),
19 ]))
20
21
22 share_data_type = bitcoin_data.ComposedType([
23     ('previous_share_hash', bitcoin_data.PossiblyNone(0, bitcoin_data.HashType())),
24     ('target', bitcoin_data.FloatingIntegerType()),
25     ('nonce', bitcoin_data.VarStrType()),
26 ])
27
28
29 coinbase_type = bitcoin_data.ComposedType([
30     ('identifier', bitcoin_data.FixedStrType(8)),
31     ('share_data', share_data_type),
32 ])
33
34 share_info_type = bitcoin_data.ComposedType([
35     ('share_data', share_data_type),
36     ('new_script', bitcoin_data.VarStrType()),
37     ('subsidy', bitcoin_data.StructType('<Q')),
38 ])
39
40
41 share1a_type = bitcoin_data.ComposedType([
42     ('header', bitcoin_data.block_header_type),
43     ('share_info', share_info_type),
44     ('merkle_branch', merkle_branch_type),
45 ])
46
47 share1b_type = bitcoin_data.ComposedType([
48     ('header', bitcoin_data.block_header_type),
49     ('share_info', share_info_type),
50     ('other_txs', bitcoin_data.ListType(bitcoin_data.tx_type)),
51 ])
52
53 def calculate_merkle_branch(txs, index):
54     hash_list = [(bitcoin_data.tx_type.hash256(tx), i == index, []) for i, tx in enumerate(txs)]
55     
56     while len(hash_list) > 1:
57         hash_list = [
58             (
59                 bitcoin_data.merkle_record_type.hash256(dict(left=left, right=right)),
60                 left_f or right_f,
61                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
62             )
63             for (left, left_f, left_l), (right, right_f, right_l) in
64                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
65         ]
66     
67     assert hash_list[0][1]
68     assert check_merkle_branch(txs[index], hash_list[0][2]) == hash_list[0][0]
69     
70     return hash_list[0][2]
71
72 def check_merkle_branch(tx, branch):
73     hash_ = bitcoin_data.tx_type.hash256(tx)
74     for step in branch:
75         if not step['side']:
76             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=step['hash'], right=hash_))
77         else:
78             hash_ = bitcoin_data.merkle_record_type.hash256(dict(left=hash_, right=step['hash']))
79     return hash_
80
81 def gentx_to_share_info(gentx):
82     return dict(
83         share_data=coinbase_type.unpack(gentx['tx_ins'][0]['script'])['share_data'],
84         subsidy=sum(tx_out['value'] for tx_out in gentx['tx_outs']),
85         new_script=gentx['tx_outs'][-1]['script'],
86     )
87
88 def share_info_to_gentx(share_info, block_target, tracker, net):
89     return generate_transaction(
90         tracker=tracker,
91         previous_share_hash=share_info['share_data']['previous_share_hash'],
92         new_script=share_info['new_script'],
93         subsidy=share_info['subsidy'],
94         nonce=share_info['share_data']['nonce'],
95         block_target=block_target,
96         net=net,
97     )
98
99 class Share(object):
100     @classmethod
101     def from_block(cls, block):
102         return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
103     
104     @classmethod
105     def from_share1a(cls, share1a):
106         return cls(**share1a)
107     
108     @classmethod
109     def from_share1b(cls, share1b):
110         return cls(**share1b)
111     
112     __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce bitcoin_hash hash time_seen shared peer'.split(' ')
113     
114     def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
115         if merkle_branch is None and other_txs is None:
116             raise ValueError('need either merkle_branch or other_txs')
117         if other_txs is not None:
118             new_merkle_branch = calculate_merkle_branch([dict(version=0, tx_ins=[], tx_outs=[], lock_time=0)] + other_txs, 0)
119             if merkle_branch is not None:
120                 if merke_branch != new_merkle_branch:
121                     raise ValueError('invalid merkle_branch and other_txs')
122             merkle_branch = new_merkle_branch
123         
124         if len(merkle_branch) > 16:
125             raise ValueError('merkle_branch too long!')
126         
127         self.header = header
128         self.previous_block = header['previous_block']
129         self.share_info = share_info
130         self.merkle_branch = merkle_branch
131         self.other_txs = other_txs
132         
133         self.timestamp = self.header['timestamp']
134         
135         self.share_data = self.share_info['share_data']
136         self.new_script = self.share_info['new_script']
137         self.subsidy = self.share_info['subsidy']
138         
139         if len(self.new_script) > 100:
140             raise ValueError('new_script too long!')
141         
142         self.previous_hash = self.previous_share_hash = self.share_data['previous_share_hash']
143         self.target = self.share_data['target']
144         self.nonce = self.share_data['nonce']
145         
146         if len(self.nonce) > 100:
147             raise ValueError('nonce too long!')
148         
149         self.bitcoin_hash = bitcoin_data.block_header_type.hash256(header)
150         self.hash = share1a_type.hash256(self.as_share1a())
151         
152         if self.bitcoin_hash > self.target:
153             print 'hash', hex(self.bitcoin_hash)
154             print 'targ', hex(self.target)
155             raise ValueError('not enough work!')
156         
157         if script.get_sigop_count(self.new_script) > 1:
158             raise ValueError('too many sigops!')
159         
160         # XXX eww
161         self.time_seen = time.time()
162         self.shared = False
163         self.peer = None
164     
165     def as_block(self, tracker, net):
166         if self.other_txs is None:
167             raise ValueError('share does not contain all txs')
168         
169         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
170         
171         return dict(header=self.header, txs=[gentx] + self.other_txs)
172     
173     def as_share1a(self):
174         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
175     
176     def as_share1b(self):
177         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
178     
179     def check(self, tracker, now, net):
180         import time
181         if self.previous_share_hash is not None:
182             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):
183                 raise ValueError('share from too far in the past!')
184         
185         if self.header['timestamp'] > now + 2*60*60:
186             raise ValueError('share from too far in the future!')
187         
188         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
189         
190         if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
191             raise ValueError('''gentx doesn't match header via merkle_branch''')
192         
193         if self.other_txs is not None:
194             if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
195                 raise ValueError('''gentx doesn't match header via other_txs''')
196             
197             if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
198                 raise ValueError('''block size too large''')
199     
200     def flag_shared(self):
201         self.shared = True
202     
203     def __repr__(self):
204         return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
205
206 def get_pool_attempts_per_second(tracker, previous_share_hash, net, dist=None):
207     if dist is None:
208         dist = net.TARGET_LOOKBEHIND
209     # XXX could be optimized to use nth_parent and cumulative_weights
210     chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), dist))
211     attempts = sum(bitcoin_data.target_to_average_attempts(share.target) for share in chain[:-1])
212     time = chain[0].timestamp - chain[-1].timestamp
213     if time == 0:
214         time = 1
215     return attempts//time
216
217 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
218     height, last = tracker.get_height_and_last(previous_share_hash)
219     if height < net.TARGET_LOOKBEHIND:
220         target = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
221     else:
222         attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
223         pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
224         previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
225         pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
226         pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
227         target = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
228     
229     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
230     max_weight = net.SPREAD * attempts_to_block
231     
232     '''
233     class fake_share(object):
234         pass
235     fake_share.new_script = new_script
236     fake_share.target = target
237     
238     dest_weights = {}
239     total_weight = 0
240     for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
241         weight = bitcoin_data.target_to_average_attempts(share.target)
242         if weight > max_weight - total_weight:
243             weight = max_weight - total_weight
244         
245         dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
246         total_weight += weight
247         
248         if total_weight == max_weight:
249             break
250     '''
251     
252     this_weight = min(bitcoin_data.target_to_average_attempts(target), max_weight)
253     other_weights, other_weights_total = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), max(0, max_weight - this_weight))
254     dest_weights, total_weight = math.add_dicts([{new_script: this_weight}, other_weights]), this_weight + other_weights_total
255     total_weight = sum(dest_weights.itervalues())
256     
257     amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
258     amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
259     amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*2//400
260     amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
261     if sum(amounts.itervalues()) != subsidy:
262         raise ValueError()
263     if any(x < 0 for x in amounts.itervalues()):
264         raise ValueError()
265     
266     pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
267     pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
268     
269     dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
270     assert dests[-1] == new_script
271     
272     return dict(
273         version=1,
274         tx_ins=[dict(
275             previous_output=None,
276             sequence=None,
277             script=coinbase_type.pack(dict(
278                 identifier=net.IDENTIFIER,
279                 share_data=dict(
280                     previous_share_hash=previous_share_hash,
281                     nonce=nonce,
282                     target=target,
283                 ),
284             )),
285         )],
286         tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script]],
287         lock_time=0,
288     )
289
290
291
292 class OkayTracker(bitcoin_data.Tracker):
293     def __init__(self, net):
294         bitcoin_data.Tracker.__init__(self)
295         self.net = net
296         self.verified = bitcoin_data.Tracker()
297         
298         self.get_cumulative_weights = skiplist.WeightsSkipList(self)
299     
300     def attempt_verify(self, share, now):
301         if share.hash in self.verified.shares:
302             return True
303         height, last = self.get_height_and_last(share.hash)
304         if height < self.net.CHAIN_LENGTH and last is not None:
305             raise AssertionError()
306         try:
307             share.check(self, now, self.net)
308         except:
309             log.err(None, 'Share check failed:')
310             return False
311         else:
312             self.verified.add(share)
313             return True
314     
315     @defer.inlineCallbacks
316     def think(self, ht, previous_block, now):
317         desired = set()
318         
319         # O(len(self.heads))
320         #   make 'unverified heads' set?
321         # for each overall head, attempt verification
322         # if it fails, attempt on parent, and repeat
323         # if no successful verification because of lack of parents, request parent
324         bads = set()
325         for head in set(self.heads) - set(self.verified.heads):
326             head_height, last = self.get_height_and_last(head)
327             
328             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))):
329                 if self.attempt_verify(share, now):
330                     break
331                 if share.hash in self.heads:
332                     bads.add(share.hash)
333             else:
334                 if last is not None:
335                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
336         for bad in bads:
337             assert bad not in self.verified.shares
338             assert bad in self.heads
339             self.remove(bad)
340         
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
348             get = min(want, can)
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, now):
352                     break
353                 if random.random() < .001:
354                     #print 'YIELDING'
355                     yield deferral.sleep(.01)
356             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
357                 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
358         
359         # decide best tree
360         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
361         # decide best verified head
362         scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
363             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
364             ht.get_min_height(self.verified.shares[h].previous_block),
365             self.verified.shares[h].peer is None,
366             -self.verified.shares[h].time_seen
367         ))
368         
369         
370         if p2pool.DEBUG:
371             print len(self.verified.tails.get(best_tail, []))
372             for h in scores:
373                 print '   ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
374                     self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
375                     ht.get_min_height(self.verified.shares[h].previous_block),
376                     self.verified.shares[h].peer is None,
377                     -self.verified.shares[h].time_seen
378                 )
379         
380         for share_hash in scores[:-5]:
381             if self.shares[share_hash].time_seen > time.time() - 30:
382                 continue
383             self.remove(share_hash)
384             self.verified.remove(share_hash)
385         
386         #for tail, heads in list(self.tails.iteritems()):
387         #    if min(self.get_height(head) for head in heads) > 2*net.CHAIN_LENGTH + 10:
388         #        self.remove(tail)
389         #        self.verified.remove(tail)
390         
391         best = scores[-1] if scores else None
392         
393         if best is not None:
394             best_share = self.verified.shares[best]
395             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:
396                 if p2pool.DEBUG:
397                     print 'Stale detected!'
398                 best = best_share.previous_hash
399         
400         defer.returnValue((best, desired))
401     
402     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
403     def score(self, share_hash, ht):
404         head_height, last = self.verified.get_height_and_last(share_hash)
405         score2 = 0
406         attempts = 0
407         max_height = 0
408         # XXX should only look past a certain share, not at recent ones
409         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
410         # XXX this must go in the opposite direction for max_height to make sense
411         for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
412             max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
413             attempts += bitcoin_data.target_to_average_attempts(share.target)
414             this_score = attempts//(ht.get_highest_height() - max_height + 1)
415             if this_score > score2:
416                 score2 = this_score
417         return min(head_height, self.net.CHAIN_LENGTH), score2
418
419 def format_hash(x):
420     if x is None:
421         return 'xxxxxxxx'
422     return '%08x' % (x % 2**32)
423
424 class Mainnet(bitcoin_data.Mainnet):
425     SHARE_PERIOD = 5 # seconds
426     CHAIN_LENGTH = 24*60*60//5 # shares
427     TARGET_LOOKBEHIND = 200 # shares
428     SPREAD = 3 # blocks
429     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
430     IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
431     PREFIX = '2472ef181efcd37b'.decode('hex')
432     ADDRS_TABLE = 'addrs'
433     P2P_PORT = 9333
434     MAX_TARGET = 2**256//2**32 - 1
435     PERSIST = True
436
437 class Testnet(bitcoin_data.Testnet):
438     SHARE_PERIOD = 1 # seconds
439     CHAIN_LENGTH = 24*60*60//5 # shares
440     TARGET_LOOKBEHIND = 200 # shares
441     SPREAD = 3 # blocks
442     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
443     IDENTIFIER = '5fc2be2d4f0d6bfb'.decode('hex')
444     PREFIX = '3f6057a15036f441'.decode('hex')
445     ADDRS_TABLE = 'addrs_testnet'
446     P2P_PORT = 19333
447     MAX_TARGET = 2**256//2**20 - 1
448     PERSIST = False