2 # Copyright (c) 2017 The Bitcoin Core developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """Class for bitcoind node under test"""
16 from .authproxy
import JSONRPCException
25 BITCOIND_PROC_WAIT_TIMEOUT
= 60
28 """A class for representing a bitcoind node under test.
32 - state about the node (whether it's running, etc)
33 - a Python subprocess.Popen object representing the running process
34 - an RPC connection to the node
35 - one or more P2P connections to the node
38 To make things easier for the test writer, any unrecognised messages will
39 be dispatched to the RPC connection."""
41 def __init__(self
, i
, dirname
, extra_args
, rpchost
, timewait
, binary
, stderr
, mocktime
, coverage_dir
):
43 self
.datadir
= os
.path
.join(dirname
, "node" + str(i
))
44 self
.rpchost
= rpchost
46 self
.rpc_timeout
= timewait
48 # Wait for up to 60 seconds for the RPC server to respond
51 self
.binary
= os
.getenv("BITCOIND", "bitcoind")
55 self
.coverage_dir
= coverage_dir
56 # Most callers will just need to add extra args to the standard list below. For those callers that need more flexibity, they can just set the args property directly.
57 self
.extra_args
= extra_args
58 self
.args
= [self
.binary
, "-datadir=" + self
.datadir
, "-server", "-keypool=1", "-discover=0", "-rest", "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-mocktime=" + str(mocktime
), "-uacomment=testnode%d" % i
]
60 self
.cli
= TestNodeCLI(os
.getenv("BITCOINCLI", "bitcoin-cli"), self
.datadir
)
64 self
.rpc_connected
= False
67 self
.log
= logging
.getLogger('TestFramework.node%d' % i
)
71 def __getattr__(self
, name
):
72 """Dispatches any unrecognised messages to the RPC connection."""
73 assert self
.rpc_connected
and self
.rpc
is not None, "Error: no RPC connection"
74 return getattr(self
.rpc
, name
)
76 def start(self
, extra_args
=None, stderr
=None):
78 if extra_args
is None:
79 extra_args
= self
.extra_args
82 self
.process
= subprocess
.Popen(self
.args
+ extra_args
, stderr
=stderr
)
84 self
.log
.debug("bitcoind started, waiting for RPC to come up")
86 def wait_for_rpc_connection(self
):
87 """Sets up an RPC connection to the bitcoind process. Returns False if unable to connect."""
88 # Poll at a rate of four times per second
90 for _
in range(poll_per_s
* self
.rpc_timeout
):
91 assert self
.process
.poll() is None, "bitcoind exited with status %i during initialization" % self
.process
.returncode
93 self
.rpc
= get_rpc_proxy(rpc_url(self
.datadir
, self
.index
, self
.rpchost
), self
.index
, timeout
=self
.rpc_timeout
, coveragedir
=self
.coverage_dir
)
94 self
.rpc
.getblockcount()
95 # If the call to getblockcount() succeeds then the RPC connection is up
96 self
.rpc_connected
= True
97 self
.url
= self
.rpc
.url
98 self
.log
.debug("RPC successfully started")
101 if e
.errno
!= errno
.ECONNREFUSED
: # Port not yet open?
102 raise # unknown IO error
103 except JSONRPCException
as e
: # Initialization phase
104 if e
.error
['code'] != -28: # RPC in warmup?
105 raise # unknown JSON RPC exception
106 except ValueError as e
: # cookie file not found and no rpcuser or rpcassword. bitcoind still starting
107 if "No RPC credentials" not in str(e
):
109 time
.sleep(1.0 / poll_per_s
)
110 raise AssertionError("Unable to connect to bitcoind")
112 def get_wallet_rpc(self
, wallet_name
):
113 assert self
.rpc_connected
115 wallet_path
= "wallet/%s" % wallet_name
116 return self
.rpc
/ wallet_path
122 self
.log
.debug("Stopping node")
125 except http
.client
.CannotSendRequest
:
126 self
.log
.exception("Unable to stop node.")
129 def is_node_stopped(self
):
130 """Checks whether the node has stopped.
132 Returns True if the node has stopped. False otherwise.
133 This method is responsible for freeing resources (self.process)."""
136 return_code
= self
.process
.poll()
137 if return_code
is None:
140 # process has stopped. Assert that it didn't return an error code.
141 assert_equal(return_code
, 0)
144 self
.rpc_connected
= False
146 self
.log
.debug("Node stopped")
149 def wait_until_stopped(self
, timeout
=BITCOIND_PROC_WAIT_TIMEOUT
):
150 wait_until(self
.is_node_stopped
, timeout
=timeout
)
152 def node_encrypt_wallet(self
, passphrase
):
153 """"Encrypts the wallet.
155 This causes bitcoind to shutdown, so this method takes
156 care of cleaning up resources."""
157 self
.encryptwallet(passphrase
)
158 self
.wait_until_stopped()
160 def add_p2p_connection(self
, p2p_conn
, *args
, **kwargs
):
161 """Add a p2p connection to the node.
163 This method adds the p2p connection to the self.p2ps list and also
164 returns the connection to the caller."""
165 if 'dstport' not in kwargs
:
166 kwargs
['dstport'] = p2p_port(self
.index
)
167 if 'dstaddr' not in kwargs
:
168 kwargs
['dstaddr'] = '127.0.0.1'
170 p2p_conn
.peer_connect(*args
, **kwargs
)
171 self
.p2ps
.append(p2p_conn
)
177 """Return the first p2p connection
179 Convenience property - most tests only use a single p2p connection to each
180 node, so this saves having to write node.p2ps[0] many times."""
181 assert self
.p2ps
, "No p2p connection"
184 def disconnect_p2ps(self
):
185 """Close all p2p connections to the node."""
192 """Interface to bitcoin-cli for an individual node"""
194 def __init__(self
, binary
, datadir
):
197 self
.datadir
= datadir
200 def __call__(self
, *args
, input=None):
201 # TestNodeCLI is callable with bitcoin-cli command-line args
202 self
.args
= [str(arg
) for arg
in args
]
206 def __getattr__(self
, command
):
207 def dispatcher(*args
, **kwargs
):
208 return self
.send_cli(command
, *args
, **kwargs
)
211 def send_cli(self
, command
, *args
, **kwargs
):
212 """Run bitcoin-cli command. Deserializes returned string as python object."""
214 pos_args
= [str(arg
) for arg
in args
]
215 named_args
= [str(key
) + "=" + str(value
) for (key
, value
) in kwargs
.items()]
216 assert not (pos_args
and named_args
), "Cannot use positional arguments and named arguments in the same bitcoin-cli call"
217 p_args
= [self
.binary
, "-datadir=" + self
.datadir
] + self
.args
220 p_args
+= [command
] + pos_args
+ named_args
221 process
= subprocess
.Popen(p_args
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, universal_newlines
=True)
222 cli_stdout
, cli_stderr
= process
.communicate(input=self
.input)
223 returncode
= process
.poll()
225 # Ignore cli_stdout, raise with cli_stderr
226 raise subprocess
.CalledProcessError(returncode
, self
.binary
, output
=cli_stderr
)
227 return json
.loads(cli_stdout
, parse_float
=decimal
.Decimal
)