Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
transaction.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-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
6#include <node/transaction.h>
7
9#include <index/txindex.h>
10#include <net.h>
11#include <net_processing.h>
12#include <node/blockstorage.h>
13#include <node/context.h>
14#include <node/types.h>
15#include <policy/feerate.h>
16#include <tinyformat.h>
17#include <txmempool.h>
18#include <validation.h>
19#include <validationinterface.h>
20
21#include <stdexcept>
22
23namespace node {
25{
26 err_string_out = state.ToString();
27 if (state.IsInvalid()) {
30 }
32 } else {
34 }
35}
36
38{
39 // BroadcastTransaction can be called by RPC or by the wallet.
40 // chainman, mempool and peerman are initialized before the RPC server and wallet are started
41 // and reset after the RPC sever and wallet are stopped.
42 assert(node.chainman);
43 assert(node.mempool);
44 assert(node.peerman);
45
46 Txid txid = tx->GetHash();
47 Wtxid wtxid = tx->GetWitnessHash();
48 bool callback_set = false;
49
50 {
52
53 // If the transaction is already confirmed in the chain, don't do anything
54 // and return early.
55 CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();
56 for (size_t o = 0; o < tx->vout.size(); o++) {
57 const Coin& existingCoin = view.AccessCoin(COutPoint(txid, o));
58 // IsSpent doesn't mean the coin is spent, it means the output doesn't exist.
59 // So if the output does exist, then this transaction exists in the chain.
61 }
62
63 if (auto mempool_tx = node.mempool->get(txid); mempool_tx) {
64 // There's already a transaction in the mempool with this txid. Don't
65 // try to submit this transaction to the mempool (since it'll be
66 // rejected as a TX_CONFLICT), but do attempt to reannounce the mempool
67 // transaction if broadcast_method is not TxBroadcast::MEMPOOL_NO_BROADCAST.
68 //
69 // The mempool transaction may have the same or different witness (and
70 // wtxid) as this transaction. Use the mempool's wtxid for reannouncement.
71 wtxid = mempool_tx->GetWitnessHash();
72 } else {
73 // Transaction is not already in the mempool.
74 const bool check_max_fee{max_tx_fee > 0};
77 // First, call ATMP with test_accept and check the fee. If ATMP
78 // fails here, return error immediately.
79 const MempoolAcceptResult result = node.chainman->ProcessTransaction(tx, /*test_accept=*/ true);
81 return HandleATMPError(result.m_state, err_string);
82 } else if (check_max_fee && result.m_base_fees.value() > max_tx_fee) {
84 } else if (check_max_feerate && result.m_base_fees.value() > max_tx_fee_rate.GetFee(result.m_vsize.value())) {
86 }
87 }
88
89 switch (broadcast_method) {
92 // Try to submit the transaction to the mempool.
93 {
94 const MempoolAcceptResult result =
95 node.chainman->ProcessTransaction(tx, /*test_accept=*/false);
97 return HandleATMPError(result.m_state, err_string);
98 }
99 }
100 // Transaction was accepted to the mempool.
101
103 // the mempool tracks locally submitted transactions to make a
104 // best-effort of initial broadcast
105 node.mempool->AddUnbroadcastTx(txid);
106 }
107 break;
109 break;
110 }
111
112 if (wait_callback && node.validation_signals) {
113 // For transactions broadcast from outside the wallet, make sure
114 // that the wallet has been notified of the transaction before
115 // continuing.
116 //
117 // This prevents a race where a user might call sendrawtransaction
118 // with a transaction to/from their wallet, immediately call some
119 // wallet RPC, and get a stale result because callbacks have not
120 // yet been processed.
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 node.validation_signals->SyncWithValidationInterfaceQueue();
130 }
131
132 switch (broadcast_method) {
134 break;
136 node.peerman->InitiateTxBroadcastToAll(wtxid);
137 break;
139 return node.peerman->InitiateTxBroadcastPrivate(tx);
140 }
141
143}
144
145CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const Txid& hash, const BlockManager& blockman, uint256& hashBlock)
146{
147 if (mempool && !block_index) {
148 CTransactionRef ptx = mempool->get(hash);
149 if (ptx) return ptx;
150 }
151 if (g_txindex) {
152 if (auto result{g_txindex->FindTx(hash)}) {
153 if (!block_index || block_index->GetBlockHash() == result->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 = result->block_hash;
158 return result->tx;
159 }
160 }
161 }
162 if (block_index) {
163 CBlock block;
164 if (!blockman.ReadBlock(block, *block_index)) {
165 throw std::runtime_error{strprintf("I/O error reading block data for block %s", block_index->GetBlockHash().ToString())};
166 }
167 for (const auto& tx : block.vtx) {
168 if (tx->GetHash() == hash) {
169 hashBlock = block_index->GetBlockHash();
170 return tx;
171 }
172 }
173 }
174 return nullptr;
175}
176} // namespace node
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
Definition block.h:74
std::vector< CTransactionRef > vtx
Definition block.h:77
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition chain.h:94
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:437
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition feerate.h:32
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition transaction.h:30
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:188
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
A UTXO entry.
Definition coins.h:46
Result GetResult() const
Definition validation.h:115
std::string ToString() const
Definition validation.h:118
bool IsInvalid() const
Definition validation.h:113
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
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
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.
TransactionError BroadcastTransaction(NodeContext &node, const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, const CFeeRate &max_tx_fee_rate, TxBroadcast broadcast_method, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
TxBroadcast
How to broadcast a local transaction.
Definition types.h:38
@ 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.
@ NO_MEMPOOL_PRIVATE_BROADCAST
Omit the mempool and directly send the transaction via a few dedicated connections to peers on privac...
TransactionError
Definition types.h:21
static TransactionError HandleATMPError(const TxValidationState &state, std::string &err_string_out)
Home for public enum and struct type definitions.
std::shared_ptr< const CTransaction > CTransactionRef
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition validation.h:134
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition validation.h:151
const ResultType m_result_type
Result type.
Definition validation.h:143
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition validation.h:153
const TxValidationState m_state
Contains information about why the transaction failed.
Definition validation.h:146
NodeContext struct containing references to chain state and connection state.
Definition context.h:57
#define LOCK(cs)
Definition sync.h:268
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition txindex.cpp:44
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())