never mark your own share as stale
[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     gentx = None
101     
102     @classmethod
103     def from_block(cls, block):
104         return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
105     
106     @classmethod
107     def from_share1a(cls, share1a):
108         return cls(**share1a)
109     
110     @classmethod
111     def from_share1b(cls, share1b):
112         return cls(**share1b)
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) > 20:
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         self.time_seen = time.time()
161         self.shared = False
162     
163     def as_block(self):
164         if self.other_txs is None:
165             raise ValueError('share does not contain all txs')
166         
167         return dict(header=self.header, txs=[self.gentx] + self.other_txs)
168     
169     def as_share1a(self):
170         return dict(header=self.header, share_info=self.share_info, merkle_branch=self.merkle_branch)
171     
172     def as_share1b(self):
173         return dict(header=self.header, share_info=self.share_info, other_txs=self.other_txs)
174     
175     def check(self, tracker, now, net):
176         import time
177         if self.previous_share_hash is not None:
178             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):
179                 raise ValueError('share from too far in the past!')
180         
181         if self.header['timestamp'] > now + 2*60*60:
182             raise ValueError('share from too far in the future!')
183         
184         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
185         
186         if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
187             raise ValueError('''gentx doesn't match header via merkle_branch''')
188         
189         if self.other_txs is not None:
190             if bitcoin_data.merkle_hash([gentx] + self.other_txs) != self.header['merkle_root']:
191                 raise ValueError('''gentx doesn't match header via other_txs''')
192             
193             if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
194                 raise ValueError('''block size too large''')
195         
196         self.gentx = gentx
197     
198     def flag_shared(self):
199         self.shared = True
200     
201     def __repr__(self):
202         return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
203
204 def get_pool_attempts_per_second(tracker, previous_share_hash, net):
205     chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
206     attempts = sum(bitcoin_data.target_to_average_attempts(share.target) for share in chain[:-1])
207     time = chain[0].timestamp - chain[-1].timestamp
208     if time == 0:
209         time = 1
210     return attempts//time
211
212 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
213     if __debug__:
214         print "start generate_transaction"
215     height, last = tracker.get_height_and_last(previous_share_hash)
216     if height < net.TARGET_LOOKBEHIND:
217         target = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
218     else:
219         attempts_per_second = get_pool_attempts_per_second(tracker, previous_share_hash, net)
220         pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1
221         previous_share = tracker.shares[previous_share_hash] if previous_share_hash is not None else None
222         pre_target2 = math.clip(pre_target, (previous_share.target*9//10, previous_share.target*11//10))
223         pre_target3 = math.clip(pre_target2, (0, 2**256//2**32 - 1))
224         target = bitcoin_data.FloatingIntegerType().truncate_to(pre_target3)
225     
226     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
227     max_weight = net.SPREAD * attempts_to_block
228     
229     '''
230     class fake_share(object):
231         pass
232     fake_share.new_script = new_script
233     fake_share.target = target
234     
235     dest_weights = {}
236     total_weight = 0
237     for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
238         weight = bitcoin_data.target_to_average_attempts(share.target)
239         if weight > max_weight - total_weight:
240             weight = max_weight - total_weight
241         
242         dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
243         total_weight += weight
244         
245         if total_weight == max_weight:
246             break
247     '''
248     
249     this_weight = min(bitcoin_data.target_to_average_attempts(target), max_weight)
250     other_weights, other_weights_total = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), max(0, max_weight - this_weight))
251     dest_weights, total_weight = math.add_dicts([{new_script: this_weight}, other_weights]), this_weight + other_weights_total
252     total_weight = sum(dest_weights.itervalues())
253     
254     amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
255     amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
256     amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy*2//400
257     amounts[net.SCRIPT] = amounts.get(net.SCRIPT, 0) + subsidy - sum(amounts.itervalues()) # collect any extra
258     if sum(amounts.itervalues()) != subsidy:
259         raise ValueError()
260     if any(x < 0 for x in amounts.itervalues()):
261         raise ValueError()
262     
263     pre_dests = sorted(amounts.iterkeys(), key=lambda script: (amounts[script], script))
264     pre_dests = pre_dests[-4000:] # block length limit, unlikely to ever be hit
265     
266     dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
267     assert dests[-1] == new_script
268     
269     if __debug__:
270         print "end generate_transaction"
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             print
310             print 'Share check failed:'
311             log.err()
312             print
313             return False
314         else:
315             self.verified.add(share)
316             return True
317     
318     def think(self, ht, previous_block, now):
319         if __debug__:
320             print "start think"
321         
322         desired = set()
323         
324         # O(len(self.heads))
325         #   make 'unverified heads' set?
326         # for each overall head, attempt verification
327         # if it fails, attempt on parent, and repeat
328         # if no successful verification because of lack of parents, request parent
329         bads = set()
330         for head in set(self.heads) - set(self.verified.heads):
331             head_height, last = self.get_height_and_last(head)
332             
333             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))):
334                 if self.attempt_verify(share, now):
335                     break
336                 if share.hash in self.heads:
337                     bads.add(share.hash)
338             else:
339                 if last is not None:
340                     desired.add((self.shares[random.choice(list(self.reverse_shares[last]))].peer, last))
341         for bad in bads:
342             assert bad not in self.verified.shares
343             assert bad in self.heads
344             self.remove(bad)
345         
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
353             get = min(want, can)
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):
357                     break
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))
360         
361         # decide best tree
362         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
363         # decide best verified head
364         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))
365         
366         
367         #if __debug__:
368             #print len(self.verified.tails.get(best_tail, []))
369             #for a in scores:
370             #    print '   ', '%x'%a, self.score(a, ht)
371         
372         for share_hash in scores[:-5]:
373             if self.shares[share_hash].time_seen > time.time() - 30:
374                 continue
375             self.remove(share_hash)
376             self.verified.remove(share_hash)
377         
378         best = scores[-1] if scores else None
379         
380         if best is not None:
381             best_share = self.verified.shares[best]
382             if ht.get_min_height(best_share.header['previous_block']) < ht.get_min_height(previous_block) and best_share.peer is not None:
383                 if __debug__:
384                     print "stale detected!"
385                 best = best_share.previous_hash
386         
387         if __debug__:
388             print "end think"
389         
390         return best, desired
391     
392     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
393     def score(self, share_hash, ht):
394         head_height, last = self.verified.get_height_and_last(share_hash)
395         score2 = 0
396         attempts = 0
397         max_height = 0
398         # XXX should only look past a certain share, not at recent ones
399         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
400         # XXX this must go in the opposite direction for max_height to make sense
401         for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
402             max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
403             attempts += bitcoin_data.target_to_average_attempts(share.target)
404             this_score = attempts//(ht.get_highest_height() - max_height + 1)
405             if this_score > score2:
406                 score2 = this_score
407         return min(head_height, self.net.CHAIN_LENGTH), score2
408
409
410 class Mainnet(bitcoin_data.Mainnet):
411     SHARE_PERIOD = 5 # seconds
412     CHAIN_LENGTH = 24*60*60//5 # shares
413     TARGET_LOOKBEHIND = 200 # shares
414     SPREAD = 3 # blocks
415     SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
416     IDENTIFIER = 'fc70035c7a81bc6f'.decode('hex')
417     PREFIX = '2472ef181efcd37b'.decode('hex')
418     ADDRS_TABLE = 'addrs'
419     P2P_PORT = 9333
420
421 class Testnet(bitcoin_data.Testnet):
422     SHARE_PERIOD = 1 # seconds
423     CHAIN_LENGTH = 24*60*60//5 # shares
424     TARGET_LOOKBEHIND = 200 # shares
425     SPREAD = 3 # blocks
426     SCRIPT = '410403ad3dee8ab3d8a9ce5dd2abfbe7364ccd9413df1d279bf1a207849310465b0956e5904b1155ecd17574778f9949589ebfd4fb33ce837c241474a225cf08d85dac'.decode('hex')
427     IDENTIFIER = '5fc2be5d4f0d6bfb'.decode('hex')
428     PREFIX = '3f6057a15076f441'.decode('hex')
429     ADDRS_TABLE = 'addrs_testnet'
430     P2P_PORT = 19333