Bitcoin Core 30.99.0
P2P Digital Currency
transaction.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2021 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
7#include <index/txindex.h>
8#include <net.h>
9#include <net_processing.h>
10#include <node/blockstorage.h>
11#include <node/context.h>
12#include <node/types.h>
13#include <txmempool.h>
14#include <validation.h>
15#include <validationinterface.h>
16#include <node/transaction.h>
17
18#include <future>
19
20namespace node {
21static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)
22{
23 err_string_out = state.ToString();
24 if (state.IsInvalid()) {
27 }
29 } else {
31 }
32}
33
35 const CTransactionRef tx,
36 std::string& err_string,
37 const CAmount& max_tx_fee,
38 TxBroadcast broadcast_method,
39 bool wait_callback)
40{
41 // BroadcastTransaction can be called by RPC or by the wallet.
42 // chainman, mempool and peerman are initialized before the RPC server and wallet are started
43 // and reset after the RPC sever and wallet are stopped.
44 assert(node.chainman);
45 assert(node.mempool);
46 assert(node.peerman);
47
48 std::promise<void> promise;
49 Txid txid = tx->GetHash();
50 Wtxid wtxid = tx->GetWitnessHash();
51 bool callback_set = false;
52
53 {
55
56 // If the transaction is already confirmed in the chain, don't do anything
57 // and return early.
58 CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();
59 for (size_t o = 0; o < tx->vout.size(); o++) {
60 const Coin& existingCoin = view.AccessCoin(COutPoint(txid, o));
61 // IsSpent doesn't mean the coin is spent, it means the output doesn't exist.
62 // So if the output does exist, then this transaction exists in the chain.
63 if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_UTXO_SET;
64 }
65
66 if (auto mempool_tx = node.mempool->get(txid); mempool_tx) {
67 // There's already a transaction in the mempool with this txid. Don't
68 // try to submit this transaction to the mempool (since it'll be
69 // rejected as a TX_CONFLICT), but do attempt to reannounce the mempool
70 // transaction if broadcast_method is not TxBroadcast::MEMPOOL_NO_BROADCAST.
71 //
72 // The mempool transaction may have the same or different witness (and
73 // wtxid) as this transaction. Use the mempool's wtxid for reannouncement.
74 wtxid = mempool_tx->GetWitnessHash();
75 } else {
76 // Transaction is not already in the mempool.
77 if (max_tx_fee > 0) {
78 // First, call ATMP with test_accept and check the fee. If ATMP
79 // fails here, return error immediately.
80 const MempoolAcceptResult result = node.chainman->ProcessTransaction(tx, /*test_accept=*/ true);
82 return HandleATMPError(result.m_state, err_string);
83 } else if (result.m_base_fees.value() > max_tx_fee) {
85 }
86 }
87
88 switch (broadcast_method) {
91 // Try to submit the transaction to the mempool.
92 {
93 const MempoolAcceptResult result =
94 node.chainman->ProcessTransaction(tx, /*test_accept=*/false);
96 return HandleATMPError(result.m_state, err_string);
97 }
98 }
99 // Transaction was accepted to the mempool.
100
101 if (broadcast_method == TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL) {
102 // the mempool tracks locally submitted transactions to make a
103 // best-effort of initial broadcast
104 node.mempool->AddUnbroadcastTx(txid);
105 }
106 break;
107 }
108
109 if (wait_callback && node.validation_signals) {
110 // For transactions broadcast from outside the wallet, make sure
111 // that the wallet has been notified of the transaction before
112 // continuing.
113 //
114 // This prevents a race where a user might call sendrawtransaction
115 // with a transaction to/from their wallet, immediately call some
116 // wallet RPC, and get a stale result because callbacks have not
117 // yet been processed.
118 node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
119 promise.set_value();
120 });
121 callback_set = true;
122 }
123 }
124 } // cs_main
125
126 if (callback_set) {
127 // Wait until Validation Interface clients have been notified of the
128 // transaction entering the mempool.
129 promise.get_future().wait();
130 }
131
132 switch (broadcast_method) {
134 break;
136 node.peerman->RelayTransaction(txid, wtxid);
137 break;
138 }
139
141}
142
143CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, const BlockManager& blockman, uint256& hashBlock)
144{
145 if (mempool && !block_index) {
146 CTransactionRef ptx = mempool->get(hash);
147 if (ptx) return ptx;
148 }
149 if (g_txindex) {
151 uint256 block_hash;
152 if (g_txindex->FindTx(hash, block_hash, tx)) {
153 if (!block_index || block_index->GetBlockHash() == block_hash) {
154 // Don't return the transaction if the provided block hash doesn't match.
155 // The case where a transaction appears in multiple blocks (e.g. reorgs or
156 // BIP30) is handled by the block lookup below.
157 hashBlock = block_hash;
158 return tx;
159 }
160 }
161 }
162 if (block_index) {
163 CBlock block;
164 if (blockman.ReadBlock(block, *block_index)) {
165 for (const auto& tx : block.vtx) {
166 if (tx->GetHash() == hash) {
167 hashBlock = block_index->GetBlockHash();
168 return tx;
169 }
170 }
171 }
172 }
173 return nullptr;
174}
175} // namespace node
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:103
uint256 GetBlockHash() const
Definition: chain.h:207
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:361
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:157
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:281
CTransactionRef get(const Txid &hash) const
Definition: txmempool.cpp:879
A UTXO entry.
Definition: coins.h:33
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:81
Result GetResult() const
Definition: validation.h:108
std::string ToString() const
Definition: validation.h:111
bool IsInvalid() const
Definition: validation.h:106
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:181
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
256-bit opaque blob.
Definition: uint256.h:196
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
Definition: messages.h:21
TxBroadcast
How to broadcast a local transaction.
Definition: types.h:106
@ MEMPOOL_AND_BROADCAST_TO_ALL
Add the transaction to the mempool and broadcast to all peers for which tx relay is enabled.
@ MEMPOOL_NO_BROADCAST
Add the transaction to the mempool, but don't broadcast to anybody.
TransactionError
Definition: types.h:25
TransactionError BroadcastTransaction(NodeContext &node, const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, TxBroadcast broadcast_method, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
Definition: transaction.cpp:34
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const Txid &hash, const BlockManager &blockman, uint256 &hashBlock)
Return transaction with a given hash.
static TransactionError HandleATMPError(const TxValidationState &state, std::string &err_string_out)
Definition: transaction.cpp:21
is a home for public enum and struct type definitions that are used internally by node code,...
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:127
const ResultType m_result_type
Result type.
Definition: validation.h:136
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:146
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:139
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
#define LOCK(cs)
Definition: sync.h:259
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:35
assert(!tx.IsCoinBase())