1 from __future__ import division
9 from twisted.python import log
12 from p2pool.bitcoin import data as bitcoin_data, script, sha256
13 from p2pool.util import math, forest, pack
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()),
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)
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())
37 share_type = pack.ComposedType([
38 ('type', pack.VarIntType()),
39 ('contents', pack.VarStrType()),
42 def load_share(share, net, peer):
43 if share['type'] in [0, 1, 2, 3]:
44 from p2pool import p2p
45 raise p2p.PeerMisbehavingError('sent an obsolete share')
46 elif share['type'] == 4:
47 return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
48 elif share['type'] == 5:
49 share1b = Share.share1b_type.unpack(share['contents'])
50 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)
51 elif share['type'] == NewShare.VERSION:
52 return NewShare(net, peer, NewShare.share_type.unpack(share['contents']))
53 elif share['type'] == NewNewShare.VERSION:
54 return NewNewShare(net, peer, NewNewShare.share_type.unpack(share['contents']))
56 raise ValueError('unknown share type: %r' % (share['type'],))
58 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
60 class NewNewShare(object):
66 small_block_header_type = pack.ComposedType([
67 ('version', pack.VarIntType()),
68 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
69 ('timestamp', pack.IntType(32)),
70 ('bits', bitcoin_data.FloatingIntegerType()),
71 ('nonce', pack.IntType(32)),
74 share_info_type = pack.ComposedType([
75 ('share_data', pack.ComposedType([
76 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
77 ('coinbase', pack.VarStrType()),
78 ('nonce', pack.IntType(32)),
79 ('pubkey_hash', pack.IntType(160)),
80 ('subsidy', pack.IntType(64)),
81 ('donation', pack.IntType(16)),
82 ('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)))),
83 ('desired_version', pack.VarIntType()),
85 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
86 ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
87 ('share_count', pack.VarIntType()),
88 ('tx_count', pack.VarIntType()),
90 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
91 ('max_bits', bitcoin_data.FloatingIntegerType()),
92 ('bits', bitcoin_data.FloatingIntegerType()),
93 ('timestamp', pack.IntType(32)),
96 share_type = pack.ComposedType([
97 ('min_header', small_block_header_type),
98 ('share_info', share_info_type),
99 ('ref_merkle_link', pack.ComposedType([
100 ('branch', pack.ListType(pack.IntType(256))),
101 ('index', pack.IntType(0)),
103 ('last_txout_nonce', pack.IntType(32)),
104 ('hash_link', hash_link_type),
105 ('merkle_link', pack.ComposedType([
106 ('branch', pack.ListType(pack.IntType(256))),
107 ('index', pack.IntType(0)), # it will always be 0
111 ref_type = pack.ComposedType([
112 ('identifier', pack.FixedStrType(64//8)),
113 ('share_info', share_info_type),
116 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]
119 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None, last_txout_nonce=0):
120 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
122 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
123 assert height >= net.REAL_CHAIN_LENGTH or last is None
124 if height < net.TARGET_LOOKBEHIND:
125 pre_target3 = net.MAX_TARGET
127 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
128 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
129 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
130 pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
131 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
132 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
134 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
135 min(height, net.REAL_CHAIN_LENGTH),
136 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
138 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
140 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
141 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
142 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
143 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
145 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
148 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
150 new_transaction_hashes = []
151 new_transaction_size = 0
152 transaction_hash_refs = []
153 other_transaction_hashes = []
155 for tx_hash in desired_other_transaction_hashes:
156 for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
157 if tx_hash in share.new_transaction_hashes:
158 this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
161 if known_txs is not None:
162 this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
163 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
165 new_transaction_size += this_size
166 new_transaction_hashes.append(tx_hash)
167 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
168 transaction_hash_refs.append(this)
169 other_transaction_hashes.append(tx_hash)
172 share_data=share_data,
173 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
176 timestamp=math.clip(desired_timestamp, (
177 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
178 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
179 )) if previous_share is not None else desired_timestamp,
180 new_transaction_hashes=new_transaction_hashes,
181 transaction_hash_refs=transaction_hash_refs,
187 previous_output=None,
189 script=share_data['coinbase'],
191 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
193 script='\x24' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(32).pack(last_txout_nonce),
198 def get_share(header, transactions):
199 min_header=dict(header);del min_header['merkle_root']
200 return cls(net, None, dict(
201 min_header=min_header,
202 share_info=share_info,
203 ref_merkle_link=dict(branch=[], index=0),
204 last_txout_nonce=last_txout_nonce,
205 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4-4], cls.gentx_before_refhash),
206 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
209 return share_info, gentx, other_transaction_hashes, get_share
212 def get_ref_hash(cls, net, share_info, ref_merkle_link):
213 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
214 identifier=net.IDENTIFIER,
215 share_info=share_info,
216 ))), ref_merkle_link))
218 __slots__ = 'net peer 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(' ')
220 def __init__(self, net, peer, contents):
223 self.contents = contents
225 self.min_header = contents['min_header']
226 self.share_info = contents['share_info']
227 self.hash_link = contents['hash_link']
228 self.merkle_link = contents['merkle_link']
230 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
231 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
233 if len(self.merkle_link['branch']) > 16:
234 raise ValueError('merkle branch too long!')
236 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
238 self.share_data = self.share_info['share_data']
239 self.max_target = self.share_info['max_bits'].target
240 self.target = self.share_info['bits'].target
241 self.timestamp = self.share_info['timestamp']
242 self.previous_hash = self.share_data['previous_share_hash']
243 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
244 self.desired_version = self.share_data['desired_version']
246 for x in self.share_info['transaction_hash_refs']:
247 assert x['share_count'] < 110
248 for i, x in enumerate(self.share_info['new_transaction_hashes']):
249 assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
251 self.gentx_hash = check_hash_link(
253 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),
254 self.gentx_before_refhash,
256 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
257 self.header = dict(self.min_header, merkle_root=merkle_root)
258 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
259 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
261 if self.target > net.MAX_TARGET:
262 from p2pool import p2p
263 raise p2p.PeerMisbehavingError('share target invalid')
265 if self.pow_hash > self.target:
266 from p2pool import p2p
267 raise p2p.PeerMisbehavingError('share PoW invalid')
269 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
272 self.time_seen = time.time()
275 return 'Share' + repr((self.net, self.peer, self.contents))
278 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
280 def check(self, tracker):
281 from p2pool import p2p
282 if self.share_data['previous_share_hash'] is not None:
283 previous_share = tracker.items[self.share_data['previous_share_hash']]
284 if type(self) is type(previous_share):
286 elif type(self) is type(previous_share).SUCCESSOR:
287 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
288 from p2pool import p2p
289 raise p2p.PeerMisbehavingError('switch without enough history')
291 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
292 counts = get_desired_version_counts(tracker,
293 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
294 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
295 raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
297 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
299 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']]
301 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, last_txout_nonce=self.contents['last_txout_nonce'])
302 assert other_tx_hashes2 == other_tx_hashes
303 if share_info != self.share_info:
304 raise ValueError('share_info invalid')
305 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
306 raise ValueError('''gentx doesn't match hash_link''')
308 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
309 raise ValueError('merkle_link and other_tx_hashes do not match')
311 return gentx # only used by as_block
313 def get_other_tx_hashes(self, tracker):
314 if tracker.get_height(self.hash) <= max(x['share_count'] for x in self.share_info['transaction_hash_refs']):
316 return [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']]
318 def _get_other_txs(self, tracker, known_txs):
319 other_tx_hashes = self.get_other_tx_hashes(tracker)
320 if other_tx_hashes is None:
321 return None # not all parents present
323 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
324 return None # not all txs present
326 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
328 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
329 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
330 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
332 if self.pow_hash <= self.header['bits'].target:
333 return -1, 'block solution'
335 other_txs = self._get_other_txs(tracker, known_txs)
336 if other_txs is None:
337 return True, 'not all txs present'
339 all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
340 if all_txs_size > 1000000:
341 return True, 'txs over block size limit'
343 new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
344 if new_txs_size > 50000:
345 return True, 'new txs over limit'
349 def as_block(self, tracker, known_txs):
350 other_txs = self._get_other_txs(tracker, known_txs)
351 if other_txs is None:
352 return None # not all txs present
353 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
357 SUCCESSOR = NewNewShare
359 small_block_header_type = pack.ComposedType([
360 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
361 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
362 ('timestamp', pack.IntType(32)),
363 ('bits', bitcoin_data.FloatingIntegerType()),
364 ('nonce', pack.IntType(32)),
367 share_data_type = pack.ComposedType([
368 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
369 ('coinbase', pack.VarStrType()),
370 ('nonce', pack.IntType(32)),
371 ('pubkey_hash', pack.IntType(160)),
372 ('subsidy', pack.IntType(64)),
373 ('donation', pack.IntType(16)),
374 ('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)))),
375 ('desired_version', pack.VarIntType()),
378 share_info_type = pack.ComposedType([
379 ('share_data', share_data_type),
380 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
381 ('max_bits', bitcoin_data.FloatingIntegerType()),
382 ('bits', bitcoin_data.FloatingIntegerType()),
383 ('timestamp', pack.IntType(32)),
386 share_common_type = pack.ComposedType([
387 ('min_header', small_block_header_type),
388 ('share_info', share_info_type),
389 ('ref_merkle_link', pack.ComposedType([
390 ('branch', pack.ListType(pack.IntType(256))),
391 ('index', pack.VarIntType()),
393 ('hash_link', hash_link_type),
395 share1a_type = pack.ComposedType([
396 ('common', share_common_type),
397 ('merkle_link', pack.ComposedType([
398 ('branch', pack.ListType(pack.IntType(256))),
399 ('index', pack.IntType(0)), # it will always be 0
402 share1b_type = pack.ComposedType([
403 ('common', share_common_type),
404 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
407 ref_type = pack.ComposedType([
408 ('identifier', pack.FixedStrType(64//8)),
409 ('share_info', share_info_type),
412 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
415 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
416 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
418 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
419 assert height >= net.REAL_CHAIN_LENGTH or last is None
420 if height < net.TARGET_LOOKBEHIND:
421 pre_target3 = net.MAX_TARGET
423 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
424 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
425 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
426 pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
427 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
428 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
430 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
431 min(height, net.REAL_CHAIN_LENGTH),
432 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
434 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
436 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
437 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
438 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
439 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
441 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
444 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
447 share_data=share_data,
448 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
451 timestamp=math.clip(desired_timestamp, (
452 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
453 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
454 )) if previous_share is not None else desired_timestamp,
460 previous_output=None,
462 script=share_data['coinbase'].ljust(2, '\x00'),
464 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
466 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
471 def get_share(header, transactions):
472 assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
473 min_header = dict(header);del min_header['merkle_root']
474 hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
475 merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
476 pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
477 return cls(net, None, dict(
478 min_header=min_header, share_info=share_info, hash_link=hash_link,
479 ref_merkle_link=dict(branch=[], index=0),
480 ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
482 return share_info, gentx, desired_other_transaction_hashes, get_share
485 def get_ref_hash(cls, net, share_info, ref_merkle_link):
486 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
487 identifier=net.IDENTIFIER,
488 share_info=share_info,
489 ))), ref_merkle_link))
491 __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(' ')
493 def __init__(self, net, peer, common, merkle_link, other_txs):
497 self.min_header = common['min_header']
498 self.share_info = common['share_info']
499 self.hash_link = common['hash_link']
500 self.merkle_link = merkle_link
501 self.other_txs = other_txs
503 if len(self.share_info['share_data']['coinbase']) > 100:
504 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
506 if len(merkle_link['branch']) > 16:
507 raise ValueError('merkle branch too long!')
509 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:
510 raise ValueError('merkle_link and other_txs do not match')
512 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
514 self.share_data = self.share_info['share_data']
515 self.max_target = self.share_info['max_bits'].target
516 self.target = self.share_info['bits'].target
517 self.timestamp = self.share_info['timestamp']
518 self.previous_hash = self.share_data['previous_share_hash']
519 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
520 self.desired_version = self.share_data['desired_version']
522 self.gentx_hash = check_hash_link(
524 self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
525 self.gentx_before_refhash,
527 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
528 self.header = dict(self.min_header, merkle_root=merkle_root)
529 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
530 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
532 if self.pow_hash > self.target:
533 from p2pool import p2p
534 raise p2p.PeerMisbehavingError('share PoW invalid')
536 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
537 raise ValueError('other_txs provided when not a block solution')
538 if other_txs is None and self.pow_hash <= self.header['bits'].target:
539 raise ValueError('other_txs not provided when a block solution')
541 self.new_transaction_hashes = []
544 self.time_seen = time.time()
547 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
549 def as_share1a(self):
550 return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
552 def as_share1b(self):
553 return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
556 if not self.pow_hash <= self.header['bits'].target: # share1a
557 return self.as_share1a()
559 return self.as_share1b()
561 def check(self, tracker):
562 from p2pool import p2p
563 if self.share_data['previous_share_hash'] is not None:
564 previous_share = tracker.items[self.share_data['previous_share_hash']]
565 if type(self) is type(previous_share):
567 elif type(self) is type(previous_share).SUCCESSOR:
568 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
569 from p2pool import p2p
570 raise p2p.PeerMisbehavingError('switch without enough history')
572 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
573 counts = get_desired_version_counts(tracker,
574 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
575 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
576 raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
578 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
580 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
581 if share_info != self.share_info:
582 raise ValueError('share_info invalid')
583 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
584 raise ValueError('''gentx doesn't match hash_link''')
585 return gentx # only used by as_block
587 def get_other_tx_hashes(self, tracker):
590 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
591 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
592 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
594 if self.pow_hash <= self.header['bits'].target:
595 return -1, 'block solution'
599 def as_block(self, tracker, known_txs):
600 if self.other_txs is None:
601 raise ValueError('share does not contain all txs')
602 return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
604 class NewShare(object):
606 SUCCESSOR = NewNewShare
610 small_block_header_type = pack.ComposedType([
611 ('version', pack.VarIntType()),
612 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
613 ('timestamp', pack.IntType(32)),
614 ('bits', bitcoin_data.FloatingIntegerType()),
615 ('nonce', pack.IntType(32)),
618 share_info_type = pack.ComposedType([
619 ('share_data', pack.ComposedType([
620 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
621 ('coinbase', pack.VarStrType()),
622 ('nonce', pack.IntType(32)),
623 ('pubkey_hash', pack.IntType(160)),
624 ('subsidy', pack.IntType(64)),
625 ('donation', pack.IntType(16)),
626 ('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)))),
627 ('desired_version', pack.VarIntType()),
629 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
630 ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
631 ('share_count', pack.VarIntType()),
632 ('tx_count', pack.VarIntType()),
634 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
635 ('max_bits', bitcoin_data.FloatingIntegerType()),
636 ('bits', bitcoin_data.FloatingIntegerType()),
637 ('timestamp', pack.IntType(32)),
640 share_type = pack.ComposedType([
641 ('min_header', small_block_header_type),
642 ('share_info', share_info_type),
643 ('ref_merkle_link', pack.ComposedType([
644 ('branch', pack.ListType(pack.IntType(256))),
645 ('index', pack.IntType(0)),
647 ('hash_link', hash_link_type),
648 ('merkle_link', pack.ComposedType([
649 ('branch', pack.ListType(pack.IntType(256))),
650 ('index', pack.IntType(0)), # it will always be 0
654 ref_type = pack.ComposedType([
655 ('identifier', pack.FixedStrType(64//8)),
656 ('share_info', share_info_type),
659 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
662 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
663 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
665 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
666 assert height >= net.REAL_CHAIN_LENGTH or last is None
667 if height < net.TARGET_LOOKBEHIND:
668 pre_target3 = net.MAX_TARGET
670 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
671 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
672 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
673 pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET))
674 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
675 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
677 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
678 min(height, net.REAL_CHAIN_LENGTH),
679 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
681 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
683 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
684 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
685 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
686 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
688 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
691 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
693 new_transaction_hashes = []
694 new_transaction_size = 0
695 transaction_hash_refs = []
696 other_transaction_hashes = []
698 for tx_hash in desired_other_transaction_hashes:
699 for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
700 if tx_hash in share.new_transaction_hashes:
701 this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
704 if known_txs is not None:
705 this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
706 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
708 new_transaction_size += this_size
709 new_transaction_hashes.append(tx_hash)
710 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
711 transaction_hash_refs.append(this)
712 other_transaction_hashes.append(tx_hash)
715 share_data=share_data,
716 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
719 timestamp=math.clip(desired_timestamp, (
720 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
721 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
722 )) if previous_share is not None else desired_timestamp,
723 new_transaction_hashes=new_transaction_hashes,
724 transaction_hash_refs=transaction_hash_refs,
730 previous_output=None,
732 script=share_data['coinbase'],
734 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
736 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
741 def get_share(header, transactions):
742 min_header=dict(header);del min_header['merkle_root']
743 return cls(net, None, dict(
744 min_header=min_header,
745 share_info=share_info,
746 ref_merkle_link=dict(branch=[], index=0),
747 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
748 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
751 return share_info, gentx, other_transaction_hashes, get_share
754 def get_ref_hash(cls, net, share_info, ref_merkle_link):
755 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
756 identifier=net.IDENTIFIER,
757 share_info=share_info,
758 ))), ref_merkle_link))
760 __slots__ = 'net peer 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(' ')
762 def __init__(self, net, peer, contents):
765 self.contents = contents
767 self.min_header = contents['min_header']
768 self.share_info = contents['share_info']
769 self.hash_link = contents['hash_link']
770 self.merkle_link = contents['merkle_link']
772 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
773 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
775 if len(self.merkle_link['branch']) > 16:
776 raise ValueError('merkle branch too long!')
778 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
780 self.share_data = self.share_info['share_data']
781 self.max_target = self.share_info['max_bits'].target
782 self.target = self.share_info['bits'].target
783 self.timestamp = self.share_info['timestamp']
784 self.previous_hash = self.share_data['previous_share_hash']
785 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
786 self.desired_version = self.share_data['desired_version']
788 for x in self.share_info['transaction_hash_refs']:
789 assert x['share_count'] < 110
790 for i, x in enumerate(self.share_info['new_transaction_hashes']):
791 assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
793 self.gentx_hash = check_hash_link(
795 self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
796 self.gentx_before_refhash,
798 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
799 self.header = dict(self.min_header, merkle_root=merkle_root)
800 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
801 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
803 if self.target > net.MAX_TARGET:
804 from p2pool import p2p
805 raise p2p.PeerMisbehavingError('share target invalid')
807 if self.pow_hash > self.target:
808 from p2pool import p2p
809 raise p2p.PeerMisbehavingError('share PoW invalid')
811 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
814 self.time_seen = time.time()
817 return 'Share' + repr((self.net, self.peer, self.contents))
820 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
822 def check(self, tracker):
823 from p2pool import p2p
824 if self.share_data['previous_share_hash'] is not None:
825 previous_share = tracker.items[self.share_data['previous_share_hash']]
826 if type(self) is type(previous_share):
828 elif type(self) is type(previous_share).SUCCESSOR:
829 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
830 from p2pool import p2p
831 raise p2p.PeerMisbehavingError('switch without enough history')
833 # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
834 counts = get_desired_version_counts(tracker,
835 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
836 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
837 raise p2p.PeerMisbehavingError('switch without enough hash power upgraded')
839 raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__))
841 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']]
843 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)
844 assert other_tx_hashes2 == other_tx_hashes
845 if share_info != self.share_info:
846 raise ValueError('share_info invalid')
847 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
848 raise ValueError('''gentx doesn't match hash_link''')
850 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
851 raise ValueError('merkle_link and other_tx_hashes do not match')
853 return gentx # only used by as_block
855 def get_other_tx_hashes(self, tracker):
856 if tracker.get_height(self.hash) <= max(x['share_count'] for x in self.share_info['transaction_hash_refs']):
858 return [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']]
860 def _get_other_txs(self, tracker, known_txs):
861 other_tx_hashes = self.get_other_tx_hashes(tracker)
862 if other_tx_hashes is None:
863 return None # not all parents present
865 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
866 return None # not all txs present
868 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
870 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
871 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
872 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
874 if self.pow_hash <= self.header['bits'].target:
875 return -1, 'block solution'
877 other_txs = self._get_other_txs(tracker, known_txs)
878 if other_txs is None:
879 return True, 'not all txs present'
881 all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
882 if all_txs_size > 1000000:
883 return True, 'txs over block size limit'
885 new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
886 if new_txs_size > 50000:
887 return True, 'new txs over limit'
891 def as_block(self, tracker, known_txs):
892 other_txs = self._get_other_txs(tracker, known_txs)
893 if other_txs is None:
894 return None # not all txs present
895 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
898 class WeightsSkipList(forest.TrackerSkipList):
899 # share_count, weights, total_weight
901 def get_delta(self, element):
902 from p2pool.bitcoin import data as bitcoin_data
903 share = self.tracker.items[element]
904 att = bitcoin_data.target_to_average_attempts(share.target)
905 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
907 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
908 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
910 def initial_solution(self, start, (max_shares, desired_weight)):
911 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
914 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)):
915 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
916 assert (desired_weight - total_weight1) % 65535 == 0
917 script, = weights2.iterkeys()
918 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
919 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)
920 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
922 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
923 if share_count > max_shares or total_weight > desired_weight:
925 elif share_count == max_shares or total_weight == desired_weight:
930 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
931 assert share_count <= max_shares and total_weight <= desired_weight
932 assert share_count == max_shares or total_weight == desired_weight
933 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
935 class OkayTracker(forest.Tracker):
936 def __init__(self, net):
937 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
938 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
939 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
942 self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
943 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
945 self.get_cumulative_weights = WeightsSkipList(self)
947 def attempt_verify(self, share):
948 if share.hash in self.verified.items:
950 height, last = self.get_height_and_last(share.hash)
951 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
952 raise AssertionError()
956 log.err(None, 'Share check failed:')
959 self.verified.add(share)
962 def think(self, block_rel_height_func, previous_block, bits, known_txs):
966 # make 'unverified heads' set?
967 # for each overall head, attempt verification
968 # if it fails, attempt on parent, and repeat
969 # if no successful verification because of lack of parents, request parent
971 for head in set(self.heads) - set(self.verified.heads):
972 head_height, last = self.get_height_and_last(head)
974 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
975 if self.attempt_verify(share):
977 if share.hash in self.heads:
982 self.items[random.choice(list(self.reverse[last]))].peer,
984 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
985 min(x.target for x in self.get_chain(head, min(head_height, 5))),
988 assert bad not in self.verified.items
989 assert bad in self.heads
994 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
995 for head in list(self.verified.heads):
996 head_height, last_hash = self.verified.get_height_and_last(head)
997 last_height, last_last_hash = self.get_height_and_last(last_hash)
998 # XXX review boundary conditions
999 want = max(self.net.CHAIN_LENGTH - head_height, 0)
1000 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
1001 get = min(want, can)
1002 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
1003 for share in self.get_chain(last_hash, get):
1004 if not self.attempt_verify(share):
1006 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
1008 self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
1010 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
1011 min(x.target for x in self.get_chain(head, min(head_height, 5))),
1015 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)
1017 print len(decorated_tails), 'tails:'
1018 for score, tail_hash in decorated_tails:
1019 print format_hash(tail_hash), score
1020 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
1022 # decide best verified head
1023 decorated_heads = sorted(((
1024 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
1025 #self.items[h].peer is None,
1026 -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
1027 -self.items[h].time_seen,
1028 ), h) for h in self.verified.tails.get(best_tail, []))
1030 print len(decorated_heads), 'heads. Top 10:'
1031 for score, head_hash in decorated_heads[-10:]:
1032 print ' ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
1033 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
1035 if best is not None:
1036 best_share = self.items[best]
1037 punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
1039 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
1040 best = best_share.previous_hash
1042 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
1043 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
1045 timestamp_cutoff = int(time.time()) - 24*60*60
1046 target_cutoff = 2**256-1
1049 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))
1050 for peer, hash, ts, targ in desired:
1051 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
1053 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
1055 def score(self, share_hash, block_rel_height_func):
1056 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
1058 head_height = self.verified.get_height(share_hash)
1059 if head_height < self.net.CHAIN_LENGTH:
1060 return head_height, None
1062 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
1064 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
1065 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
1067 return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
1069 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
1071 near = tracker.items[previous_share_hash]
1072 far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
1073 attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
1074 time = near.timestamp - far.timestamp
1078 return attempts//time
1079 return attempts/time
1081 def get_average_stale_prop(tracker, share_hash, lookbehind):
1082 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
1083 return stales/(lookbehind + stales)
1085 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
1087 for share in tracker.get_chain(share_hash, lookbehind - 1):
1088 res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
1089 s = share.share_data['stale_info']
1091 res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
1093 dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
1094 res = dict((k, v/dt) for k, v in res.iteritems())
1097 def get_user_stale_props(tracker, share_hash, lookbehind):
1099 for share in tracker.get_chain(share_hash, lookbehind - 1):
1100 stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
1102 if share.share_data['stale_info'] is not None:
1105 res[share.share_data['pubkey_hash']] = stale, total
1106 return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
1108 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
1109 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))
1110 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
1111 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
1114 def get_desired_version_counts(tracker, best_share_hash, dist):
1116 for share in tracker.get_chain(best_share_hash, dist):
1117 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
1120 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
1123 desired_version_counts = get_desired_version_counts(tracker, best_share,
1124 min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
1125 majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
1126 if majority_desired_version > NewNewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
1127 res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
1128 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
1129 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
1131 if bitcoind_warning is not None:
1132 if 'This is a pre-release test build' in bitcoind_warning:
1134 res.append('(from bitcoind) %s' % (bitcoind_warning,))
1136 if time.time() > bitcoind_work_value['last_update'] + 60:
1137 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']),))
1144 return '%08x' % (x % 2**32)
1146 class ShareStore(object):
1147 def __init__(self, prefix, net):
1148 self.filename = prefix
1149 self.dirname = os.path.dirname(os.path.abspath(prefix))
1150 self.filename = os.path.basename(os.path.abspath(prefix))
1152 self.known = None # will be filename -> set of share hashes, set of verified hashes
1153 self.known_desired = None
1155 def get_shares(self):
1156 if self.known is not None:
1157 raise AssertionError()
1159 filenames, next = self.get_filenames_and_next()
1160 for filename in filenames:
1161 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
1162 with open(filename, 'rb') as f:
1165 type_id_str, data_hex = line.strip().split(' ')
1166 type_id = int(type_id_str)
1172 verified_hash = int(data_hex, 16)
1173 yield 'verified_hash', verified_hash
1174 verified_hashes.add(verified_hash)
1176 raw_share = share_type.unpack(data_hex.decode('hex'))
1177 if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
1179 share = load_share(raw_share, self.net, None)
1180 yield 'share', share
1181 share_hashes.add(share.hash)
1183 raise NotImplementedError("share type %i" % (type_id,))
1185 log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
1187 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
1189 def _add_line(self, line):
1190 filenames, next = self.get_filenames_and_next()
1191 if filenames and os.path.getsize(filenames[-1]) < 10e6:
1192 filename = filenames[-1]
1196 with open(filename, 'ab') as f:
1197 f.write(line + '\n')
1201 def add_share(self, share):
1202 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
1203 if share.hash in share_hashes:
1206 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
1207 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
1208 share_hashes.add(share.hash)
1209 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
1210 share_hashes.add(share.hash)
1212 def add_verified_hash(self, share_hash):
1213 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
1214 if share_hash in verified_hashes:
1217 filename = self._add_line("%i %x" % (2, share_hash))
1218 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
1219 verified_hashes.add(share_hash)
1220 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
1221 verified_hashes.add(share_hash)
1223 def get_filenames_and_next(self):
1224 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())
1225 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)))
1227 def forget_share(self, share_hash):
1228 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1229 if share_hash in share_hashes:
1230 share_hashes.remove(share_hash)
1233 def forget_verified_share(self, share_hash):
1234 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1235 if share_hash in verified_hashes:
1236 verified_hashes.remove(share_hash)
1239 def check_remove(self):
1241 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
1242 #print filename, len(share_hashes) + len(verified_hashes)
1243 if not share_hashes and not verified_hashes:
1244 to_remove.add(filename)
1245 for filename in to_remove:
1246 self.known.pop(filename)
1247 self.known_desired.pop(filename)
1249 print "REMOVED", filename