4 from twisted.internet import defer
7 from p2pool.bitcoin import data as bitcoin_data
8 from p2pool.util import deferral, jsonrpc
10 @deferral.retry('Error while checking Bitcoin connection:', 1)
11 @defer.inlineCallbacks
12 def check(bitcoind, net):
13 if not (yield net.PARENT.RPC_CHECK(bitcoind)):
14 print >>sys.stderr, " Check failed! Make sure that you're connected to the right bitcoind with --bitcoind-rpc-port!"
15 raise deferral.RetrySilentlyException()
16 if not net.VERSION_CHECK((yield bitcoind.rpc_getinfo())['version']):
17 print >>sys.stderr, ' Bitcoin version too old! Upgrade to 0.6.4 or newer!'
18 raise deferral.RetrySilentlyException()
20 @deferral.retry('Error getting work from bitcoind:', 3)
21 @defer.inlineCallbacks
22 def getwork(bitcoind, use_getblocktemplate=False):
24 if use_getblocktemplate:
25 return bitcoind.rpc_getblocktemplate(dict(mode='template'))
27 return bitcoind.rpc_getmemorypool()
32 except jsonrpc.Error_for_code(-32601): # Method not found
33 use_getblocktemplate = not use_getblocktemplate
38 except jsonrpc.Error_for_code(-32601): # Method not found
39 print >>sys.stderr, 'Error: Bitcoin version too old! Upgrade to v0.5 or newer!'
40 raise deferral.RetrySilentlyException()
41 packed_transactions = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['transactions']]
43 transactions=map(bitcoin_data.tx_type.unpack, packed_transactions)
44 transaction_hashes=map(bitcoin_data.hash256, packed_transactions)
48 for tx in transactions:
49 if tx.timestamp > txn_timestamp:
50 txn_timestamp = tx.timestamp
52 if 'height' not in work:
53 work['height'] = (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
55 assert work['height'] == (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
56 defer.returnValue(dict(
57 version=work['version'],
58 previous_block=int(work['previousblockhash'], 16),
59 transactions=transactions,
60 transaction_hashes=transaction_hashes,
61 transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']],
62 subsidy=work['coinbasevalue'],
63 time=work['time'] if 'time' in work else work['curtime'],
64 txn_timestamp=txn_timestamp,
65 bits=bitcoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else bitcoin_data.FloatingInteger(work['bits']),
66 coinbaseflags=work['coinbaseflags'].decode('hex') if 'coinbaseflags' in work else ''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()) if 'coinbaseaux' in work else '',
67 height=work['height'],
68 last_update=time.time(),
69 use_getblocktemplate=use_getblocktemplate,
73 @deferral.retry('Error submitting primary block: (will retry)', 10, 10)
74 def submit_block_p2p(block, factory, net):
75 if factory.conn.value is None:
76 print >>sys.stderr, 'No bitcoind connection when block submittal attempted! %s%064x' % (net.PARENT.BLOCK_EXPLORER_URL_PREFIX, self.node.net.PARENT.BLOCKHASH_FUNC(bitcoin_data.block_header_type.pack(block['header'])))
77 raise deferral.RetrySilentlyException()
78 factory.conn.value.send_block(block=block)
80 @deferral.retry('Error submitting block: (will retry)', 10, 10)
81 @defer.inlineCallbacks
82 def submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net):
84 if bitcoind_work.value['use_getblocktemplate']:
85 result = yield bitcoind.rpc_submitblock(bitcoin_data.block_type.pack(block).encode('hex'))
86 success = result is None
88 print bitcoin_data.block_type.pack(block).encode('hex')
90 result = yield bitcoind.rpc_getmemorypool(bitcoin_data.block_type.pack(block).encode('hex'))
92 success_expected = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(block['header'])) <= block['header']['bits'].target
93 if (not success and success_expected and not ignore_failure) or (success and not success_expected):
94 print >>sys.stderr, 'Block submittal result: %s (%r) Expected: %s' % (success, result, success_expected)
96 def submit_block(block, ignore_failure, factory, bitcoind, bitcoind_work, net):
97 #submit_block_p2p(block, factory, net)
98 submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net)