3d5810b75c4062ee48fa9d02d932eea701902892
[p2pool.git] / p2pool / bitcoin / helper.py
1 import sys
2 import time
3
4 from twisted.internet import defer
5
6 import p2pool
7 from p2pool.bitcoin import data as bitcoin_data
8 from p2pool.util import deferral, jsonrpc
9
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()
19
20 @deferral.retry('Error getting work from bitcoind:', 3)
21 @defer.inlineCallbacks
22 def getwork(bitcoind, use_getblocktemplate=False):
23     def go():
24         if use_getblocktemplate:
25             return bitcoind.rpc_getblocktemplate(dict(mode='template'))
26         else:
27             return bitcoind.rpc_getmemorypool()
28     try:
29         work = yield go()
30     except jsonrpc.Error_for_code(-32601): # Method not found
31         use_getblocktemplate = not use_getblocktemplate
32         try:
33             work = yield go()
34         except jsonrpc.Error_for_code(-32601): # Method not found
35             print >>sys.stderr, 'Error: Bitcoin version too old! Upgrade to v0.5 or newer!'
36             raise deferral.RetrySilentlyException()
37     packed_transactions = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['transactions']]
38     if 'height' not in work:
39         work['height'] = (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
40     elif p2pool.DEBUG:
41         assert work['height'] == (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
42     defer.returnValue(dict(
43         version=work['version'],
44         previous_block=int(work['previousblockhash'], 16),
45         transactions=map(bitcoin_data.tx_type.unpack, packed_transactions),
46         transaction_hashes=map(bitcoin_data.hash256, packed_transactions),
47         subsidy=work['coinbasevalue'],
48         time=work['time'] if 'time' in work else work['curtime'],
49         bits=bitcoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else bitcoin_data.FloatingInteger(work['bits']),
50         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 '',
51         height=work['height'],
52         last_update=time.time(),
53         use_getblocktemplate=use_getblocktemplate,
54     ))
55
56 @deferral.retry('Error submitting primary block: (will retry)', 10, 10)
57 def submit_block_p2p(block, factory, net):
58     if factory.conn.value is None:
59         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'])))
60         raise deferral.RetrySilentlyException()
61     factory.conn.value.send_block(block=block)
62
63 @deferral.retry('Error submitting block: (will retry)', 10, 10)
64 @defer.inlineCallbacks
65 def submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net):
66     if bitcoind_work.value['use_getblocktemplate']:
67         result = yield bitcoind.rpc_submitblock(bitcoin_data.block_type.pack(block).encode('hex'))
68         success = result is None
69     else:
70         result = yield bitcoind.rpc_getmemorypool(bitcoin_data.block_type.pack(block).encode('hex'))
71         success = result
72     success_expected = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(block['header'])) <= block['header']['bits'].target
73     if (not success and success_expected and not ignore_failure) or (success and not success_expected):
74         print >>sys.stderr, 'Block submittal result: %s (%r) Expected: %s' % (success, result, success_expected)
75
76 def submit_block(block, ignore_failure, factory, bitcoind, bitcoind_work, net):
77     submit_block_p2p(block, factory, net)
78     submit_block_rpc(block, ignore_failure, bitcoind, bitcoind_work, net)