1 # Copyright (c) 2014 The Bitcoin Core developers
2 # Distributed under the MIT software license, see the accompanying
3 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 # Helpful routines for regression testing
8 # Add python-bitcoinrpc to module search path:
11 sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc"))
13 from decimal import Decimal, ROUND_DOWN
21 from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
25 return 11000 + n + os.getpid()%999
27 return 12000 + n + os.getpid()%999
29 def check_json_precision():
30 """Make sure json library being used does not lose precision converting BTC values"""
31 n = Decimal("20000000.00000003")
32 satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
33 if satoshis != 2000000000000003:
34 raise RuntimeError("JSON encode/decode loses precision")
36 def sync_blocks(rpc_connections):
38 Wait until everybody has the same block count
41 counts = [ x.getblockcount() for x in rpc_connections ]
42 if counts == [ counts[0] ]*len(counts):
46 def sync_mempools(rpc_connections):
48 Wait until everybody has the same transactions in their memory
52 pool = set(rpc_connections[0].getrawmempool())
54 for i in range(1, len(rpc_connections)):
55 if set(rpc_connections[i].getrawmempool()) == pool:
56 num_match = num_match+1
57 if num_match == len(rpc_connections):
61 bitcoind_processes = {}
63 def initialize_datadir(dirname, n):
64 datadir = os.path.join(dirname, "node"+str(n))
65 if not os.path.isdir(datadir):
67 with open(os.path.join(datadir, "bitcoin.conf"), 'w') as f:
68 f.write("regtest=1\n");
69 f.write("rpcuser=rt\n");
70 f.write("rpcpassword=rt\n");
71 f.write("port="+str(p2p_port(n))+"\n");
72 f.write("rpcport="+str(rpc_port(n))+"\n");
75 def initialize_chain(test_dir):
77 Create (or copy from cache) a 200-block-long chain and
79 bitcoind and bitcoin-cli must be in search path.
82 if not os.path.isdir(os.path.join("cache", "node0")):
83 devnull = open("/dev/null", "w+")
84 # Create cache directories, run bitcoinds:
86 datadir=initialize_datadir("cache", i)
87 args = [ os.getenv("BITCOIND", "bitcoind"), "-keypool=1", "-datadir="+datadir, "-discover=0" ]
89 args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
90 bitcoind_processes[i] = subprocess.Popen(args)
91 subprocess.check_call([ os.getenv("BITCOINCLI", "bitcoin-cli"), "-datadir="+datadir,
92 "-rpcwait", "getblockcount"], stdout=devnull)
98 rpcs.append(AuthServiceProxy(url))
100 sys.stderr.write("Error connecting to "+url+"\n")
103 # Create a 200-block-long chain; each of the 4 nodes
104 # gets 25 mature blocks and 25 immature.
105 # blocks are created with timestamps 10 minutes apart, starting
107 block_time = 1388534400
109 for peer in range(4):
111 set_node_times(rpcs, block_time)
112 rpcs[peer].setgenerate(True, 1)
114 # Must sync before next peer starts generating blocks
117 # Shut them down, and clean up cache directories:
121 os.remove(log_filename("cache", i, "debug.log"))
122 os.remove(log_filename("cache", i, "db.log"))
123 os.remove(log_filename("cache", i, "peers.dat"))
124 os.remove(log_filename("cache", i, "fee_estimates.dat"))
127 from_dir = os.path.join("cache", "node"+str(i))
128 to_dir = os.path.join(test_dir, "node"+str(i))
129 shutil.copytree(from_dir, to_dir)
130 initialize_datadir(test_dir, i) # Overwrite port/rpcport in bitcoin.conf
132 def initialize_chain_clean(test_dir, num_nodes):
134 Create an empty blockchain and num_nodes wallets.
135 Useful if a test case wants complete control over initialization.
137 for i in range(num_nodes):
138 datadir=initialize_datadir(test_dir, i)
141 def _rpchost_to_args(rpchost):
142 '''Convert optional IP:port spec to rpcconnect/rpcport args'''
146 match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
148 raise ValueError('Invalid RPC host spec ' + rpchost)
150 rpcconnect = match.group(1)
151 rpcport = match.group(2)
153 if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
154 rpcconnect = rpcconnect[1:-1]
156 rv = ['-rpcconnect=' + rpcconnect]
158 rv += ['-rpcport=' + rpcport]
161 def start_node(i, dirname, extra_args=None, rpchost=None):
163 Start a bitcoind and return RPC connection to it
165 datadir = os.path.join(dirname, "node"+str(i))
166 args = [ os.getenv("BITCOIND", "bitcoind"), "-datadir="+datadir, "-keypool=1", "-discover=0" ]
167 if extra_args is not None: args.extend(extra_args)
168 bitcoind_processes[i] = subprocess.Popen(args)
169 devnull = open("/dev/null", "w+")
170 subprocess.check_call([ os.getenv("BITCOINCLI", "bitcoin-cli"), "-datadir="+datadir] +
171 _rpchost_to_args(rpchost) +
172 ["-rpcwait", "getblockcount"], stdout=devnull)
174 url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
175 proxy = AuthServiceProxy(url)
176 proxy.url = url # store URL on proxy for info
179 def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None):
181 Start multiple bitcoinds, return RPC connections to them
183 if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
184 return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ]
186 def log_filename(dirname, n_node, logname):
187 return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
189 def stop_node(node, i):
191 bitcoind_processes[i].wait()
192 del bitcoind_processes[i]
194 def stop_nodes(nodes):
197 del nodes[:] # Emptying array closes connections as a side effect
199 def set_node_times(nodes, t):
203 def wait_bitcoinds():
204 # Wait for all bitcoinds to cleanly exit
205 for bitcoind in bitcoind_processes.values():
207 bitcoind_processes.clear()
209 def connect_nodes(from_connection, node_num):
210 ip_port = "127.0.0.1:"+str(p2p_port(node_num))
211 from_connection.addnode(ip_port, "onetry")
212 # poll until version handshake complete to avoid race conditions
213 # with transaction relaying
214 while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
217 def connect_nodes_bi(nodes, a, b):
218 connect_nodes(nodes[a], b)
219 connect_nodes(nodes[b], a)
221 def find_output(node, txid, amount):
223 Return index to output of txid with value amount
224 Raises exception if there is none.
226 txdata = node.getrawtransaction(txid, 1)
227 for i in range(len(txdata["vout"])):
228 if txdata["vout"][i]["value"] == amount:
230 raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
233 def gather_inputs(from_node, amount_needed, confirmations_required=1):
235 Return a random set of unspent txouts that are enough to pay amount_needed
237 assert(confirmations_required >=0)
238 utxo = from_node.listunspent(confirmations_required)
241 total_in = Decimal("0.00000000")
242 while total_in < amount_needed and len(utxo) > 0:
244 total_in += t["amount"]
245 inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
246 if total_in < amount_needed:
247 raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
248 return (total_in, inputs)
250 def make_change(from_node, amount_in, amount_out, fee):
252 Create change output(s), return them
255 amount = amount_out+fee
256 change = amount_in - amount
257 if change > amount*2:
258 # Create an extra change output to break up big inputs
259 change_address = from_node.getnewaddress()
260 # Split change in two, being careful of rounding:
261 outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
262 change = amount_in - amount - outputs[change_address]
264 outputs[from_node.getnewaddress()] = change
267 def send_zeropri_transaction(from_node, to_node, amount, fee):
269 Create&broadcast a zero-priority transaction.
270 Returns (txid, hex-encoded-txdata)
271 Ensures transaction is zero-priority by first creating a send-to-self,
272 then using it's output
275 # Create a send-to-self with confirmed inputs:
276 self_address = from_node.getnewaddress()
277 (total_in, inputs) = gather_inputs(from_node, amount+fee*2)
278 outputs = make_change(from_node, total_in, amount+fee, fee)
279 outputs[self_address] = float(amount+fee)
281 self_rawtx = from_node.createrawtransaction(inputs, outputs)
282 self_signresult = from_node.signrawtransaction(self_rawtx)
283 self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)
285 vout = find_output(from_node, self_txid, amount+fee)
286 # Now immediately spend the output to create a 1-input, 1-output
287 # zero-priority transaction:
288 inputs = [ { "txid" : self_txid, "vout" : vout } ]
289 outputs = { to_node.getnewaddress() : float(amount) }
291 rawtx = from_node.createrawtransaction(inputs, outputs)
292 signresult = from_node.signrawtransaction(rawtx)
293 txid = from_node.sendrawtransaction(signresult["hex"], True)
295 return (txid, signresult["hex"])
297 def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
299 Create a random zero-priority transaction.
300 Returns (txid, hex-encoded-transaction-data, fee)
302 from_node = random.choice(nodes)
303 to_node = random.choice(nodes)
304 fee = min_fee + fee_increment*random.randint(0,fee_variants)
305 (txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
306 return (txid, txhex, fee)
308 def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
310 Create a random transaction.
311 Returns (txid, hex-encoded-transaction-data, fee)
313 from_node = random.choice(nodes)
314 to_node = random.choice(nodes)
315 fee = min_fee + fee_increment*random.randint(0,fee_variants)
317 (total_in, inputs) = gather_inputs(from_node, amount+fee)
318 outputs = make_change(from_node, total_in, amount, fee)
319 outputs[to_node.getnewaddress()] = float(amount)
321 rawtx = from_node.createrawtransaction(inputs, outputs)
322 signresult = from_node.signrawtransaction(rawtx)
323 txid = from_node.sendrawtransaction(signresult["hex"], True)
325 return (txid, signresult["hex"], fee)
327 def assert_equal(thing1, thing2):
329 raise AssertionError("%s != %s"%(str(thing1),str(thing2)))