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']]
42 if 'height' not in work:
43 work['height'] = (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
45 assert work['height'] == (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
46 defer.returnValue(dict(
47 version=work['version'],
48 previous_block=int(work['previousblockhash'], 16),
49 transactions=map(bitcoin_data.tx_type.unpack, packed_transactions),
50 transaction_hashes=map(bitcoin_data.hash256, packed_transactions),
51 transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']],
52 subsidy=work['coinbasevalue'],
53 time=work['time'] if 'time' in work else work['curtime'],
54 bits=bitcoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else bitcoin_data.FloatingInteger(work['bits']),
55 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 '',
56 height=work['height'],
57 last_update=time.time(),
58 use_getblocktemplate=use_getblocktemplate,
62 @deferral.retry('Error submitting primary block: (will retry)', 10, 10)
63 def submit_block_p2p(block, factory, net):
64 if factory.conn.value is None:
65 print >>sys.stderr, 'No bitcoind connection when block submittal attempted! %s%064x' % (net.PARENT.BLOCK_EXPLORER_URL_PREFIX, bitcoin_data.hash256(bitcoin_data.block_header_type.pack(block['header'])))
66 raise deferral.RetrySilentlyException()
67 factory.conn.value.send_block(block=block)
69 @deferral.retry('Error submitting block: (will retry)', 10, 10)
70 @defer.inlineCallbacks
71 def submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net):
72 if bitcoind_work.value['use_getblocktemplate']:
74 result = yield bitcoind.rpc_submitblock(bitcoin_data.block_type.pack(block).encode('hex'))
75 except jsonrpc.Error_for_code(-32601): # Method not found, for older litecoin versions
76 result = yield bitcoind.rpc_getblocktemplate(dict(mode='submit', data=bitcoin_data.block_type.pack(block).encode('hex')))
77 success = result is None
79 result = yield bitcoind.rpc_getmemorypool(bitcoin_data.block_type.pack(block).encode('hex'))
81 success_expected = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(block['header'])) <= block['header']['bits'].target
82 if (not success and success_expected and not ignore_failure) or (success and not success_expected):
83 print >>sys.stderr, 'Block submittal result: %s (%r) Expected: %s' % (success, result, success_expected)
85 def submit_block(block, ignore_failure, factory, bitcoind, bitcoind_work, net):
86 submit_block_p2p(block, factory, net)
87 submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net)