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']))
54 raise ValueError('unknown share type: %r' % (share['type'],))
56 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
59 small_block_header_type = pack.ComposedType([
60 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
61 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
62 ('timestamp', pack.IntType(32)),
63 ('bits', bitcoin_data.FloatingIntegerType()),
64 ('nonce', pack.IntType(32)),
67 share_data_type = pack.ComposedType([
68 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
69 ('coinbase', pack.VarStrType()),
70 ('nonce', pack.IntType(32)),
71 ('pubkey_hash', pack.IntType(160)),
72 ('subsidy', pack.IntType(64)),
73 ('donation', pack.IntType(16)),
74 ('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)))),
75 ('desired_version', pack.VarIntType()),
78 share_info_type = pack.ComposedType([
79 ('share_data', share_data_type),
80 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
81 ('max_bits', bitcoin_data.FloatingIntegerType()),
82 ('bits', bitcoin_data.FloatingIntegerType()),
83 ('timestamp', pack.IntType(32)),
86 share_common_type = pack.ComposedType([
87 ('min_header', small_block_header_type),
88 ('share_info', share_info_type),
89 ('ref_merkle_link', pack.ComposedType([
90 ('branch', pack.ListType(pack.IntType(256))),
91 ('index', pack.VarIntType()),
93 ('hash_link', hash_link_type),
95 share1a_type = pack.ComposedType([
96 ('common', share_common_type),
97 ('merkle_link', pack.ComposedType([
98 ('branch', pack.ListType(pack.IntType(256))),
99 ('index', pack.IntType(0)), # it will always be 0
102 share1b_type = pack.ComposedType([
103 ('common', share_common_type),
104 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
107 ref_type = pack.ComposedType([
108 ('identifier', pack.FixedStrType(64//8)),
109 ('share_info', share_info_type),
112 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
115 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
116 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
118 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
119 assert height >= net.REAL_CHAIN_LENGTH or last is None
120 if height < net.TARGET_LOOKBEHIND:
121 pre_target3 = net.MAX_TARGET
123 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
124 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
125 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
126 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
127 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
128 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
130 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
131 min(height, net.REAL_CHAIN_LENGTH),
132 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
134 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
136 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
137 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
138 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
139 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
141 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
144 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
147 share_data=share_data,
148 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
151 timestamp=math.clip(desired_timestamp, (
152 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
153 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
154 )) if previous_share is not None else desired_timestamp,
160 previous_output=None,
162 script=share_data['coinbase'].ljust(2, '\x00'),
164 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
166 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
171 def get_share(header, transactions):
172 assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
173 min_header = dict(header);del min_header['merkle_root']
174 hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
175 merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
176 pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
177 return cls(net, None, dict(
178 min_header=min_header, share_info=share_info, hash_link=hash_link,
179 ref_merkle_link=dict(branch=[], index=0),
180 ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
182 return share_info, gentx, desired_other_transaction_hashes, get_share
185 def get_ref_hash(cls, net, share_info, ref_merkle_link):
186 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
187 identifier=net.IDENTIFIER,
188 share_info=share_info,
189 ))), ref_merkle_link))
191 __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(' ')
193 def __init__(self, net, peer, common, merkle_link, other_txs):
197 self.min_header = common['min_header']
198 self.share_info = common['share_info']
199 self.hash_link = common['hash_link']
200 self.merkle_link = merkle_link
201 self.other_txs = other_txs
203 if len(self.share_info['share_data']['coinbase']) > 100:
204 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
206 if len(merkle_link['branch']) > 16:
207 raise ValueError('merkle branch too long!')
209 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:
210 raise ValueError('merkle_link and other_txs do not match')
212 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
214 self.share_data = self.share_info['share_data']
215 self.max_target = self.share_info['max_bits'].target
216 self.target = self.share_info['bits'].target
217 self.timestamp = self.share_info['timestamp']
218 self.previous_hash = self.share_data['previous_share_hash']
219 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
220 self.desired_version = self.share_data['desired_version']
222 self.gentx_hash = check_hash_link(
224 self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
225 self.gentx_before_refhash,
227 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
228 self.header = dict(self.min_header, merkle_root=merkle_root)
229 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
230 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
232 if self.pow_hash > self.target:
233 from p2pool import p2p
234 raise p2p.PeerMisbehavingError('share PoW invalid')
236 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
237 raise ValueError('other_txs provided when not a block solution')
238 if other_txs is None and self.pow_hash <= self.header['bits'].target:
239 raise ValueError('other_txs not provided when a block solution')
241 self.new_transaction_hashes = []
244 self.time_seen = time.time()
247 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
249 def as_share1a(self):
250 return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
252 def as_share1b(self):
253 return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
256 if not self.pow_hash <= self.header['bits'].target: # share1a
257 return self.as_share1a()
259 return self.as_share1b()
261 def check(self, tracker):
262 if self.share_data['previous_share_hash'] is not None:
263 previous_share = tracker.items[self.share_data['previous_share_hash']]
264 if isinstance(previous_share, NewShare):
265 from p2pool import p2p
266 raise p2p.PeerMisbehavingError('''Share can't follow NewShare''')
267 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
268 if share_info != self.share_info:
269 raise ValueError('share_info invalid')
270 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
271 raise ValueError('''gentx doesn't match hash_link''')
272 return gentx # only used by as_block
274 def get_other_tx_hashes(self, tracker):
277 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
278 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
279 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
281 if self.pow_hash <= self.header['bits'].target:
282 return -1, 'block solution'
286 def as_block(self, tracker, known_txs):
287 if self.other_txs is None:
288 raise ValueError('share does not contain all txs')
289 return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
291 class NewShare(object):
296 small_block_header_type = pack.ComposedType([
297 ('version', pack.VarIntType()),
298 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
299 ('timestamp', pack.IntType(32)),
300 ('bits', bitcoin_data.FloatingIntegerType()),
301 ('nonce', pack.IntType(32)),
304 share_info_type = pack.ComposedType([
305 ('share_data', pack.ComposedType([
306 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
307 ('coinbase', pack.VarStrType()),
308 ('nonce', pack.IntType(32)),
309 ('pubkey_hash', pack.IntType(160)),
310 ('subsidy', pack.IntType(64)),
311 ('donation', pack.IntType(16)),
312 ('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)))),
313 ('desired_version', pack.VarIntType()),
315 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
316 ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
317 ('share_count', pack.VarIntType()),
318 ('tx_count', pack.VarIntType()),
320 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
321 ('max_bits', bitcoin_data.FloatingIntegerType()),
322 ('bits', bitcoin_data.FloatingIntegerType()),
323 ('timestamp', pack.IntType(32)),
326 share_type = pack.ComposedType([
327 ('min_header', small_block_header_type),
328 ('share_info', share_info_type),
329 ('ref_merkle_link', pack.ComposedType([
330 ('branch', pack.ListType(pack.IntType(256))),
331 ('index', pack.IntType(0)),
333 ('hash_link', hash_link_type),
334 ('merkle_link', pack.ComposedType([
335 ('branch', pack.ListType(pack.IntType(256))),
336 ('index', pack.IntType(0)), # it will always be 0
340 ref_type = pack.ComposedType([
341 ('identifier', pack.FixedStrType(64//8)),
342 ('share_info', share_info_type),
345 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
348 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
349 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
351 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
352 assert height >= net.REAL_CHAIN_LENGTH or last is None
353 if height < net.TARGET_LOOKBEHIND:
354 pre_target3 = net.MAX_TARGET
356 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
357 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
358 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
359 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
360 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
361 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
363 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
364 min(height, net.REAL_CHAIN_LENGTH),
365 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
367 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
369 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
370 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
371 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
372 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
374 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
377 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
379 new_transaction_hashes = []
380 new_transaction_size = 0
381 transaction_hash_refs = []
382 other_transaction_hashes = []
384 for tx_hash in desired_other_transaction_hashes:
385 for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
386 if tx_hash in share.new_transaction_hashes:
387 this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
390 if known_txs is not None:
391 this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash])
392 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
394 new_transaction_size += this_size
395 new_transaction_hashes.append(tx_hash)
396 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
397 transaction_hash_refs.append(this)
398 other_transaction_hashes.append(tx_hash)
401 share_data=share_data,
402 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
405 timestamp=math.clip(desired_timestamp, (
406 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
407 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
408 )) if previous_share is not None else desired_timestamp,
409 new_transaction_hashes=new_transaction_hashes,
410 transaction_hash_refs=transaction_hash_refs,
416 previous_output=None,
418 script=share_data['coinbase'],
420 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
422 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
427 def get_share(header, transactions):
428 min_header=dict(header);del min_header['merkle_root']
429 return cls(net, None, dict(
430 min_header=min_header,
431 share_info=share_info,
432 ref_merkle_link=dict(branch=[], index=0),
433 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
434 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
437 return share_info, gentx, other_transaction_hashes, get_share
440 def get_ref_hash(cls, net, share_info, ref_merkle_link):
441 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
442 identifier=net.IDENTIFIER,
443 share_info=share_info,
444 ))), ref_merkle_link))
446 __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(' ')
448 def __init__(self, net, peer, contents):
451 self.contents = contents
453 self.min_header = contents['min_header']
454 self.share_info = contents['share_info']
455 self.hash_link = contents['hash_link']
456 self.merkle_link = contents['merkle_link']
458 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
459 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
461 if len(self.merkle_link['branch']) > 16:
462 raise ValueError('merkle branch too long!')
464 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
466 self.share_data = self.share_info['share_data']
467 self.max_target = self.share_info['max_bits'].target
468 self.target = self.share_info['bits'].target
469 self.timestamp = self.share_info['timestamp']
470 self.previous_hash = self.share_data['previous_share_hash']
471 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
472 self.desired_version = self.share_data['desired_version']
474 for x in self.share_info['transaction_hash_refs']:
475 assert x['share_count'] < 110
476 for i, x in enumerate(self.share_info['new_transaction_hashes']):
477 assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
479 self.gentx_hash = check_hash_link(
481 self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
482 self.gentx_before_refhash,
484 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
485 self.header = dict(self.min_header, merkle_root=merkle_root)
486 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
487 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
489 if self.target > net.MAX_TARGET:
490 from p2pool import p2p
491 raise p2p.PeerMisbehavingError('share target invalid')
493 if self.pow_hash > self.target:
494 from p2pool import p2p
495 raise p2p.PeerMisbehavingError('share PoW invalid')
497 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
500 self.time_seen = time.time()
503 return 'Share' + repr((self.net, self.peer, self.contents))
506 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
508 def check(self, tracker):
509 if self.share_data['previous_share_hash'] is not None:
510 previous_share = tracker.items[self.share_data['previous_share_hash']]
511 if isinstance(previous_share, Share):
512 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
513 from p2pool import p2p
514 raise p2p.PeerMisbehavingError('NewShare without enough history')
516 # Share -> NewShare only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
517 counts = get_desired_version_counts(tracker,
518 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
519 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
520 from p2pool import p2p
521 raise p2p.PeerMisbehavingError('NewShare without enough hash power upgraded')
523 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']]
525 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)
526 assert other_tx_hashes2 == other_tx_hashes
527 if share_info != self.share_info:
528 raise ValueError('share_info invalid')
529 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
530 raise ValueError('''gentx doesn't match hash_link''')
532 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
533 raise ValueError('merkle_link and other_tx_hashes do not match')
535 return gentx # only used by as_block
537 def get_other_tx_hashes(self, tracker):
538 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']]
540 def _get_other_txs(self, tracker, known_txs):
541 other_tx_hashes = self.get_other_tx_hashes(tracker)
543 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
544 return None # not all txs present
546 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
548 def should_punish_reason(self, previous_block, bits, tracker, known_txs):
549 if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer is not None:
550 return True, 'Block-stale detected! %x < %x' % (self.header['previous_block'], previous_block)
552 if self.pow_hash <= self.header['bits'].target:
553 return -1, 'block solution'
555 other_txs = self._get_other_txs(tracker, known_txs)
556 if other_txs is None:
557 return True, 'not all txs present'
559 all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs)
560 if all_txs_size > 1000000:
561 return True, 'txs over block size limit'
563 new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes'])
564 if new_txs_size > 50000:
565 return True, 'new txs over limit'
569 def as_block(self, tracker, known_txs):
570 other_txs = self._get_other_txs(tracker, known_txs)
571 if other_txs is None:
572 return None # not all txs present
573 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
576 class WeightsSkipList(forest.TrackerSkipList):
577 # share_count, weights, total_weight
579 def get_delta(self, element):
580 from p2pool.bitcoin import data as bitcoin_data
581 share = self.tracker.items[element]
582 att = bitcoin_data.target_to_average_attempts(share.target)
583 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
585 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
586 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
588 def initial_solution(self, start, (max_shares, desired_weight)):
589 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
592 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)):
593 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
594 assert (desired_weight - total_weight1) % 65535 == 0
595 script, = weights2.iterkeys()
596 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
597 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)
598 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
600 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
601 if share_count > max_shares or total_weight > desired_weight:
603 elif share_count == max_shares or total_weight == desired_weight:
608 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
609 assert share_count <= max_shares and total_weight <= desired_weight
610 assert share_count == max_shares or total_weight == desired_weight
611 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
613 class OkayTracker(forest.Tracker):
614 def __init__(self, net):
615 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
616 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
617 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
620 self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
621 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
623 self.get_cumulative_weights = WeightsSkipList(self)
625 def attempt_verify(self, share):
626 if share.hash in self.verified.items:
628 height, last = self.get_height_and_last(share.hash)
629 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
630 raise AssertionError()
634 log.err(None, 'Share check failed:')
637 self.verified.add(share)
640 def think(self, block_rel_height_func, previous_block, bits, known_txs):
644 # make 'unverified heads' set?
645 # for each overall head, attempt verification
646 # if it fails, attempt on parent, and repeat
647 # if no successful verification because of lack of parents, request parent
649 for head in set(self.heads) - set(self.verified.heads):
650 head_height, last = self.get_height_and_last(head)
652 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
653 if self.attempt_verify(share):
655 if share.hash in self.heads:
660 self.items[random.choice(list(self.reverse[last]))].peer,
662 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
663 min(x.target for x in self.get_chain(head, min(head_height, 5))),
666 assert bad not in self.verified.items
667 assert bad in self.heads
672 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
673 for head in list(self.verified.heads):
674 head_height, last_hash = self.verified.get_height_and_last(head)
675 last_height, last_last_hash = self.get_height_and_last(last_hash)
676 # XXX review boundary conditions
677 want = max(self.net.CHAIN_LENGTH - head_height, 0)
678 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
680 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
681 for share in self.get_chain(last_hash, get):
682 if not self.attempt_verify(share):
684 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
686 self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
688 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
689 min(x.target for x in self.get_chain(head, min(head_height, 5))),
693 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)
695 print len(decorated_tails), 'tails:'
696 for score, tail_hash in decorated_tails:
697 print format_hash(tail_hash), score
698 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
700 # decide best verified head
701 decorated_heads = sorted(((
702 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
703 #self.items[h].peer is None,
704 -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0],
705 -self.items[h].time_seen,
706 ), h) for h in self.verified.tails.get(best_tail, []))
708 print len(decorated_heads), 'heads. Top 10:'
709 for score, head_hash in decorated_heads[-10:]:
710 print ' ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
711 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
714 best_share = self.items[best]
715 punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs)
717 print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash))
718 best = best_share.previous_hash
720 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
721 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
723 timestamp_cutoff = int(time.time()) - 24*60*60
724 target_cutoff = 2**256-1
727 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))
728 for peer, hash, ts, targ in desired:
729 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
731 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads
733 def score(self, share_hash, block_rel_height_func):
734 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
736 head_height = self.verified.get_height(share_hash)
737 if head_height < self.net.CHAIN_LENGTH:
738 return head_height, None
740 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
742 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
743 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
745 return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
747 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
749 near = tracker.items[previous_share_hash]
750 far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
751 attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
752 time = near.timestamp - far.timestamp
756 return attempts//time
759 def get_average_stale_prop(tracker, share_hash, lookbehind):
760 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
761 return stales/(lookbehind + stales)
763 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
765 for share in tracker.get_chain(share_hash, lookbehind - 1):
766 res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
767 s = share.share_data['stale_info']
769 res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
771 dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
772 res = dict((k, v/dt) for k, v in res.iteritems())
775 def get_user_stale_props(tracker, share_hash, lookbehind):
777 for share in tracker.get_chain(share_hash, lookbehind - 1):
778 stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
780 if share.share_data['stale_info'] is not None:
783 res[share.share_data['pubkey_hash']] = stale, total
784 return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
786 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
787 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))
788 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
789 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
792 def get_desired_version_counts(tracker, best_share_hash, dist):
794 for share in tracker.get_chain(best_share_hash, dist):
795 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
798 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
801 desired_version_counts = get_desired_version_counts(tracker, best_share,
802 min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
803 majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
804 if majority_desired_version > NewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
805 res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
806 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
807 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
809 if bitcoind_warning is not None:
810 res.append('(from bitcoind) %s' % (bitcoind_warning,))
812 if time.time() > bitcoind_work_value['last_update'] + 60:
813 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']),))
820 return '%08x' % (x % 2**32)
822 class ShareStore(object):
823 def __init__(self, prefix, net):
824 self.filename = prefix
825 self.dirname = os.path.dirname(os.path.abspath(prefix))
826 self.filename = os.path.basename(os.path.abspath(prefix))
828 self.known = None # will be filename -> set of share hashes, set of verified hashes
829 self.known_desired = None
831 def get_shares(self):
832 if self.known is not None:
833 raise AssertionError()
835 filenames, next = self.get_filenames_and_next()
836 for filename in filenames:
837 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
838 with open(filename, 'rb') as f:
841 type_id_str, data_hex = line.strip().split(' ')
842 type_id = int(type_id_str)
848 verified_hash = int(data_hex, 16)
849 yield 'verified_hash', verified_hash
850 verified_hashes.add(verified_hash)
852 raw_share = share_type.unpack(data_hex.decode('hex'))
853 if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
855 share = load_share(raw_share, self.net, None)
857 share_hashes.add(share.hash)
859 raise NotImplementedError("share type %i" % (type_id,))
861 log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
863 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
865 def _add_line(self, line):
866 filenames, next = self.get_filenames_and_next()
867 if filenames and os.path.getsize(filenames[-1]) < 10e6:
868 filename = filenames[-1]
872 with open(filename, 'ab') as f:
877 def add_share(self, share):
878 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
879 if share.hash in share_hashes:
882 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
883 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
884 share_hashes.add(share.hash)
885 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
886 share_hashes.add(share.hash)
888 def add_verified_hash(self, share_hash):
889 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
890 if share_hash in verified_hashes:
893 filename = self._add_line("%i %x" % (2, share_hash))
894 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
895 verified_hashes.add(share_hash)
896 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
897 verified_hashes.add(share_hash)
899 def get_filenames_and_next(self):
900 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())
901 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)))
903 def forget_share(self, share_hash):
904 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
905 if share_hash in share_hashes:
906 share_hashes.remove(share_hash)
909 def forget_verified_share(self, share_hash):
910 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
911 if share_hash in verified_hashes:
912 verified_hashes.remove(share_hash)
915 def check_remove(self):
917 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
918 #print filename, len(share_hashes) + len(verified_hashes)
919 if not share_hashes and not verified_hashes:
920 to_remove.add(filename)
921 for filename in to_remove:
922 self.known.pop(filename)
923 self.known_desired.pop(filename)
925 print "REMOVED", filename