]> Git Repo - VerusCoin.git/blob - qa/rpc-tests/util.py
print the caught error instead of raising an error
[VerusCoin.git] / qa / rpc-tests / util.py
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.
4 #
5 # Helpful routines for regression testing
6 #
7
8 # Add python-bitcoinrpc to module search path:
9 import os
10 import sys
11 sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc"))
12
13 from decimal import Decimal, ROUND_DOWN
14 import json
15 import random
16 import shutil
17 import subprocess
18 import time
19 import re
20
21 from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
22 from util import *
23
24 def p2p_port(n):
25     return 11000 + n + os.getpid()%999
26 def rpc_port(n):
27     return 12000 + n + os.getpid()%999
28
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")
35
36 def sync_blocks(rpc_connections):
37     """
38     Wait until everybody has the same block count
39     """
40     while True:
41         counts = [ x.getblockcount() for x in rpc_connections ]
42         if counts == [ counts[0] ]*len(counts):
43             break
44         time.sleep(1)
45
46 def sync_mempools(rpc_connections):
47     """
48     Wait until everybody has the same transactions in their memory
49     pools
50     """
51     while True:
52         pool = set(rpc_connections[0].getrawmempool())
53         num_match = 1
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):
58             break
59         time.sleep(1)
60
61 bitcoind_processes = {}
62
63 def initialize_datadir(dirname, n):
64     datadir = os.path.join(dirname, "node"+str(n))
65     if not os.path.isdir(datadir):
66         os.makedirs(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");
73     return datadir
74
75 def initialize_chain(test_dir):
76     """
77     Create (or copy from cache) a 200-block-long chain and
78     4 wallets.
79     bitcoind and bitcoin-cli must be in search path.
80     """
81
82     if not os.path.isdir(os.path.join("cache", "node0")):
83         devnull = open("/dev/null", "w+")
84         # Create cache directories, run bitcoinds:
85         for i in range(4):
86             datadir=initialize_datadir("cache", i)
87             args = [ os.getenv("BITCOIND", "bitcoind"), "-keypool=1", "-datadir="+datadir, "-discover=0" ]
88             if i > 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)
93         devnull.close()
94         rpcs = []
95         for i in range(4):
96             try:
97                 url = "http://rt:[email protected]:%d"%(rpc_port(i),)
98                 rpcs.append(AuthServiceProxy(url))
99             except:
100                 sys.stderr.write("Error connecting to "+url+"\n")
101                 sys.exit(1)
102
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
106         # at 1 Jan 2014
107         block_time = 1388534400
108         for i in range(2):
109             for peer in range(4):
110                 for j in range(25):
111                     set_node_times(rpcs, block_time)
112                     rpcs[peer].setgenerate(True, 1)
113                     block_time += 10*60
114                 # Must sync before next peer starts generating blocks
115                 sync_blocks(rpcs)
116
117         # Shut them down, and clean up cache directories:
118         stop_nodes(rpcs)
119         wait_bitcoinds()
120         for i in range(4):
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"))
125
126     for i in range(4):
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
131
132 def initialize_chain_clean(test_dir, num_nodes):
133     """
134     Create an empty blockchain and num_nodes wallets.
135     Useful if a test case wants complete control over initialization.
136     """
137     for i in range(num_nodes):
138         datadir=initialize_datadir(test_dir, i)
139
140
141 def _rpchost_to_args(rpchost):
142     '''Convert optional IP:port spec to rpcconnect/rpcport args'''
143     if rpchost is None:
144         return []
145
146     match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
147     if not match:
148         raise ValueError('Invalid RPC host spec ' + rpchost)
149
150     rpcconnect = match.group(1)
151     rpcport = match.group(2)
152
153     if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
154         rpcconnect = rpcconnect[1:-1]
155
156     rv = ['-rpcconnect=' + rpcconnect]
157     if rpcport:
158         rv += ['-rpcport=' + rpcport]
159     return rv
160
161 def start_node(i, dirname, extra_args=None, rpchost=None):
162     """
163     Start a bitcoind and return RPC connection to it
164     """
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)
173     devnull.close()
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
177     return proxy
178
179 def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None):
180     """
181     Start multiple bitcoinds, return RPC connections to them
182     """
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) ]
185
186 def log_filename(dirname, n_node, logname):
187     return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
188
189 def stop_node(node, i):
190     node.stop()
191     bitcoind_processes[i].wait()
192     del bitcoind_processes[i]
193
194 def stop_nodes(nodes):
195     for node in nodes:
196         node.stop()
197     del nodes[:] # Emptying array closes connections as a side effect
198
199 def set_node_times(nodes, t):
200     for node in nodes:
201         node.setmocktime(t)
202
203 def wait_bitcoinds():
204     # Wait for all bitcoinds to cleanly exit
205     for bitcoind in bitcoind_processes.values():
206         bitcoind.wait()
207     bitcoind_processes.clear()
208
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()):
215         time.sleep(0.1)
216
217 def connect_nodes_bi(nodes, a, b):
218     connect_nodes(nodes[a], b)
219     connect_nodes(nodes[b], a)
220
221 def find_output(node, txid, amount):
222     """
223     Return index to output of txid with value amount
224     Raises exception if there is none.
225     """
226     txdata = node.getrawtransaction(txid, 1)
227     for i in range(len(txdata["vout"])):
228         if txdata["vout"][i]["value"] == amount:
229             return i
230     raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
231
232
233 def gather_inputs(from_node, amount_needed, confirmations_required=1):
234     """
235     Return a random set of unspent txouts that are enough to pay amount_needed
236     """
237     assert(confirmations_required >=0)
238     utxo = from_node.listunspent(confirmations_required)
239     random.shuffle(utxo)
240     inputs = []
241     total_in = Decimal("0.00000000")
242     while total_in < amount_needed and len(utxo) > 0:
243         t = utxo.pop()
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)
249
250 def make_change(from_node, amount_in, amount_out, fee):
251     """
252     Create change output(s), return them
253     """
254     outputs = {}
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]
263     if change > 0:
264         outputs[from_node.getnewaddress()] = change
265     return outputs
266
267 def send_zeropri_transaction(from_node, to_node, amount, fee):
268     """
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
273     """
274
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)
280
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)
284
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) }
290
291     rawtx = from_node.createrawtransaction(inputs, outputs)
292     signresult = from_node.signrawtransaction(rawtx)
293     txid = from_node.sendrawtransaction(signresult["hex"], True)
294
295     return (txid, signresult["hex"])
296
297 def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
298     """
299     Create a random zero-priority transaction.
300     Returns (txid, hex-encoded-transaction-data, fee)
301     """
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)
307
308 def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
309     """
310     Create a random transaction.
311     Returns (txid, hex-encoded-transaction-data, fee)
312     """
313     from_node = random.choice(nodes)
314     to_node = random.choice(nodes)
315     fee = min_fee + fee_increment*random.randint(0,fee_variants)
316
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)
320
321     rawtx = from_node.createrawtransaction(inputs, outputs)
322     signresult = from_node.signrawtransaction(rawtx)
323     txid = from_node.sendrawtransaction(signresult["hex"], True)
324
325     return (txid, signresult["hex"], fee)
326
327 def assert_equal(thing1, thing2):
328     if thing1 != thing2:
329         raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
This page took 0.041387 seconds and 4 git commands to generate.