-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtransaction.cpp
More file actions
304 lines (267 loc) · 11.8 KB
/
transaction.cpp
File metadata and controls
304 lines (267 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Copyright (c) 2014-2024 The Reddcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/validation.h>
#include <index/txindex.h>
#include <net.h>
#include <net_processing.h>
#include <node/blockstorage.h>
#include <node/context.h>
#include <txmempool.h>
#include <validation.h>
#include <validationinterface.h>
#include <node/transaction.h>
#include <coins.h>
#include <chainparams.h>
#include <index/disktxpos.h>
#include <logging.h>
#include <future>
static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)
{
err_string_out = state.ToString();
if (state.IsInvalid()) {
if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
return TransactionError::MISSING_INPUTS;
}
return TransactionError::MEMPOOL_REJECTED;
} else {
return TransactionError::MEMPOOL_ERROR;
}
}
TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)
{
// BroadcastTransaction can be called by either sendrawtransaction RPC or the wallet.
// chainman, mempool and peerman are initialized before the RPC server and wallet are started
// and reset after the RPC sever and wallet are stopped.
assert(node.chainman);
assert(node.mempool);
assert(node.peerman);
std::promise<void> promise;
uint256 txid = tx->GetHash();
uint256 wtxid = tx->GetWitnessHash();
bool callback_set = false;
{
LOCK(cs_main);
// If the transaction is already confirmed in the chain, don't do anything
// and return early.
CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();
for (size_t o = 0; o < tx->vout.size(); o++) {
const Coin& existingCoin = view.AccessCoin(COutPoint(txid, o));
// IsSpent doesn't mean the coin is spent, it means the output doesn't exist.
// So if the output does exist, then this transaction exists in the chain.
if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_CHAIN;
}
if (auto mempool_tx = node.mempool->get(txid); mempool_tx) {
// There's already a transaction in the mempool with this txid. Don't
// try to submit this transaction to the mempool (since it'll be
// rejected as a TX_CONFLICT), but do attempt to reannounce the mempool
// transaction if relay=true.
//
// The mempool transaction may have the same or different witness (and
// wtxid) as this transaction. Use the mempool's wtxid for reannouncement.
wtxid = mempool_tx->GetWitnessHash();
} else {
// Transaction is not already in the mempool.
if (max_tx_fee > 0) {
// First, call ATMP with test_accept and check the fee. If ATMP
// fails here, return error immediately.
const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
true /* test_accept */);
if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
return HandleATMPError(result.m_state, err_string);
} else if (result.m_base_fees.value() > max_tx_fee) {
return TransactionError::MAX_FEE_EXCEEDED;
}
}
// Try to submit the transaction to the mempool.
const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
false /* test_accept */);
if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
return HandleATMPError(result.m_state, err_string);
}
// Transaction was accepted to the mempool.
if (relay) {
// the mempool tracks locally submitted transactions to make a
// best-effort of initial broadcast
node.mempool->AddUnbroadcastTx(txid);
}
if (wait_callback) {
// For transactions broadcast from outside the wallet, make sure
// that the wallet has been notified of the transaction before
// continuing.
//
// This prevents a race where a user might call sendrawtransaction
// with a transaction to/from their wallet, immediately call some
// wallet RPC, and get a stale result because callbacks have not
// yet been processed.
CallFunctionInValidationInterfaceQueue([&promise] {
promise.set_value();
});
callback_set = true;
}
}
} // cs_main
if (callback_set) {
// Wait until Validation Interface clients have been notified of the
// transaction entering the mempool.
promise.get_future().wait();
}
if (relay) {
node.peerman->RelayTransaction(txid, wtxid);
}
return TransactionError::OK;
}
CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock)
{
LOCK(cs_main);
if (mempool && !block_index) {
CTransactionRef ptx = mempool->get(hash);
if (ptx) return ptx;
}
if (g_txindex) {
CTransactionRef tx;
uint256 block_hash;
if (g_txindex->FindTx(hash, block_hash, tx)) {
if (!block_index || block_index->GetBlockHash() == block_hash) {
// Don't return the transaction if the provided block hash doesn't match.
// The case where a transaction appears in multiple blocks (e.g. reorgs or
// BIP30) is handled by the block lookup below.
hashBlock = block_hash;
return tx;
}
}
}
if (block_index) {
CBlock block;
if (ReadBlockFromDisk(block, block_index, consensusParams)) {
for (const auto& tx : block.vtx) {
if (tx->GetHash() == hash) {
hashBlock = block_index->GetBlockHash();
return tx;
}
}
}
}
return nullptr;
}
CTransactionRef GetTransaction(const uint256& txhash, uint256& hashBlock)
{
if (g_txindex) {
CTransactionRef tx;
uint256 block_hash;
if (g_txindex->FindTx(txhash, block_hash, tx)) {
hashBlock = block_hash;
return tx;
}
}
return nullptr;
}
CTransactionRef GetTransaction(const uint256& txhash)
{
if (g_txindex) {
CDiskTxPos postx;
if (g_txindex->FindTxPosition(txhash, postx)) {
// Read block header
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
CBlockHeader header;
CTransactionRef tx;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> tx;
return tx;
} catch (std::exception& e) {
return nullptr;
}
}
}
return nullptr;
}
bool GetTransaction(CChainState* active_chainstate, const COutPoint& prevout,
CTransactionRef& txOut, CBlockHeader& blockHeader, unsigned int& nTxOffset)
{
// During reindex, skip txindex as it may contain stale data
// Always use UTXO fallback during reindex to ensure correct validation
const bool fSkipTxIndex = fReindex.load();
// Try txindex first if available and not reindexing (fast path)
if (g_txindex && !fSkipTxIndex) {
CDiskTxPos postx;
if (g_txindex->FindTxPosition(prevout.hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (!file.IsNull()) {
try {
file >> blockHeader;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
nTxOffset = postx.nTxOffset;
return true;
} catch (const std::exception& e) {
// Fall through to UTXO lookup
}
}
}
}
// Fallback: use UTXO set + block reading (works during reindex without txindex)
if (!active_chainstate) {
LogPrint(BCLog::POS, "%s: no active chainstate available\n", __func__);
return false;
}
LOCK(cs_main);
// Get the coin from UTXO set
const Coin& coin = active_chainstate->CoinsTip().AccessCoin(prevout);
if (coin.IsSpent()) {
LogPrint(BCLog::POS, "%s: prevout %s already spent\n", __func__, prevout.ToString());
return false;
}
// Get the block index at the height where the coin was created
CBlockIndex* pindex = active_chainstate->m_chain[coin.nHeight];
if (!pindex) {
LogPrint(BCLog::POS, "%s: block at height %d not found in chain\n", __func__, coin.nHeight);
return false;
}
// Read block header and transaction directly from disk (same as txindex does)
// This ensures we get the exact same serialized data that txindex would provide
CAutoFile file(OpenBlockFile(pindex->GetBlockPos(), true), SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
return error("%s: failed to open block file for %s", __func__, prevout.hash.ToString());
}
try {
file >> blockHeader; // Read header directly from disk
} catch (const std::exception& e) {
return error("%s: failed to read block header: %s", __func__, e.what());
}
// Now we need to read the full block to find our transaction and calculate offset
CBlock block;
if (!ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
LogPrint(BCLog::POS, "%s: failed to read block %s from disk\n", __func__, pindex->GetBlockHash().ToString());
return false;
}
// Find the transaction in the block and calculate its offset
// The offset must match exactly what txindex stores: offset from after block header to the transaction
// Offset = CompactSize(vtx.size()) + sum of sizes of all transactions before target
// Start with CompactSize of transaction count
CDataStream ssSize(SER_DISK, CLIENT_VERSION);
WriteCompactSize(ssSize, block.vtx.size());
unsigned int currentOffset = ssSize.size();
for (size_t i = 0; i < block.vtx.size(); i++) {
if (block.vtx[i]->GetHash() == prevout.hash) {
nTxOffset = currentOffset;
// Read transaction from file using calculated offset (same as txindex does)
// Seek to the transaction offset from current position (after header)
if (fseek(file.Get(), nTxOffset, SEEK_CUR) != 0) {
return error("%s: failed to seek to offset %u for tx %s", __func__, nTxOffset, prevout.hash.ToString());
}
try {
file >> txOut; // Read transaction directly from file
} catch (const std::exception& e) {
return error("%s: failed to read transaction from file: %s", __func__, e.what());
}
return true;
}
// Add this transaction's size to offset for next iteration
currentOffset += ::GetSerializeSize(*block.vtx[i], CLIENT_VERSION);
}
return error("%s: transaction %s not found in block %s", __func__, prevout.hash.ToString(), pindex->GetBlockHash().ToString());
}