1 from __future__ import division
8 from twisted.python import log
11 from p2pool.bitcoin import data as bitcoin_data, script, sha256
12 from p2pool.util import math, forest, pack
16 hash_link_type = pack.ComposedType([
17 ('state', pack.FixedStrType(32)),
18 ('extra_data', pack.FixedStrType(0)), # bit of a hack, but since the donation script is at the end, const_ending is long enough to always make this empty
19 ('length', pack.VarIntType()),
22 def prefix_to_hash_link(prefix, const_ending=''):
23 assert prefix.endswith(const_ending), (prefix, const_ending)
24 x = sha256.sha256(prefix)
25 return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8)
27 def check_hash_link(hash_link, data, const_ending=''):
28 extra_length = hash_link['length'] % (512//8)
29 assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending))
30 extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:]
31 assert len(extra) == extra_length
32 return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest())
36 share_type = pack.ComposedType([
37 ('type', pack.VarIntType()),
38 ('contents', pack.VarStrType()),
41 def load_share(share, net, peer):
42 if share['type'] in [0, 1, 2, 3]:
43 from p2pool import p2p
44 raise p2p.PeerMisbehavingError('sent an obsolete share')
45 elif share['type'] == 4:
46 return Share(net, peer, other_txs=None, **Share.share1a_type.unpack(share['contents']))
47 elif share['type'] == 5:
48 share1b = Share.share1b_type.unpack(share['contents'])
49 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)
50 elif share['type'] == NewShare.VERSION:
51 return NewShare(net, peer, NewShare.share_type.unpack(share['contents']))
53 raise ValueError('unknown share type: %r' % (share['type'],))
55 DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex')
58 small_block_header_type = pack.ComposedType([
59 ('version', pack.VarIntType()), # XXX must be constrained to 32 bits
60 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
61 ('timestamp', pack.IntType(32)),
62 ('bits', bitcoin_data.FloatingIntegerType()),
63 ('nonce', pack.IntType(32)),
66 share_data_type = pack.ComposedType([
67 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
68 ('coinbase', pack.VarStrType()),
69 ('nonce', pack.IntType(32)),
70 ('pubkey_hash', pack.IntType(160)),
71 ('subsidy', pack.IntType(64)),
72 ('donation', pack.IntType(16)),
73 ('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)))),
74 ('desired_version', pack.VarIntType()),
77 share_info_type = pack.ComposedType([
78 ('share_data', share_data_type),
79 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
80 ('max_bits', bitcoin_data.FloatingIntegerType()),
81 ('bits', bitcoin_data.FloatingIntegerType()),
82 ('timestamp', pack.IntType(32)),
85 share_common_type = pack.ComposedType([
86 ('min_header', small_block_header_type),
87 ('share_info', share_info_type),
88 ('ref_merkle_link', pack.ComposedType([
89 ('branch', pack.ListType(pack.IntType(256))),
90 ('index', pack.VarIntType()),
92 ('hash_link', hash_link_type),
94 share1a_type = pack.ComposedType([
95 ('common', share_common_type),
96 ('merkle_link', pack.ComposedType([
97 ('branch', pack.ListType(pack.IntType(256))),
98 ('index', pack.IntType(0)), # it will always be 0
101 share1b_type = pack.ComposedType([
102 ('common', share_common_type),
103 ('other_txs', pack.ListType(bitcoin_data.tx_type)),
106 ref_type = pack.ComposedType([
107 ('identifier', pack.FixedStrType(64//8)),
108 ('share_info', share_info_type),
111 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
114 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
115 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
117 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
118 assert height >= net.REAL_CHAIN_LENGTH or last is None
119 if height < net.TARGET_LOOKBEHIND:
120 pre_target3 = net.MAX_TARGET
122 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
123 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
124 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
125 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
126 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
127 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
129 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
130 min(height, net.REAL_CHAIN_LENGTH),
131 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
133 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
135 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
136 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
137 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
138 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
140 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
143 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
146 share_data=share_data,
147 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
150 timestamp=math.clip(desired_timestamp, (
151 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
152 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
153 )) if previous_share is not None else desired_timestamp,
159 previous_output=None,
161 script=share_data['coinbase'].ljust(2, '\x00'),
163 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
165 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
170 def get_share(header, transactions):
171 assert transactions[0] == gentx and [bitcoin_data.hash256(bitcoin_data.tx_type.pack(tx)) for tx in transactions[1:]] == desired_other_transaction_hashes
172 min_header = dict(header);del min_header['merkle_root']
173 hash_link = prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash)
174 merkle_link = bitcoin_data.calculate_merkle_link([None] + desired_other_transaction_hashes, 0)
175 pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(header))
176 return cls(net, None, dict(
177 min_header=min_header, share_info=share_info, hash_link=hash_link,
178 ref_merkle_link=dict(branch=[], index=0),
179 ), merkle_link=merkle_link, other_txs=transactions[1:] if pow_hash <= header['bits'].target else None)
181 return share_info, gentx, desired_other_transaction_hashes, get_share
184 def get_ref_hash(cls, net, share_info, ref_merkle_link):
185 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
186 identifier=net.IDENTIFIER,
187 share_info=share_info,
188 ))), ref_merkle_link))
190 __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(' ')
192 def __init__(self, net, peer, common, merkle_link, other_txs):
196 self.min_header = common['min_header']
197 self.share_info = common['share_info']
198 self.hash_link = common['hash_link']
199 self.merkle_link = merkle_link
200 self.other_txs = other_txs
202 if len(self.share_info['share_data']['coinbase']) > 100:
203 raise ValueError('''coinbase too large! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
205 if len(merkle_link['branch']) > 16:
206 raise ValueError('merkle branch too long!')
208 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:
209 raise ValueError('merkle_link and other_txs do not match')
211 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
213 self.share_data = self.share_info['share_data']
214 self.max_target = self.share_info['max_bits'].target
215 self.target = self.share_info['bits'].target
216 self.timestamp = self.share_info['timestamp']
217 self.previous_hash = self.share_data['previous_share_hash']
218 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
219 self.desired_version = self.share_data['desired_version']
221 self.gentx_hash = check_hash_link(
223 self.get_ref_hash(net, self.share_info, common['ref_merkle_link']) + pack.IntType(32).pack(0),
224 self.gentx_before_refhash,
226 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, merkle_link)
227 self.header = dict(self.min_header, merkle_root=merkle_root)
228 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
229 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
231 if self.pow_hash > self.target:
232 from p2pool import p2p
233 raise p2p.PeerMisbehavingError('share PoW invalid')
235 if other_txs is not None and not self.pow_hash <= self.header['bits'].target:
236 raise ValueError('other_txs provided when not a block solution')
237 if other_txs is None and self.pow_hash <= self.header['bits'].target:
238 raise ValueError('other_txs not provided when a block solution')
240 self.new_transaction_hashes = []
243 self.time_seen = time.time()
246 return '<Share %s>' % (' '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__),)
248 def as_share1a(self):
249 return dict(type=4, contents=self.share1a_type.pack(dict(common=self.common, merkle_link=self.merkle_link)))
251 def as_share1b(self):
252 return dict(type=5, contents=self.share1b_type.pack(dict(common=self.common, other_txs=self.other_txs)))
255 if not self.pow_hash <= self.header['bits'].target: # share1a
256 return self.as_share1a()
258 return self.as_share1b()
260 def check(self, tracker):
261 if self.share_data['previous_share_hash'] is not None:
262 previous_share = tracker.items[self.share_data['previous_share_hash']]
263 if isinstance(previous_share, NewShare):
264 from p2pool import p2p
265 raise p2p.PeerMisbehavingError('''Share can't follow NewShare''')
266 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
267 if share_info != self.share_info:
268 raise ValueError('share_info invalid')
269 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
270 raise ValueError('''gentx doesn't match hash_link''')
271 return gentx # only used by as_block
273 def get_other_tx_hashes(self, tracker):
276 def get_other_txs(self, tracker, known_txs):
279 def get_other_txs_size(self, tracker, known_txs):
282 def get_new_txs_size(self, known_txs):
285 def as_block(self, tracker, known_txs):
286 if self.other_txs is None:
287 raise ValueError('share does not contain all txs')
288 return dict(header=self.header, txs=[self.check(tracker)] + self.other_txs)
290 class NewShare(object):
295 small_block_header_type = pack.ComposedType([
296 ('version', pack.VarIntType()),
297 ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))),
298 ('timestamp', pack.IntType(32)),
299 ('bits', bitcoin_data.FloatingIntegerType()),
300 ('nonce', pack.IntType(32)),
303 share_info_type = pack.ComposedType([
304 ('share_data', pack.ComposedType([
305 ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
306 ('coinbase', pack.VarStrType()),
307 ('nonce', pack.IntType(32)),
308 ('pubkey_hash', pack.IntType(160)),
309 ('subsidy', pack.IntType(64)),
310 ('donation', pack.IntType(16)),
311 ('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)))),
312 ('desired_version', pack.VarIntType()),
314 ('new_transaction_hashes', pack.ListType(pack.IntType(256))),
315 ('transaction_hash_refs', pack.ListType(pack.ComposedType([ # compressed by referencing previous shares' hashes
316 ('share_count', pack.VarIntType()),
317 ('tx_count', pack.VarIntType()),
319 ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))),
320 ('max_bits', bitcoin_data.FloatingIntegerType()),
321 ('bits', bitcoin_data.FloatingIntegerType()),
322 ('timestamp', pack.IntType(32)),
325 share_type = pack.ComposedType([
326 ('min_header', small_block_header_type),
327 ('share_info', share_info_type),
328 ('ref_merkle_link', pack.ComposedType([
329 ('branch', pack.ListType(pack.IntType(256))),
330 ('index', pack.IntType(0)),
332 ('hash_link', hash_link_type),
333 ('merkle_link', pack.ComposedType([
334 ('branch', pack.ListType(pack.IntType(256))),
335 ('index', pack.IntType(0)), # it will always be 0
339 ref_type = pack.ComposedType([
340 ('identifier', pack.FixedStrType(64//8)),
341 ('share_info', share_info_type),
344 gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x20' + pack.IntType(256).pack(0))[:2]
347 def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes, net, known_txs=None):
348 previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None
350 height, last = tracker.get_height_and_last(share_data['previous_share_hash'])
351 assert height >= net.REAL_CHAIN_LENGTH or last is None
352 if height < net.TARGET_LOOKBEHIND:
353 pre_target3 = net.MAX_TARGET
355 attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True)
356 pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1
357 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10))
358 pre_target3 = math.clip(pre_target2, (0, net.MAX_TARGET))
359 max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3)
360 bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//10, pre_target3)))
362 weights, total_weight, donation_weight = tracker.get_cumulative_weights(share_data['previous_share_hash'],
363 min(height, net.REAL_CHAIN_LENGTH),
364 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target),
366 assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight)
368 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
369 this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash'])
370 amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder
371 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
373 if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()):
376 dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit
378 new_transaction_hashes = []
379 new_transaction_size = 0
380 transaction_hash_refs = []
381 other_transaction_hashes = []
383 for tx_hash in desired_other_transaction_hashes:
384 for i, share in enumerate(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))):
385 if tx_hash in share.new_transaction_hashes:
386 this = dict(share_count=i+1, tx_count=share.new_transaction_hashes.index(tx_hash))
389 if known_txs is not None:
390 this_size = len(bitcoin_data.tx_type.pack(known_txs[tx_hash]))
391 if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share
393 new_transaction_size += this_size
394 new_transaction_hashes.append(tx_hash)
395 this = dict(share_count=0, tx_count=len(new_transaction_hashes)-1)
396 transaction_hash_refs.append(this)
397 other_transaction_hashes.append(tx_hash)
400 share_data=share_data,
401 far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99),
404 timestamp=math.clip(desired_timestamp, (
405 (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1
406 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1),
407 )) if previous_share is not None else desired_timestamp,
408 new_transaction_hashes=new_transaction_hashes,
409 transaction_hash_refs=transaction_hash_refs,
415 previous_output=None,
417 script=share_data['coinbase'],
419 tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict(
421 script='\x20' + cls.get_ref_hash(net, share_info, ref_merkle_link),
426 def get_share(header, transactions):
427 min_header=dict(header);del min_header['merkle_root']
428 return cls(net, None, dict(
429 min_header=min_header,
430 share_info=share_info,
431 ref_merkle_link=dict(branch=[], index=0),
432 hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-4], cls.gentx_before_refhash),
433 merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0),
436 return share_info, gentx, other_transaction_hashes, get_share
439 def get_ref_hash(cls, net, share_info, ref_merkle_link):
440 return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict(
441 identifier=net.IDENTIFIER,
442 share_info=share_info,
443 ))), ref_merkle_link))
445 __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(' ')
447 def __init__(self, net, peer, contents):
450 self.contents = contents
452 self.min_header = contents['min_header']
453 self.share_info = contents['share_info']
454 self.hash_link = contents['hash_link']
455 self.merkle_link = contents['merkle_link']
457 if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100):
458 raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),))
460 if len(self.merkle_link['branch']) > 16:
461 raise ValueError('merkle branch too long!')
463 assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data'])
465 self.share_data = self.share_info['share_data']
466 self.max_target = self.share_info['max_bits'].target
467 self.target = self.share_info['bits'].target
468 self.timestamp = self.share_info['timestamp']
469 self.previous_hash = self.share_data['previous_share_hash']
470 self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash'])
471 self.desired_version = self.share_data['desired_version']
473 for x in self.share_info['transaction_hash_refs']:
474 assert x['share_count'] < 110
475 for i, x in enumerate(self.share_info['new_transaction_hashes']):
476 assert dict(share_count=0, tx_count=i) in self.share_info['transaction_hash_refs']
478 self.gentx_hash = check_hash_link(
480 self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(32).pack(0),
481 self.gentx_before_refhash,
483 merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link)
484 self.header = dict(self.min_header, merkle_root=merkle_root)
485 self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header))
486 self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header))
488 if self.target > net.MAX_TARGET:
489 from p2pool import p2p
490 raise p2p.PeerMisbehavingError('share target invalid')
492 if self.pow_hash > self.target:
493 from p2pool import p2p
494 raise p2p.PeerMisbehavingError('share PoW invalid')
496 self.new_transaction_hashes = self.share_info['new_transaction_hashes']
499 self.time_seen = time.time()
502 return 'Share' + repr((self.net, self.peer, self.contents))
505 return dict(type=self.VERSION, contents=self.share_type.pack(self.contents))
507 def check(self, tracker):
508 if self.share_data['previous_share_hash'] is not None:
509 previous_share = tracker.items[self.share_data['previous_share_hash']]
510 if isinstance(previous_share, Share):
511 if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH:
512 from p2pool import p2p
513 raise p2p.PeerMisbehavingError('NewShare without enough history')
515 # Share -> NewShare only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version
516 counts = get_desired_version_counts(tracker,
517 tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10)
518 if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100:
519 from p2pool import p2p
520 raise p2p.PeerMisbehavingError('NewShare without enough hash power upgraded')
522 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']]
524 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)
525 assert other_tx_hashes2 == other_tx_hashes
526 if share_info != self.share_info:
527 raise ValueError('share_info invalid')
528 if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash:
529 raise ValueError('''gentx doesn't match hash_link''')
531 if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link:
532 raise ValueError('merkle_link and other_tx_hashes do not match')
534 return gentx # only used by as_block
536 def get_other_tx_hashes(self, tracker):
537 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']]
539 def get_other_txs(self, tracker, known_txs):
540 other_tx_hashes = self.get_other_tx_hashes(tracker)
542 if not all(tx_hash in known_txs for tx_hash in other_tx_hashes):
543 return None # not all txs present
545 return [known_txs[tx_hash] for tx_hash in other_tx_hashes]
547 def get_other_txs_size(self, tracker, known_txs):
548 other_txs = self.get_other_txs(tracker, known_txs)
549 if other_txs is None:
550 return None # not all txs present
551 size = sum(len(bitcoin_data.tx_type.pack(tx)) for tx in other_txs)
553 def get_new_txs_size(self, known_txs):
554 if not all(tx_hash in known_txs for tx_hash in self.share_info['new_transaction_hashes']):
555 return None # not all txs present
556 return sum(len(bitcoin_data.tx_type.pack(known_txs[tx_hash])) for tx_hash in self.share_info['new_transaction_hashes'])
558 def as_block(self, tracker, known_txs):
559 other_txs = self.get_other_txs(tracker, known_txs)
560 if other_txs is None:
561 return None # not all txs present
562 return dict(header=self.header, txs=[self.check(tracker)] + other_txs)
565 class WeightsSkipList(forest.TrackerSkipList):
566 # share_count, weights, total_weight
568 def get_delta(self, element):
569 from p2pool.bitcoin import data as bitcoin_data
570 share = self.tracker.items[element]
571 att = bitcoin_data.target_to_average_attempts(share.target)
572 return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation']
574 def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)):
575 return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
577 def initial_solution(self, start, (max_shares, desired_weight)):
578 assert desired_weight % 65535 == 0, divmod(desired_weight, 65535)
581 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)):
582 if total_weight1 + total_weight2 > desired_weight and share_count2 == 1:
583 assert (desired_weight - total_weight1) % 65535 == 0
584 script, = weights2.iterkeys()
585 new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)}
586 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)
587 return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2
589 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
590 if share_count > max_shares or total_weight > desired_weight:
592 elif share_count == max_shares or total_weight == desired_weight:
597 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)):
598 assert share_count <= max_shares and total_weight <= desired_weight
599 assert share_count == max_shares or total_weight == desired_weight
600 return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight
602 class OkayTracker(forest.Tracker):
603 def __init__(self, net, my_share_hashes, my_doa_share_hashes):
604 forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
605 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
606 min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target),
609 self.verified = forest.Tracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs,
610 work=lambda share: bitcoin_data.target_to_average_attempts(share.target),
611 my_count=lambda share: 1 if share.hash in my_share_hashes else 0,
612 my_doa_count=lambda share: 1 if share.hash in my_doa_share_hashes else 0,
613 my_orphan_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'orphan' else 0,
614 my_dead_announce_count=lambda share: 1 if share.hash in my_share_hashes and share.share_data['stale_info'] == 'doa' else 0,
616 self.get_cumulative_weights = WeightsSkipList(self)
618 def attempt_verify(self, share):
619 if share.hash in self.verified.items:
621 height, last = self.get_height_and_last(share.hash)
622 if height < self.net.CHAIN_LENGTH + 1 and last is not None:
623 raise AssertionError()
627 log.err(None, 'Share check failed:')
630 self.verified.add(share)
633 def think(self, block_rel_height_func, previous_block, bits, known_txs):
637 # make 'unverified heads' set?
638 # for each overall head, attempt verification
639 # if it fails, attempt on parent, and repeat
640 # if no successful verification because of lack of parents, request parent
642 for head in set(self.heads) - set(self.verified.heads):
643 head_height, last = self.get_height_and_last(head)
645 for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))):
646 if self.attempt_verify(share):
648 if share.hash in self.heads:
653 self.items[random.choice(list(self.reverse[last]))].peer,
655 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
656 min(x.target for x in self.get_chain(head, min(head_height, 5))),
659 assert bad not in self.verified.items
660 assert bad in self.heads
665 # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed
666 for head in list(self.verified.heads):
667 head_height, last_hash = self.verified.get_height_and_last(head)
668 last_height, last_last_hash = self.get_height_and_last(last_hash)
669 # XXX review boundary conditions
670 want = max(self.net.CHAIN_LENGTH - head_height, 0)
671 can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height
673 #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get
674 for share in self.get_chain(last_hash, get):
675 if not self.attempt_verify(share):
677 if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
679 self.items[random.choice(list(self.verified.reverse[last_hash]))].peer,
681 max(x.timestamp for x in self.get_chain(head, min(head_height, 5))),
682 min(x.target for x in self.get_chain(head, min(head_height, 5))),
686 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)
688 print len(decorated_tails), 'tails:'
689 for score, tail_hash in decorated_tails:
690 print format_hash(tail_hash), score
691 best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None)
693 # decide best verified head
694 decorated_heads = sorted(((
695 self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
696 #self.items[h].peer is None,
697 self.items[h].pow_hash <= self.items[h].header['bits'].target, # is block solution
698 (self.items[h].header['previous_block'], self.items[h].header['bits']) == (previous_block, bits) or self.items[h].peer is None,
699 self.items[h].get_other_txs(self, known_txs) is not None,
700 self.items[h].get_other_txs_size(self, known_txs) < 1000000,
701 self.items[h].get_new_txs_size(known_txs) < 50000,
702 -self.items[h].time_seen,
703 ), h) for h in self.verified.tails.get(best_tail, []))
705 print len(decorated_heads), 'heads. Top 10:'
706 for score, head_hash in decorated_heads[-10:]:
707 print ' ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score
708 best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None)
712 for i in xrange(1000):
714 for share_hash, tail in self.heads.iteritems():
715 if share_hash in [head_hash for score, head_hash in decorated_heads[-5:]]:
718 if self.items[share_hash].time_seen > time.time() - 300:
721 if share_hash not in self.verified.items and max(self.items[after_tail_hash].time_seen for after_tail_hash in self.reverse.get(tail)) > time.time() - 120: # XXX stupid
724 to_remove.add(share_hash)
727 for share_hash in to_remove:
728 if share_hash in self.verified.items:
729 self.verified.remove(share_hash)
730 self.remove(share_hash)
731 #print "_________", to_remove
734 for i in xrange(1000):
736 for tail, heads in self.tails.iteritems():
737 if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
739 for aftertail in self.reverse.get(tail, set()):
740 if len(self.reverse[self.items[aftertail].previous_hash]) > 1: # XXX
743 to_remove.add(aftertail)
746 # if removed from this, it must be removed from verified
748 for aftertail in to_remove:
749 if self.items[aftertail].previous_hash not in self.tails:
750 print "erk", aftertail, self.items[aftertail].previous_hash
752 if aftertail in self.verified.items:
753 self.verified.remove(aftertail)
754 self.remove(aftertail)
756 #print "removed! %i %f" % (len(to_remove), (end - start)/len(to_remove))
759 best_share = self.items[best]
760 if (best_share.header['previous_block'], best_share.header['bits']) != (previous_block, bits) and best_share.header_hash != previous_block and best_share.peer is not None:
762 print 'Stale detected! %x < %x' % (best_share.header['previous_block'], previous_block)
763 best = best_share.previous_hash
764 elif best_share.get_other_txs(self, known_txs) is None:
765 print 'Share with incomplete transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
766 best = best_share.previous_hash
767 elif best_share.get_other_txs_size(self, known_txs) > 1000000:
768 print >>sys.stderr, 'Share with too many transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
769 best = best_share.previous_hash
770 elif best_share.get_new_txs_size(known_txs) > 50000:
771 print >>sys.stderr, 'Share with too many new transactions detected! Jumping from %s to %s!' % (format_hash(best), format_hash(best_share.previous_hash))
772 best = best_share.previous_hash
774 timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600
775 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
777 timestamp_cutoff = int(time.time()) - 24*60*60
778 target_cutoff = 2**256-1
781 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))
782 for peer, hash, ts, targ in desired:
783 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
785 return best, [(peer, hash) for peer, hash, ts, targ in desired if ts >= timestamp_cutoff]
787 def score(self, share_hash, block_rel_height_func):
788 # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time
790 head_height = self.verified.get_height(share_hash)
791 if head_height < self.net.CHAIN_LENGTH:
792 return head_height, None
794 end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16)
796 block_height = max(block_rel_height_func(share.header['previous_block']) for share in
797 self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16))
799 return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work//((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD)
801 def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False):
803 near = tracker.items[previous_share_hash]
804 far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
805 attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work
806 time = near.timestamp - far.timestamp
810 return attempts//time
813 def get_average_stale_prop(tracker, share_hash, lookbehind):
814 stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None)
815 return stales/(lookbehind + stales)
817 def get_stale_counts(tracker, share_hash, lookbehind, rates=False):
819 for share in tracker.get_chain(share_hash, lookbehind - 1):
820 res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target)
821 s = share.share_data['stale_info']
823 res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target)
825 dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp
826 res = dict((k, v/dt) for k, v in res.iteritems())
829 def get_user_stale_props(tracker, share_hash, lookbehind):
831 for share in tracker.get_chain(share_hash, lookbehind - 1):
832 stale, total = res.get(share.share_data['pubkey_hash'], (0, 0))
834 if share.share_data['stale_info'] is not None:
837 res[share.share_data['pubkey_hash']] = stale, total
838 return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems())
840 def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net):
841 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))
842 res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems())
843 res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues())
846 def get_desired_version_counts(tracker, best_share_hash, dist):
848 for share in tracker.get_chain(best_share_hash, dist):
849 res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target)
852 def get_warnings(tracker, best_share, net, bitcoind_warning, bitcoind_work_value):
855 desired_version_counts = get_desired_version_counts(tracker, best_share,
856 min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share)))
857 majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k])
858 if majority_desired_version > NewShare.VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2:
859 res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n'
860 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % (
861 majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues())))
863 if bitcoind_warning is not None:
864 res.append('(from bitcoind) %s' % (bitcoind_warning,))
866 if time.time() > bitcoind_work_value['last_update'] + 60:
867 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']),))
874 return '%08x' % (x % 2**32)
876 class ShareStore(object):
877 def __init__(self, prefix, net):
878 self.filename = prefix
879 self.dirname = os.path.dirname(os.path.abspath(prefix))
880 self.filename = os.path.basename(os.path.abspath(prefix))
882 self.known = None # will be filename -> set of share hashes, set of verified hashes
883 self.known_desired = None
885 def get_shares(self):
886 if self.known is not None:
887 raise AssertionError()
889 filenames, next = self.get_filenames_and_next()
890 for filename in filenames:
891 share_hashes, verified_hashes = known.setdefault(filename, (set(), set()))
892 with open(filename, 'rb') as f:
895 type_id_str, data_hex = line.strip().split(' ')
896 type_id = int(type_id_str)
902 verified_hash = int(data_hex, 16)
903 yield 'verified_hash', verified_hash
904 verified_hashes.add(verified_hash)
906 raw_share = share_type.unpack(data_hex.decode('hex'))
907 if raw_share['type'] in [0, 1, 2, 3, 6, 7]:
909 share = load_share(raw_share, self.net, None)
911 share_hashes.add(share.hash)
913 raise NotImplementedError("share type %i" % (type_id,))
915 log.err(None, "HARMLESS error while reading saved shares, continuing where left off:")
917 self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems())
919 def _add_line(self, line):
920 filenames, next = self.get_filenames_and_next()
921 if filenames and os.path.getsize(filenames[-1]) < 10e6:
922 filename = filenames[-1]
926 with open(filename, 'ab') as f:
931 def add_share(self, share):
932 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
933 if share.hash in share_hashes:
936 filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex')))
937 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
938 share_hashes.add(share.hash)
939 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
940 share_hashes.add(share.hash)
942 def add_verified_hash(self, share_hash):
943 for filename, (share_hashes, verified_hashes) in self.known.iteritems():
944 if share_hash in verified_hashes:
947 filename = self._add_line("%i %x" % (2, share_hash))
948 share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set()))
949 verified_hashes.add(share_hash)
950 share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set()))
951 verified_hashes.add(share_hash)
953 def get_filenames_and_next(self):
954 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())
955 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)))
957 def forget_share(self, share_hash):
958 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
959 if share_hash in share_hashes:
960 share_hashes.remove(share_hash)
963 def forget_verified_share(self, share_hash):
964 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
965 if share_hash in verified_hashes:
966 verified_hashes.remove(share_hash)
969 def check_remove(self):
971 for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems():
972 #print filename, len(share_hashes) + len(verified_hashes)
973 if not share_hashes and not verified_hashes:
974 to_remove.add(filename)
975 for filename in to_remove:
976 self.known.pop(filename)
977 self.known_desired.pop(filename)
979 print "REMOVED", filename