Line data Source code
1 : // Copyright (c) 2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2022 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 :
6 : #include <chain.h>
7 : #include <chainparams.h>
8 : #include <coins.h>
9 : #include <index/txindex.h>
10 : #include <merkleblock.h>
11 : #include <node/blockstorage.h>
12 : #include <primitives/transaction.h>
13 : #include <rpc/server.h>
14 : #include <rpc/server_util.h>
15 : #include <rpc/util.h>
16 : #include <univalue.h>
17 : #include <util/strencodings.h>
18 : #include <validation.h>
19 :
20 : using node::GetTransaction;
21 : using node::ReadBlockFromDisk;
22 :
23 92 : static RPCHelpMan gettxoutproof()
24 : {
25 184 : return RPCHelpMan{"gettxoutproof",
26 92 : "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
27 : "\nNOTE: By default this function only works sometimes. This is when there is an\n"
28 : "unspent output in the utxo for this transaction. To make it always work,\n"
29 : "you need to maintain a transaction index, using the -txindex command line option or\n"
30 : "specify the block in which the transaction is included manually (by blockhash).\n",
31 276 : {
32 184 : {"txids", RPCArg::Type::ARR, RPCArg::Optional::NO, "The txids to filter",
33 184 : {
34 92 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A transaction hash"},
35 : },
36 : },
37 92 : {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "If specified, looks for txid in the block with this hash"},
38 : },
39 92 : RPCResult{
40 92 : RPCResult::Type::STR, "data", "A string that is a serialized, hex-encoded data for the proof."
41 : },
42 92 : RPCExamples{
43 92 : HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'")
44 92 : + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"")
45 92 : + HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"")
46 : },
47 92 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
48 : {
49 0 : std::set<uint256> setTxids;
50 0 : UniValue txids = request.params[0].get_array();
51 0 : if (txids.empty()) {
52 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txids' cannot be empty");
53 : }
54 0 : for (unsigned int idx = 0; idx < txids.size(); idx++) {
55 0 : auto ret = setTxids.insert(ParseHashV(txids[idx], "txid"));
56 0 : if (!ret.second) {
57 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ") + txids[idx].get_str());
58 : }
59 0 : }
60 :
61 0 : const CBlockIndex* pblockindex = nullptr;
62 0 : uint256 hashBlock;
63 0 : ChainstateManager& chainman = EnsureAnyChainman(request.context);
64 0 : if (!request.params[1].isNull()) {
65 0 : LOCK(cs_main);
66 0 : hashBlock = ParseHashV(request.params[1], "blockhash");
67 0 : pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
68 0 : if (!pblockindex) {
69 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
70 : }
71 0 : } else {
72 0 : LOCK(cs_main);
73 0 : CChainState& active_chainstate = chainman.ActiveChainstate();
74 :
75 : // Loop through txids and try to find which block they're in. Exit loop once a block is found.
76 0 : for (const auto& tx : setTxids) {
77 0 : const Coin& coin = AccessByTxid(active_chainstate.CoinsTip(), tx);
78 0 : if (!coin.IsSpent()) {
79 0 : pblockindex = active_chainstate.m_chain[coin.nHeight];
80 0 : break;
81 : }
82 : }
83 0 : }
84 :
85 :
86 : // Allow txindex to catch up if we need to query it and before we acquire cs_main.
87 0 : if (g_txindex && !pblockindex) {
88 0 : g_txindex->BlockUntilSyncedToCurrentChain();
89 0 : }
90 :
91 0 : if (pblockindex == nullptr) {
92 0 : const CTransactionRef tx = GetTransaction(/*block_index=*/nullptr, /*mempool=*/nullptr, *setTxids.begin(), Params().GetConsensus(), hashBlock);
93 0 : if (!tx || hashBlock.IsNull()) {
94 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
95 : }
96 0 : pblockindex = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(hashBlock));
97 0 : if (!pblockindex) {
98 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
99 : }
100 0 : }
101 :
102 0 : CBlock block;
103 0 : if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
104 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
105 : }
106 :
107 0 : unsigned int ntxFound = 0;
108 0 : for (const auto& tx : block.vtx) {
109 0 : if (setTxids.count(tx->GetHash())) {
110 0 : ntxFound++;
111 0 : }
112 : }
113 0 : if (ntxFound != setTxids.size()) {
114 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
115 : }
116 :
117 0 : CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
118 0 : CMerkleBlock mb(block, setTxids);
119 0 : ssMB << mb;
120 0 : std::string strHex = HexStr(ssMB);
121 0 : return strHex;
122 0 : },
123 : };
124 0 : }
125 :
126 92 : static RPCHelpMan verifytxoutproof()
127 : {
128 184 : return RPCHelpMan{"verifytxoutproof",
129 92 : "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
130 : "and throwing an RPC error if the block is not in our best chain\n",
131 184 : {
132 92 : {"proof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded proof generated by gettxoutproof"},
133 : },
134 92 : RPCResult{
135 92 : RPCResult::Type::ARR, "", "",
136 184 : {
137 92 : {RPCResult::Type::STR_HEX, "txid", "The txid(s) which the proof commits to, or empty array if the proof cannot be validated."},
138 : }
139 : },
140 92 : RPCExamples{
141 92 : HelpExampleCli("verifytxoutproof", "\"proof\"")
142 92 : + HelpExampleRpc("gettxoutproof", "\"proof\"")
143 : },
144 92 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
145 : {
146 0 : CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
147 0 : CMerkleBlock merkleBlock;
148 0 : ssMB >> merkleBlock;
149 :
150 0 : UniValue res(UniValue::VARR);
151 :
152 0 : std::vector<uint256> vMatch;
153 0 : std::vector<unsigned int> vIndex;
154 0 : if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
155 0 : return res;
156 :
157 0 : ChainstateManager& chainman = EnsureAnyChainman(request.context);
158 0 : LOCK(cs_main);
159 :
160 0 : const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash());
161 0 : if (!pindex || !chainman.ActiveChain().Contains(pindex) || pindex->nTx == 0) {
162 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
163 : }
164 :
165 : // Check if proof is valid, only add results if so
166 0 : if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) {
167 0 : for (const uint256& hash : vMatch) {
168 0 : res.push_back(hash.GetHex());
169 : }
170 0 : }
171 :
172 0 : return res;
173 0 : },
174 : };
175 0 : }
176 :
177 178 : void RegisterTxoutProofRPCCommands(CRPCTable& t)
178 : {
179 270 : static const CRPCCommand commands[]{
180 46 : {"blockchain", &gettxoutproof},
181 46 : {"blockchain", &verifytxoutproof},
182 : };
183 534 : for (const auto& c : commands) {
184 356 : t.appendCommand(c.name, &c);
185 : }
186 178 : }
|