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