wallet_listtransactions.py raw
1 #!/usr/bin/env python3
2 # Copyright (c) 2014-present 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 """Test the listtransactions API."""
6
7 from decimal import Decimal
8 import time
9 import os
10 import shutil
11
12 from test_framework.blocktools import MAX_FUTURE_BLOCK_TIME
13 from test_framework.descriptors import descsum_create
14 from test_framework.test_framework import BitcoinTestFramework
15 from test_framework.util import (
16 assert_not_equal,
17 assert_array_result,
18 assert_equal,
19 assert_raises_rpc_error,
20 find_vout_for_address,
21 )
22 from test_framework.wallet_util import get_generate_key
23
24
25 class ListTransactionsTest(BitcoinTestFramework):
26 def set_test_params(self):
27 self.num_nodes = 3
28 # whitelist peers to speed up tx relay / mempool sync
29 self.noban_tx_relay = True
30
31 def skip_test_if_missing_module(self):
32 self.skip_if_no_wallet()
33
34 def run_test(self):
35 self.log.info("Test simple send from node0 to node1")
36 txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
37 self.sync_all()
38 assert_array_result(self.nodes[0].listtransactions(),
39 {"txid": txid},
40 {"category": "send", "amount": Decimal("-0.1"), "confirmations": 0, "trusted": True})
41 assert_array_result(self.nodes[1].listtransactions(),
42 {"txid": txid},
43 {"category": "receive", "amount": Decimal("0.1"), "confirmations": 0, "trusted": False})
44 self.log.info("Test confirmations change after mining a block")
45 blockhash = self.generate(self.nodes[0], 1)[0]
46 blockheight = self.nodes[0].getblockheader(blockhash)['height']
47 assert_array_result(self.nodes[0].listtransactions(),
48 {"txid": txid},
49 {"category": "send", "amount": Decimal("-0.1"), "confirmations": 1, "blockhash": blockhash, "blockheight": blockheight})
50 assert_array_result(self.nodes[1].listtransactions(),
51 {"txid": txid},
52 {"category": "receive", "amount": Decimal("0.1"), "confirmations": 1, "blockhash": blockhash, "blockheight": blockheight})
53
54 self.log.info("Test send-to-self on node0")
55 txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 0.2)
56 assert_array_result(self.nodes[0].listtransactions(),
57 {"txid": txid, "category": "send"},
58 {"amount": Decimal("-0.2")})
59 assert_array_result(self.nodes[0].listtransactions(),
60 {"txid": txid, "category": "receive"},
61 {"amount": Decimal("0.2")})
62
63 self.log.info("Test sendmany from node1: twice to self, twice to node0")
64 send_to = {self.nodes[0].getnewaddress(): 0.11,
65 self.nodes[1].getnewaddress(): 0.22,
66 self.nodes[0].getnewaddress(): 0.33,
67 self.nodes[1].getnewaddress(): 0.44}
68 txid = self.nodes[1].sendmany("", send_to)
69 self.sync_all()
70 assert_array_result(self.nodes[1].listtransactions(),
71 {"category": "send", "amount": Decimal("-0.11")},
72 {"txid": txid})
73 assert_array_result(self.nodes[0].listtransactions(),
74 {"category": "receive", "amount": Decimal("0.11")},
75 {"txid": txid})
76 assert_array_result(self.nodes[1].listtransactions(),
77 {"category": "send", "amount": Decimal("-0.22")},
78 {"txid": txid})
79 assert_array_result(self.nodes[1].listtransactions(),
80 {"category": "receive", "amount": Decimal("0.22")},
81 {"txid": txid})
82 assert_array_result(self.nodes[1].listtransactions(),
83 {"category": "send", "amount": Decimal("-0.33")},
84 {"txid": txid})
85 assert_array_result(self.nodes[0].listtransactions(),
86 {"category": "receive", "amount": Decimal("0.33")},
87 {"txid": txid})
88 assert_array_result(self.nodes[1].listtransactions(),
89 {"category": "send", "amount": Decimal("-0.44")},
90 {"txid": txid})
91 assert_array_result(self.nodes[1].listtransactions(),
92 {"category": "receive", "amount": Decimal("0.44")},
93 {"txid": txid})
94
95 self.run_externally_generated_address_test()
96 self.run_coinjoin_test()
97 self.run_invalid_parameters_test()
98 self.test_op_return()
99 self.test_from_me_status_change()
100
101 def run_externally_generated_address_test(self):
102 """Test behavior when receiving address is not in the address book."""
103
104 self.log.info("Setup the same wallet on two nodes")
105 # refill keypool otherwise the second node wouldn't recognize addresses generated on the first nodes
106 self.nodes[0].keypoolrefill(1000)
107 self.stop_nodes()
108 wallet0 = os.path.join(self.nodes[0].chain_path, self.default_wallet_name, "wallet.dat")
109 wallet2 = os.path.join(self.nodes[2].chain_path, self.default_wallet_name, "wallet.dat")
110 shutil.copyfile(wallet0, wallet2)
111 self.start_nodes()
112 # reconnect nodes
113 self.connect_nodes(0, 1)
114 self.connect_nodes(1, 2)
115 self.connect_nodes(2, 0)
116
117 addr1 = self.nodes[0].getnewaddress("pizza1", 'legacy')
118 addr2 = self.nodes[0].getnewaddress("pizza2", 'p2sh-segwit')
119 addr3 = self.nodes[0].getnewaddress("pizza3", 'bech32')
120
121 self.log.info("Send to externally generated addresses")
122 # send to an address beyond the next to be generated to test the keypool gap
123 self.nodes[1].sendtoaddress(addr3, "0.001")
124 self.generate(self.nodes[1], 1)
125
126 # send to an address that is already marked as used due to the keypool gap mechanics
127 self.nodes[1].sendtoaddress(addr2, "0.001")
128 self.generate(self.nodes[1], 1)
129
130 # send to self transaction
131 self.nodes[0].sendtoaddress(addr1, "0.001")
132 self.generate(self.nodes[0], 1)
133
134 self.log.info("Verify listtransactions is the same regardless of where the address was generated")
135 transactions0 = self.nodes[0].listtransactions()
136 transactions2 = self.nodes[2].listtransactions()
137
138 # normalize results: remove fields that normally could differ and sort
139 def normalize_list(txs):
140 for tx in txs:
141 tx.pop('label', None)
142 tx.pop('time', None)
143 tx.pop('timereceived', None)
144 txs.sort(key=lambda x: x['txid'])
145
146 normalize_list(transactions0)
147 normalize_list(transactions2)
148 assert_equal(transactions0, transactions2)
149
150 self.log.info("Verify labels are persistent on the node that generated the addresses")
151 assert_equal(['pizza1'], self.nodes[0].getaddressinfo(addr1)['labels'])
152 assert_equal(['pizza2'], self.nodes[0].getaddressinfo(addr2)['labels'])
153 assert_equal(['pizza3'], self.nodes[0].getaddressinfo(addr3)['labels'])
154
155 def run_coinjoin_test(self):
156 self.log.info('Check "coin-join" transaction')
157 input_0 = next(i for i in self.nodes[0].listunspent(query_options={"minimumAmount": 0.2}, include_unsafe=False))
158 input_1 = next(i for i in self.nodes[1].listunspent(query_options={"minimumAmount": 0.2}, include_unsafe=False))
159 raw_hex = self.nodes[0].createrawtransaction(
160 inputs=[
161 {
162 "txid": input_0["txid"],
163 "vout": input_0["vout"],
164 },
165 {
166 "txid": input_1["txid"],
167 "vout": input_1["vout"],
168 },
169 ],
170 outputs={
171 self.nodes[0].getnewaddress(): 0.123,
172 self.nodes[1].getnewaddress(): 0.123,
173 },
174 )
175 raw_hex = self.nodes[0].signrawtransactionwithwallet(raw_hex)["hex"]
176 raw_hex = self.nodes[1].signrawtransactionwithwallet(raw_hex)["hex"]
177 txid_join = self.nodes[0].sendrawtransaction(hexstring=raw_hex, maxfeerate=0)
178 fee_join = self.nodes[0].getmempoolentry(txid_join)["fees"]["base"]
179 # Fee should be correct: assert_equal(fee_join, self.nodes[0].gettransaction(txid_join)['fee'])
180 # But it is not, see for example https://github.com/bitcoin/bitcoin/issues/14136:
181 assert_not_equal(fee_join, self.nodes[0].gettransaction(txid_join)["fee"])
182
183 def run_invalid_parameters_test(self):
184 self.log.info("Test listtransactions RPC parameter validity")
185 assert_raises_rpc_error(-8, 'Label argument must be a valid label name or "*".', self.nodes[0].listtransactions, label="")
186 self.nodes[0].listtransactions(label="*")
187 assert_raises_rpc_error(-8, "Negative count", self.nodes[0].listtransactions, count=-1)
188 assert_raises_rpc_error(-8, "Negative from", self.nodes[0].listtransactions, skip=-1)
189
190 def test_op_return(self):
191 """Test if OP_RETURN outputs will be displayed correctly."""
192 raw_tx = self.nodes[0].createrawtransaction([], [{'data': 'aa'}])
193 funded_tx = self.nodes[0].fundrawtransaction(raw_tx)
194 signed_tx = self.nodes[0].signrawtransactionwithwallet(funded_tx['hex'])
195 tx_id = self.nodes[0].sendrawtransaction(signed_tx['hex'])
196
197 op_ret_tx = [tx for tx in self.nodes[0].listtransactions() if tx['txid'] == tx_id][0]
198
199 assert 'address' not in op_ret_tx
200
201 def test_from_me_status_change(self):
202 self.log.info("Test gettransaction after changing a transaction's 'from me' status")
203 self.nodes[0].createwallet("fromme")
204 default_wallet = self.nodes[0].get_wallet_rpc(self.default_wallet_name)
205 wallet = self.nodes[0].get_wallet_rpc("fromme")
206
207 # The 'fee' field of gettransaction is only added when the transaction is 'from me'
208 # Run twice, once for a transaction in the mempool, again when it confirms
209 for confirm in [False, True]:
210 key = get_generate_key()
211 descriptor = descsum_create(f"wpkh({key.privkey})")
212 default_wallet.importdescriptors([{"desc": descriptor, "timestamp": "now"}])
213
214 send_res = default_wallet.send(outputs=[{key.p2wpkh_addr: 1}, {wallet.getnewaddress(): 1}])
215 assert_equal(send_res["complete"], True)
216 vout = find_vout_for_address(self.nodes[0], send_res["txid"], key.p2wpkh_addr)
217 utxos = [{"txid": send_res["txid"], "vout": vout}]
218 self.generate(self.nodes[0], 1, sync_fun=self.no_op)
219
220 # Send to the test wallet, ensuring that one input is for the descriptor we will import,
221 # and that there are other inputs belonging to only the sending wallet
222 send_res = default_wallet.send(outputs=[{wallet.getnewaddress(): 1.5}], inputs=utxos, add_inputs=True)
223 assert_equal(send_res["complete"], True)
224 txid = send_res["txid"]
225 self.nodes[0].syncwithvalidationinterfacequeue()
226 tx_info = wallet.gettransaction(txid)
227 assert "fee" not in tx_info
228 assert_equal(any(detail["category"] == "send" for detail in tx_info["details"]), False)
229
230 if confirm:
231 self.generate(self.nodes[0], 1, sync_fun=self.no_op)
232 # Mock time forward and generate blocks so that the import does not rescan the transaction
233 self.nodes[0].setmocktime(int(time.time()) + MAX_FUTURE_BLOCK_TIME + 1)
234 self.generate(self.nodes[0], 10, sync_fun=self.no_op)
235
236 import_res = wallet.importdescriptors([{"desc": descriptor, "timestamp": "now"}])
237 assert_equal(import_res[0]["success"], True)
238 # TODO: We should check that the fee matches, but since the transaction spends inputs
239 # not known to the wallet, it is incorrectly calculating the fee.
240 # assert_equal(wallet.gettransaction(txid)["fee"], fee)
241 tx_info = wallet.gettransaction(txid)
242 assert "fee" in tx_info
243 assert_equal(any(detail["category"] == "send" for detail in tx_info["details"]), True)
244
245 if __name__ == '__main__':
246 ListTransactionsTest(__file__).main()
247