added new share type
[p2pool.git] / p2pool / data.py
1 from __future__ import division
2
3 import hashlib
4 import os
5 import random
6 import time
7
8 from twisted.python import log
9
10 import p2pool
11 from p2pool.bitcoin import data as bitcoin_data, script, sha256
12 from p2pool.util import math, forest, pack
13
14 # hashlink
15
16 hash_link_type = pack.ComposedType([
17     ('state', pack.FixedStrType(32)),
18     ('extra_data', pack.FixedStrType(0)), # bit of a hack, but since the donation script is at the end, const_ending is long enough to always make this empty
19     ('length', pack.VarIntType()),
20 ])
21
22 def prefix_to_hash_link(prefix, const_ending=''):
23     assert prefix.endswith(const_ending), (prefix, const_ending)
24     x = sha256.sha256(prefix)
25     return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
26
27 def check_hash_link(hash_link, data, const_ending=''):
28     extra_length = hash_link['length'] % (512//8)
29     assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
30     extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
31     assert len(extra) == extra_length
32     return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
33
34 # shares
35
36 # type:
37 # 2: share1a
38 # 3: share1b
39
40 share_type = pack.ComposedType([
41     ('type', pack.VarIntType()),
42     ('contents', pack.VarStrType()),
43 ])
44
45 def load_share(share, net, peer):
46     if share['type'] in [0, 1, 2, 3]:
47         from p2pool import p2p
48         raise p2p.PeerMisbehavingError('sent an obsolete share')
49     elif share['type'] == 4:
50         return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
51     elif share['type'] == 5:
52         share1b = Share.share1b_type.unpack(share['contents'])
53         return Share(net, peer, merkle_link=bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in share1b['other_txs']], 0), **share1b)
54     elif share['type'] == 8:
55         return NewShare(net, peer, NewShare.share_type.unpack(share['contents']))
56     else:
57         raise ValueError('unknown share type: %r' % (share['type'],))
58
59 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
60
61 class Share(object):
62     small_block_header_type = pack.ComposedType([
63         ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
64         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
65         ('timestamp', pack.IntType(32)),
66         ('bits', bitcoin_data.FloatingIntegerType()),
67         ('nonce', pack.IntType(32)),
68     ])
69     
70     share_data_type = pack.ComposedType([
71         ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
72         ('coinbase', pack.VarStrType()),
73         ('nonce', pack.IntType(32)),
74         ('pubkey_hash', pack.IntType(160)),
75         ('subsidy', pack.IntType(64)),
76         ('donation', pack.IntType(16)),
77         ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))),
78         ('desired_version', pack.VarIntType()),
79     ])
80     
81     share_info_type = pack.ComposedType([
82         ('share_data', share_data_type),
83         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
84         ('max_bits', bitcoin_data.FloatingIntegerType()),
85         ('bits', bitcoin_data.FloatingIntegerType()),
86         ('timestamp', pack.IntType(32)),
87     ])
88     
89     share_common_type = pack.ComposedType([
90         ('min_header', small_block_header_type),
91         ('share_info', share_info_type),
92         ('ref_merkle_link', pack.ComposedType([
93             ('branch', pack.ListType(pack.IntType(256))),
94             ('index', pack.VarIntType()),
95         ])),
96         ('hash_link', hash_link_type),
97     ])
98     share1a_type = pack.ComposedType([
99         ('common', share_common_type),
100         ('merkle_link', pack.ComposedType([
101             ('branch', pack.ListType(pack.IntType(256))),
102             ('index', pack.IntType(0)), # it will always be 0
103         ])),
104     ])
105     share1b_type = pack.ComposedType([
106         ('common', share_common_type),
107         ('other_txs', pack.ListType(bitcoin_data.tx_type)),
108     ])
109     
110     ref_type = pack.ComposedType([
111         ('identifier', pack.FixedStrType(64//8)),
112         ('share_info', share_info_type),
113     ])
114     
115     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
116     
117     @classmethod
118     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net):
119         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
120         
121         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
122         assert height >= net.REAL_CHAIN_LENGTH or last is None
123         if height < net.TARGET_LOOKBEHIND:
124             pre_target3 = net.MAX_TARGET
125         else:
126             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
127             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
128             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
129             pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
130         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
131         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
132         
133         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
134             min(height, net.REAL_CHAIN_LENGTH),
135             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
136         )
137         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
138         
139         amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share
140         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
141         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
142         amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding
143         
144         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
145             raise ValueError()
146         
147         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
148         
149         share_info = dict(
150             share_data=share_data,
151             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
152             max_bits=max_bits,
153             bits=bits,
154             timestamp=math.clip(desired_timestamp, (
155                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
156                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
157             )) if previous_share is not None else desired_timestamp,
158         )
159         
160         gentx = dict(
161             version=1,
162             tx_ins=[dict(
163                 previous_output=None,
164                 sequence=None,
165                 script=share_data['coinbase'].ljust(2, '\x00'),
166             )],
167             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
168                 value=0,
169                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
170             )],
171             lock_time=0,
172         )
173         
174         def get_share(header, transactions):
175             assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
176             min_header = dict(header);del min_header['merkle_root']
177             hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
178             merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
179             pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
180             return cls(net, None, dict(
181                 min_header=min_header, share_info=share_info, hash_link=hash_link,
182                 ref_merkle_link=dict(branch=[], index=0),
183             ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
184         
185         return share_info, gentx, desired_other_transaction_hashes, get_share
186     
187     @classmethod
188     def get_ref_hash(cls, net, share_info, ref_merkle_link):
189         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
190             identifier=net.IDENTIFIER,
191             share_info=share_info,
192         ))), ref_merkle_link))
193     
194     __slots__ = 'net peer common min_header share_info hash_link merkle_link other_txs hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash new_transaction_hashes time_seen'.split(' ')
195     
196     def __init__(self, net, peer, common, merkle_link, other_txs):
197         self.net = net
198         self.peer = peer
199         self.common = common
200         self.min_header = common['min_header']
201         self.share_info = common['share_info']
202         self.hash_link = common['hash_link']
203         self.merkle_link = merkle_link
204         self.other_txs = other_txs
205         
206         if len(self.share_info['share_data']['coinbase']) > 100:
207             raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
208         
209         if len(merkle_link['branch']) > 16:
210             raise ValueError('merkle branch too long!')
211         
212         if p2pool.DEBUG and other_txs is not None and bitcoin_data.calculate_merkle_link([0] + [bitcoin_data.hash256(bitcoin_data.tx_type.pack(x)) for x in other_txs], 0) != merkle_link:
213             raise ValueError('merkle_link and other_txs do not match')
214         
215         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
216         
217         self.share_data = self.share_info['share_data']
218         self.max_target = self.share_info['max_bits'].target
219         self.target = self.share_info['bits'].target
220         self.timestamp = self.share_info['timestamp']
221         self.previous_hash = self.share_data['previous_share_hash']
222         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
223         self.desired_version = self.share_data['desired_version']
224         
225         self.gentx_hash = check_hash_link(
226             self.hash_link,
227             self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
228             self.gentx_before_refhash,
229         )
230         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
231         self.header = dict(self.min_header, merkle_root=merkle_root)
232         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
233         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
234         
235         if self.pow_hash > self.target:
236             from p2pool import p2p
237             raise p2p.PeerMisbehavingError('share PoW invalid')
238         
239         if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
240             raise ValueError('other_txs provided when not a block solution')
241         if other_txs is None and self.pow_hash <= self.header['bits'].target:
242             raise ValueError('other_txs not provided when a block solution')
243         
244         self.new_transaction_hashes = []
245         
246         # XXX eww
247         self.time_seen = time.time()
248     
249     def __repr__(self):
250         return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
251     
252     def as_share1a(self):
253         return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
254     
255     def as_share1b(self):
256         return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
257     
258     def as_share(self):
259         if not self.pow_hash <= self.header['bits'].target: # share1a
260             return self.as_share1a()
261         else:
262             return self.as_share1b()
263     
264     def check(self, tracker):
265         share_info, gentx, other_transaction_hashes, get_share = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.common['ref_merkle_link'], [], self.net) # ok because desired_other_transaction_hashes is only used in get_share
266         if share_info != self.share_info:
267             raise ValueError('share_info invalid')
268         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
269             raise ValueError('''gentx doesn't match hash_link''')
270         return gentx # only used by as_block
271     
272     def as_block(self, tracker):
273         if self.other_txs is None:
274             raise ValueError('share does not contain all txs')
275         return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
276
277 class NewShare(object):
278     small_block_header_type = pack.ComposedType([
279         ('version', pack.VarIntType()),
280         ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
281         ('timestamp', pack.IntType(32)),
282         ('bits', bitcoin_data.FloatingIntegerType()),
283         ('nonce', pack.IntType(32)),
284     ])
285     
286     share_info_type = pack.ComposedType([
287         ('share_data', pack.ComposedType([
288             ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
289             ('coinbase', pack.VarStrType()),
290             ('nonce', pack.IntType(32)),
291             ('pubkey_hash', pack.IntType(160)),
292             ('subsidy', pack.IntType(64)),
293             ('donation', pack.IntType(16)),
294             ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))),
295             ('desired_version', pack.VarIntType()),
296         ])),
297         ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
298         ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
299             ('share_count', pack.VarIntType()),
300             ('tx_count', pack.VarIntType()),
301         ]))),
302         ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
303         ('max_bits', bitcoin_data.FloatingIntegerType()),
304         ('bits', bitcoin_data.FloatingIntegerType()),
305         ('timestamp', pack.IntType(32)),
306     ])
307     
308     share_type = pack.ComposedType([
309         ('min_header', small_block_header_type),
310         ('share_info', share_info_type),
311         ('ref_merkle_link', pack.ComposedType([
312             ('branch', pack.ListType(pack.IntType(256))),
313             ('index', pack.IntType(0)),
314         ])),
315         ('hash_link', hash_link_type),
316         ('merkle_link', pack.ComposedType([
317             ('branch', pack.ListType(pack.IntType(256))),
318             ('index', pack.IntType(0)), # it will always be 0
319         ])),
320     ])
321     
322     ref_type = pack.ComposedType([
323         ('identifier', pack.FixedStrType(64//8)),
324         ('share_info', share_info_type),
325     ])
326     
327     gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
328     
329     @classmethod
330     def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net):
331         previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
332         
333         height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
334         assert height >= net.REAL_CHAIN_LENGTH or last is None
335         if height < net.TARGET_LOOKBEHIND:
336             pre_target3 = net.MAX_TARGET
337         else:
338             attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
339             pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
340             pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
341             pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
342         max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
343         bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
344         
345         weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
346             min(height, net.REAL_CHAIN_LENGTH),
347             65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
348         )
349         assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
350         
351         amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share
352         this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
353         amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
354         amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding
355         
356         if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
357             raise ValueError()
358         
359         dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
360         
361         new_transaction_hashes = []
362         transaction_hash_refs = []
363         other_transaction_hashes = []
364         
365         for tx_hash in desired_other_transaction_hashes:
366             for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
367                 if tx_hash in share.new_transaction_hashes:
368                     this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
369                     break
370             else:
371                 if len(new_transaction_hashes) == 10: # only allow 10 new txns/share
372                     break
373                 new_transaction_hashes.append(tx_hash)
374                 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
375             transaction_hash_refs.append(this)
376             other_transaction_hashes.append(tx_hash)
377         
378         share_info = dict(
379             share_data=share_data,
380             far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
381             max_bits=max_bits,
382             bits=bits,
383             timestamp=math.clip(desired_timestamp, (
384                 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
385                 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
386             )) if previous_share is not None else desired_timestamp,
387             new_transaction_hashes=new_transaction_hashes,
388             transaction_hash_refs=transaction_hash_refs,
389         )
390         
391         gentx = dict(
392             version=1,
393             tx_ins=[dict(
394                 previous_output=None,
395                 sequence=None,
396                 script=share_data['coinbase'],
397             )],
398             tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
399                 value=0,
400                 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
401             )],
402             lock_time=0,
403         )
404         
405         def get_share(header, transactions):
406             min_header=dict(header);del min_header['merkle_root']
407             return cls(net, None, dict(
408                 min_header=min_header,
409                 share_info=share_info,
410                 ref_merkle_link=dict(branch=[], index=0),
411                 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
412                 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
413             ))
414         
415         return share_info, gentx, other_transaction_hashes, get_share
416     
417     @classmethod
418     def get_ref_hash(cls, net, share_info, ref_merkle_link):
419         return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
420             identifier=net.IDENTIFIER,
421             share_info=share_info,
422         ))), ref_merkle_link))
423     
424     __slots__ = 'net peer contents min_header share_info hash_link merkle_link other_txs hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash new_transaction_hashes time_seen'.split(' ')
425     
426     def __init__(self, net, peer, contents):
427         self.net = net
428         self.peer = peer
429         self.contents = contents
430         
431         self.min_header = contents['min_header']
432         self.share_info = contents['share_info']
433         self.hash_link = contents['hash_link']
434         self.merkle_link = contents['merkle_link']
435         
436         if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
437             raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
438         
439         if len(self.merkle_link['branch']) > 16:
440             raise ValueError('merkle branch too long!')
441         
442         assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
443         
444         self.share_data = self.share_info['share_data']
445         self.max_target = self.share_info['max_bits'].target
446         self.target = self.share_info['bits'].target
447         self.timestamp = self.share_info['timestamp']
448         self.previous_hash = self.share_data['previous_share_hash']
449         self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
450         self.desired_version = self.share_data['desired_version']
451         
452         for x in self.share_info['transaction_hash_refs']:
453             assert x['share_count'] < net.CHAIN_LENGTH
454         
455         self.gentx_hash = check_hash_link(
456             self.hash_link,
457             self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
458             self.gentx_before_refhash,
459         )
460         merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
461         self.header = dict(self.min_header, merkle_root=merkle_root)
462         self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
463         self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
464         
465         if self.target > net.MAX_TARGET:
466             from p2pool import p2p
467             raise p2p.PeerMisbehavingError('share target invalid')
468         
469         if self.pow_hash > self.target:
470             from p2pool import p2p
471             raise p2p.PeerMisbehavingError('share PoW invalid')
472         
473         self.new_transaction_hashes = self.share_info['new_transaction_hashes']
474         
475         # XXX eww
476         self.time_seen = time.time()
477     
478     def __repr__(self):
479         return 'Share' + repr((self.net, self.peer, self.contents))
480     
481     def as_share(self):
482         return dict(type=8, contents=self.share_type.pack(self.contents))
483     
484     def check(self, tracker):
485         other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, x['share_count'])].share_info['new_transaction_hashes'][x['tx_count']] for x in self.share_info['transaction_hash_refs']]
486         
487         share_info, gentx, other_tx_hashes2, get_share = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.contents['ref_merkle_link'], other_tx_hashes, self.net)
488         assert other_tx_hashes2 == other_tx_hashes
489         if share_info != self.share_info:
490             raise ValueError('share_info invalid')
491         if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
492             raise ValueError('''gentx doesn't match hash_link''')
493         
494         if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
495             raise ValueError('merkle_link and other_tx_hashes do not match')
496         
497         #return [gentx] + other_txs # only used by as_block
498     
499     def as_block(self, tracker):
500         assert False
501         return dict(header=self.header, txs=self.check(tracker))
502
503
504 class WeightsSkipList(forest.TrackerSkipList):
505     # share_count, weights, total_weight
506     
507     def get_delta(self, element):
508         from p2pool.bitcoin import data as bitcoin_data
509         share = self.tracker.items[element]
510         att = bitcoin_data.target_to_average_attempts(share.target)
511         return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
512     
513     def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
514         return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
515     
516     def initial_solution(self, start, (max_shares, desired_weight)):
517         assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
518         return 0, None, 0, 0
519     
520     def apply_delta(self, (share_count1, weights_list, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2), (max_shares, desired_weight)):
521         if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
522             assert (desired_weight - total_weight1) % 65535 == 0
523             script, = weights2.iterkeys()
524             new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
525             return share_count1 + share_count2, (weights_list, new_weights), desired_weight, total_donation_weight1 + (desired_weight - total_weight1)//65535*total_donation_weight2//(total_weight2//65535)
526         return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
527     
528     def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
529         if share_count > max_shares or total_weight > desired_weight:
530             return 1
531         elif share_count == max_shares or total_weight == desired_weight:
532             return 0
533         else:
534             return -1
535     
536     def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
537         assert share_count <= max_shares and total_weight <= desired_weight
538         assert share_count == max_shares or total_weight == desired_weight
539         return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
540
541 class OkayTracker(forest.Tracker):
542     def __init__(self, net, my_share_hashes, my_doa_share_hashes):
543         forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
544             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
545             min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
546         )))
547         self.net = net
548         self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
549             work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
550             my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
551             my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
552             my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'orphan' else 0,
553             my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'doa' else 0,
554         )), subset_of=self)
555         self.get_cumulative_weights = WeightsSkipList(self)
556     
557     def attempt_verify(self, share):
558         if share.hash in self.verified.items:
559             return True
560         height, last = self.get_height_and_last(share.hash)
561         if height < self.net.CHAIN_LENGTH + 1 and last is not None:
562             raise AssertionError()
563         try:
564             share.check(self)
565         except:
566             log.err(None, 'Share check failed:')
567             return False
568         else:
569             self.verified.add(share)
570             return True
571     
572     def think(self, block_rel_height_func, previous_block, bits):
573         desired = set()
574         
575         # O(len(self.heads))
576         #   make 'unverified heads' set?
577         # for each overall head, attempt verification
578         # if it fails, attempt on parent, and repeat
579         # if no successful verification because of lack of parents, request parent
580         bads = set()
581         for head in set(self.heads) - set(self.verified.heads):
582             head_height, last = self.get_height_and_last(head)
583             
584             for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
585                 if self.attempt_verify(share):
586                     break
587                 if share.hash in self.heads:
588                     bads.add(share.hash)
589             else:
590                 if last is not None:
591                     desired.add((
592                         self.items[random.choice(list(self.reverse[last]))].peer,
593                         last,
594                         max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
595                         min(x.target for x in self.get_chain(head, min(head_height, 5))),
596                     ))
597         for bad in bads:
598             assert bad not in self.verified.items
599             assert bad in self.heads
600             if p2pool.DEBUG:
601                 print "BAD", bad
602             self.remove(bad)
603         
604         # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
605         for head in list(self.verified.heads):
606             head_height, last_hash = self.verified.get_height_and_last(head)
607             last_height, last_last_hash = self.get_height_and_last(last_hash)
608             # XXX review boundary conditions
609             want = max(self.net.CHAIN_LENGTH - head_height, 0)
610             can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
611             get = min(want, can)
612             #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
613             for share in self.get_chain(last_hash, get):
614                 if not self.attempt_verify(share):
615                     break
616             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
617                 desired.add((
618                     self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
619                     last_last_hash,
620                     max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
621                     min(x.target for x in self.get_chain(head, min(head_height, 5))),
622                 ))
623         
624         # decide best tree
625         decorated_tails = sorted((self.score(max(self.verified.tails[tail_hash], key=self.verified.get_work), block_rel_height_func), tail_hash) for tail_hash in self.verified.tails)
626         if p2pool.DEBUG:
627             print len(decorated_tails), 'tails:'
628             for score, tail_hash in decorated_tails:
629                 print format_hash(tail_hash), score
630         best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
631         
632         # decide best verified head
633         decorated_heads = sorted(((
634             self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
635             #self.items[h].peer is None,
636             self.items[h].pow_hash <= self.items[h].header['bits'].target, # is block solution
637             (self.items[h].header['previous_block'], self.items[h].header['bits']) == (previous_block, bits) or self.items[h].peer is None,
638             -self.items[h].time_seen,
639         ), h) for h in self.verified.tails.get(best_tail, []))
640         if p2pool.DEBUG:
641             print len(decorated_heads), 'heads. Top 10:'
642             for score, head_hash in decorated_heads[-10:]:
643                 print '   ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
644         best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
645         
646         # eat away at heads
647         if decorated_heads:
648             for i in xrange(1000):
649                 to_remove = set()
650                 for share_hash, tail in self.heads.iteritems():
651                     if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
652                         #print 1
653                         continue
654                     if self.items[share_hash].time_seen > time.time() - 300:
655                         #print 2
656                         continue
657                     if share_hash not in self.verified.items and max(self.items[after_tail_hash].time_seen for after_tail_hash in self.reverse.get(tail)) > time.time() - 120: # XXX stupid
658                         #print 3
659                         continue
660                     to_remove.add(share_hash)
661                 if not to_remove:
662                     break
663                 for share_hash in to_remove:
664                     if share_hash in self.verified.items:
665                         self.verified.remove(share_hash)
666                     self.remove(share_hash)
667                 #print "_________", to_remove
668         
669         # drop tails
670         for i in xrange(1000):
671             to_remove = set()
672             for tail, heads in self.tails.iteritems():
673                 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
674                     continue
675                 for aftertail in self.reverse.get(tail, set()):
676                     if len(self.reverse[self.items[aftertail].previous_hash]) > 1: # XXX
677                         print "raw"
678                         continue
679                     to_remove.add(aftertail)
680             if not to_remove:
681                 break
682             # if removed from this, it must be removed from verified
683             #start = time.time()
684             for aftertail in to_remove:
685                 if self.items[aftertail].previous_hash not in self.tails:
686                     print "erk", aftertail, self.items[aftertail].previous_hash
687                     continue
688                 if aftertail in self.verified.items:
689                     self.verified.remove(aftertail)
690                 self.remove(aftertail)
691             #end = time.time()
692             #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
693         
694         if best is not None:
695             best_share = self.items[best]
696             if (best_share.header['previous_block'], best_share.header['bits']) != (previous_block, bits) and best_share.header_hash != previous_block and best_share.peer is not None:
697                 if p2pool.DEBUG:
698                     print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
699                 best = best_share.previous_hash
700             
701             timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
702             target_cutoff = 2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 if best_tail_score[1] is not None else 2**256-1
703         else:
704             timestamp_cutoff = int(time.time()) - 24*60*60
705             target_cutoff = 2**256-1
706         
707         if p2pool.DEBUG:
708             print 'Desire %i shares. Cutoff: %s old diff>%.2f' % (len(desired), math.format_dt(time.time() - timestamp_cutoff), bitcoin_data.target_to_difficulty(target_cutoff))
709             for peer, hash, ts, targ in desired:
710                 print '   ', '%s:%i' % peer.addr if peer is not None else None, format_hash(hash), math.format_dt(time.time() - ts), bitcoin_data.target_to_difficulty(targ), ts >= timestamp_cutoff, targ <= target_cutoff
711         
712         return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff]
713     
714     def score(self, share_hash, block_rel_height_func):
715         # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
716         
717         head_height = self.verified.get_height(share_hash)
718         if head_height < self.net.CHAIN_LENGTH:
719             return head_height, None
720         
721         end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
722         
723         block_height = max(block_rel_height_func(share.header['previous_block']) for share in
724             self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
725         
726         return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
727
728 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
729     assert dist >= 2
730     near = tracker.items[previous_share_hash]
731     far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
732     attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
733     time = near.timestamp - far.timestamp
734     if time <= 0:
735         time = 1
736     if integer:
737         return attempts//time
738     return attempts/time
739
740 def get_average_stale_prop(tracker, share_hash, lookbehind):
741     stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
742     return stales/(lookbehind + stales)
743
744 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
745     res = {}
746     for share in tracker.get_chain(share_hash, lookbehind - 1):
747         res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
748         s = share.share_data['stale_info']
749         if s is not None:
750             res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
751     if rates:
752         dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
753         res = dict((k, v/dt) for k, v in res.iteritems())
754     return res
755
756 def get_user_stale_props(tracker, share_hash, lookbehind):
757     res = {}
758     for share in tracker.get_chain(share_hash, lookbehind - 1):
759         stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
760         total += 1
761         if share.share_data['stale_info'] is not None:
762             stale += 1
763             total += 1
764         res[share.share_data['pubkey_hash']] = stale, total
765     return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
766
767 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
768     weights, total_weight, donation_weight = tracker.get_cumulative_weights(best_share_hash, min(tracker.get_height(best_share_hash), net.REAL_CHAIN_LENGTH), 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target))
769     res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
770     res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
771     return res
772
773 def get_desired_version_counts(tracker, best_share_hash, dist):
774     res = {}
775     for share in tracker.get_chain(best_share_hash, dist):
776         res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
777     return res
778
779 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
780     res = []
781     
782     desired_version_counts = get_desired_version_counts(tracker, best_share,
783         min(60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
784     majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
785     if majority_desired_version > 5 and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
786         res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
787             'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
788                 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
789     
790     if bitcoind_warning is not None:
791         res.append('(from bitcoind) %s' % (bitcoind_warning,))
792     
793     if time.time() > bitcoind_work_value['last_update'] + 60:
794         res.append('''LOST CONTACT WITH BITCOIND for %s! Check that it isn't frozen or dead!''' % (math.format_dt(time.time() - bitcoind_work_value['last_update']),))
795     
796     return res
797
798 def format_hash(x):
799     if x is None:
800         return 'xxxxxxxx'
801     return '%08x' % (x % 2**32)
802
803 class ShareStore(object):
804     def __init__(self, prefix, net):
805         self.filename = prefix
806         self.dirname = os.path.dirname(os.path.abspath(prefix))
807         self.filename = os.path.basename(os.path.abspath(prefix))
808         self.net = net
809         self.known = None # will be filename -> set of share hashes, set of verified hashes
810         self.known_desired = None
811     
812     def get_shares(self):
813         if self.known is not None:
814             raise AssertionError()
815         known = {}
816         filenames, next = self.get_filenames_and_next()
817         for filename in filenames:
818             share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
819             with open(filename, 'rb') as f:
820                 for line in f:
821                     try:
822                         type_id_str, data_hex = line.strip().split(' ')
823                         type_id = int(type_id_str)
824                         if type_id == 0:
825                             pass
826                         elif type_id == 1:
827                             pass
828                         elif type_id == 2:
829                             verified_hash = int(data_hex, 16)
830                             yield 'verified_hash', verified_hash
831                             verified_hashes.add(verified_hash)
832                         elif type_id == 5:
833                             raw_share = share_type.unpack(data_hex.decode('hex'))
834                             if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
835                                 continue
836                             share = load_share(raw_share, self.net, None)
837                             yield 'share', share
838                             share_hashes.add(share.hash)
839                         else:
840                             raise NotImplementedError("share type %i" % (type_id,))
841                     except Exception:
842                         log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
843         self.known = known
844         self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
845     
846     def _add_line(self, line):
847         filenames, next = self.get_filenames_and_next()
848         if filenames and os.path.getsize(filenames[-1]) < 10e6:
849             filename = filenames[-1]
850         else:
851             filename = next
852         
853         with open(filename, 'ab') as f:
854             f.write(line + '\n')
855         
856         return filename
857     
858     def add_share(self, share):
859         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
860             if share.hash in share_hashes:
861                 break
862         else:
863             filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
864             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
865             share_hashes.add(share.hash)
866         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
867         share_hashes.add(share.hash)
868     
869     def add_verified_hash(self, share_hash):
870         for filename, (share_hashes, verified_hashes) in self.known.iteritems():
871             if share_hash in verified_hashes:
872                 break
873         else:
874             filename = self._add_line("%i %x" % (2, share_hash))
875             share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
876             verified_hashes.add(share_hash)
877         share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
878         verified_hashes.add(share_hash)
879     
880     def get_filenames_and_next(self):
881         suffixes = sorted(int(x[len(self.filename):]) for x in os.listdir(self.dirname) if x.startswith(self.filename) and x[len(self.filename):].isdigit())
882         return [os.path.join(self.dirname, self.filename + str(suffix)) for suffix in suffixes], os.path.join(self.dirname, self.filename + (str(suffixes[-1] + 1) if suffixes else str(0)))
883     
884     def forget_share(self, share_hash):
885         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
886             if share_hash in share_hashes:
887                 share_hashes.remove(share_hash)
888         self.check_remove()
889     
890     def forget_verified_share(self, share_hash):
891         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
892             if share_hash in verified_hashes:
893                 verified_hashes.remove(share_hash)
894         self.check_remove()
895     
896     def check_remove(self):
897         to_remove = set()
898         for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
899             #print filename, len(share_hashes) + len(verified_hashes)
900             if not share_hashes and not verified_hashes:
901                 to_remove.add(filename)
902         for filename in to_remove:
903             self.known.pop(filename)
904             self.known_desired.pop(filename)
905             os.remove(filename)
906             print "REMOVED", filename