Files
bitcoin/src/test
Ryan Ofsky 796f18e559 Merge bitcoin/bitcoin#29415: Broadcast own transactions only via short-lived Tor or I2P connections
8937221304 doc: add release notes for 29415 (Vasil Dimov)
582016fa5f test: add unit test for the private broadcast storage (Vasil Dimov)
e74d54e048 test: add functional test for private broadcast (Vasil Dimov)
818b780a05 rpc: use private broadcast from sendrawtransaction RPC if -privatebroadcast is ON (Vasil Dimov)
eab595f9cf net_processing: retry private broadcast (Vasil Dimov)
37b79f9c39 net_processing: stop private broadcast of a transaction after round-trip (Vasil Dimov)
2de53eee74 net_processing: handle ConnectionType::PRIVATE_BROADCAST connections (Vasil Dimov)
30a9853ad3 net_processing: move a debug check in VERACK processing earlier (Vasil Dimov)
d1092e5d48 net_processing: modernize PushNodeVersion() (Vasil Dimov)
9937a12a2f net_processing: move the debug log about receiving VERSION earlier (Vasil Dimov)
a098f37b9e net_processing: reorder the code that handles the VERSION message (Vasil Dimov)
679ce3a0b8 net_processing: store transactions for private broadcast in PeerManager (Vasil Dimov)
a3faa6f944 node: extend node::TxBroadcast with a 3rd option (Vasil Dimov)
95c051e210 net_processing: rename RelayTransaction() to better describe what it does (Vasil Dimov)
bb49d26032 net: implement opening PRIVATE_BROADCAST connections (Vasil Dimov)
01dad4efe2 net: introduce a new connection type for private broadcast (Vasil Dimov)
94aaa5d31b init: introduce a new option to enable/disable private broadcast (Vasil Dimov)
d6ee490e0a log: introduce a new category for private broadcast (Vasil Dimov)

Pull request description:

  _Parts of this PR are isolated in independent smaller PRs to ease review:_

  * [x] _https://github.com/bitcoin/bitcoin/pull/29420_
  * [x] _https://github.com/bitcoin/bitcoin/pull/33454_
  * [x] _https://github.com/bitcoin/bitcoin/pull/33567_
  * [x] _https://github.com/bitcoin/bitcoin/pull/33793_

  ---

  To improve privacy, broadcast locally submitted transactions (from the `sendrawtransaction` RPC) to the P2P network only via Tor or I2P short-lived connections, or to IPv4/IPv6 peers but through the Tor network.

  * Introduce a new connection type for private broadcast of transactions with the following properties:
    * started whenever there are local transactions to be sent
    * opened to Tor or I2P peers or IPv4/IPv6 via the Tor proxy
    * opened regardless of max connections limits
    * after handshake is completed one local transaction is pushed to the peer, `PING` is sent and after receiving `PONG` the connection is closed
    * ignore all incoming messages after handshake is completed (except `PONG`)

  * Broadcast transactions submitted via `sendrawtransaction` using this new mechanism, to a few peers. Keep doing this until we receive back this transaction from one of our ordinary peers (this takes about 1 second on mainnet).

  * The transaction is stored in peerman and does not enter the mempool.

  * Once we get an `INV` from one of our ordinary peers, then the normal flow executes: we request the transaction with `GETDATA`, receive it with a `TX` message, put it in our mempool and broadcast it to all our existent connections (as if we see it for the first time).

  * After we receive the full transaction as a `TX` message, in reply to our `GETDATA` request, only then consider the transaction has propagated through the network and remove it from the storage in peerman, ending the private broadcast attempts.

  The messages exchange should look like this:

  ```
  tx-sender >--- connect -------> tx-recipient
  tx-sender >--- VERSION -------> tx-recipient (dummy VERSION with no revealing data)
  tx-sender <--- VERSION -------< tx-recipient
  tx-sender <--- WTXIDRELAY ----< tx-recipient (maybe)
  tx-sender <--- SENDADDRV2 ----< tx-recipient (maybe)
  tx-sender <--- SENDTXRCNCL ---< tx-recipient (maybe)
  tx-sender <--- VERACK --------< tx-recipient
  tx-sender >--- VERACK --------> tx-recipient
  tx-sender >--- INV/TX --------> tx-recipient
  tx-sender <--- GETDATA/TX ----< tx-recipient
  tx-sender >--- TX ------------> tx-recipient
  tx-sender >--- PING ----------> tx-recipient
  tx-sender <--- PONG ----------< tx-recipient
  tx-sender disconnects
  ```

  Whenever a new transaction is received from `sendrawtransaction` RPC, the node will send it to a few (`NUM_PRIVATE_BROADCAST_PER_TX`) recipients right away. If after some time we still have not heard anything about the transaction from the network, then it will be sent to 1 more peer (see `PeerManagerImpl::ReattemptPrivateBroadcast()`).

  A few considerations:
  * The short-lived private broadcast connections are very cheap and fast wrt network traffic. It is expected that some of those peers could blackhole the transaction. Just one honest/proper peer is enough for successful propagation.
  * The peers that receive the transaction could deduce that this is initial transaction broadcast from the transaction originator. This is ok, they can't identify the sender.

  ---

  <details>
  <summary>How to test this?</summary>

  Thank you, @stratospher and @andrewtoth!

  Start `bitcoind` with `-privatebroadcast=1 -debug=privatebroadcast`.

  Create a wallet and get a new address, go to the Signet faucet and request some coins to that address:
  ```bash
  build/bin/bitcoin-cli -chain="signet" createwallet test
  build/bin/bitcoin-cli -chain="signet" getnewaddress
  ```

  Get a new address for the test transaction recipient:
  ```bash
  build/bin/bitcoin-cli -chain="signet" loadwallet test
  new_address=$(build/bin/bitcoin-cli -chain="signet" getnewaddress)
  ```

  Create the transaction:
  ```bash
  # Option 1: `createrawtransaction` and `signrawtransactionwithwallet`:

  txid=$(build/bin/bitcoin-cli -chain="signet" listunspent | jq -r '.[0] | .txid')
  vout=$(build/bin/bitcoin-cli -chain="signet" listunspent | jq -r '.[0] | .vout')
  echo "txid: $txid"
  echo "vout: $vout"

  tx=$(build/bin/bitcoin-cli -chain="signet" createrawtransaction "[{\"txid\": \"$txid\", \"vout\": $vout}]" "[{\"$new_address\": 0.00001000}]" 0 false)
  echo "tx: $tx"

  signed_tx=$(build/bin/bitcoin-cli -chain="signet" signrawtransactionwithwallet "$tx" | jq -r '.hex')
  echo "signed_tx: $signed_tx"

  # OR Option 2: `walletcreatefundedpsbt` and `walletprocesspsbt`:
  # This makes it not have to worry about inputs and also automatically sends back change to the wallet.
  # Start `bitcoind` with `-fallbackfee=0.00003000` for instance for 3 sat/vbyte fee.

  psbt=$(build/bin/bitcoin-cli -chain="signet" walletcreatefundedpsbt "[]" "[{\"$new_address\": 0.00001000}]" | jq -r '.psbt')
  echo "psbt: $psbt"

  signed_tx=$(build/bin/bitcoin-cli -chain="signet" walletprocesspsbt "$psbt" | jq -r '.hex')
  echo "signed_tx: $signed_tx"
  ```

  Finally, send the transaction:
  ```bash
  raw_tx=$(build/bin/bitcoin-cli -chain="signet" sendrawtransaction "$signed_tx")
  echo "raw_tx: $raw_tx"
  ```

  </details>

  ---

  <details>
  <summary>High-level explanation of the commits</summary>

  * New logging category and config option to enable private broadcast
    * `log: introduce a new category for private broadcast`
    * `init: introduce a new option to enable/disable private broadcast`

  * Implement the private broadcast connection handling on the `CConnman` side:
    * `net: introduce a new connection type for private broadcast`
    * `net: implement opening PRIVATE_BROADCAST connections`

  * Prepare `BroadcastTransaction()` for private broadcast requests:
    * `net_processing: rename RelayTransaction to better describe what it does`
    * `node: extend node::TxBroadcast with a 3rd option`
    * `net_processing: store transactions for private broadcast in PeerManager`

  * Implement the private broadcast connection handling on the `PeerManager` side:
    * `net_processing: reorder the code that handles the VERSION message`
    * `net_processing: move the debug log about receiving VERSION earlier`
    * `net_processing: modernize PushNodeVersion()`
    * `net_processing: move a debug check in VERACK processing earlier`
    * `net_processing: handle ConnectionType::PRIVATE_BROADCAST connections`
    * `net_processing: stop private broadcast of a transaction after round-trip`
    * `net_processing: retry private broadcast`

  * Engage the new functionality from `sendrawtransaction`:
    * `rpc: use private broadcast from sendrawtransaction RPC if -privatebroadcast is ON`

  * New tests:
    * `test: add functional test for private broadcast`
    * `test: add unit test for the private broadcast storage`

  </details>

  ---

  **This PR would resolve the following issues:**
  https://github.com/bitcoin/bitcoin/issues/3828 Clients leak IPs if they are recipients of a transaction
  https://github.com/bitcoin/bitcoin/issues/14692 Can't configure bitocoind to only send tx via Tor but receive clearnet transactions
  https://github.com/bitcoin/bitcoin/issues/19042 Tor-only transaction broadcast onlynet=onion alternative
  https://github.com/bitcoin/bitcoin/issues/24557 Option for receive events with all networks, but send transactions and/or blocks only with anonymous network[s]?
  https://github.com/bitcoin/bitcoin/issues/25450 Ability to broadcast wallet transactions only via dedicated oneshot Tor connections
  https://github.com/bitcoin/bitcoin/issues/32235 Tor: TX circuit isolation

  **Issues that are related, but (maybe?) not to be resolved by this PR:**
  https://github.com/bitcoin/bitcoin/issues/21876 Broadcast a transaction to specific nodes
  https://github.com/bitcoin/bitcoin/issues/28636 new RPC: sendrawtransactiontopeer

  ---

  Further extensions:
  * Have the wallet do the private broadcast as well, https://github.com/bitcoin/bitcoin/issues/11887 would have to be resolved.
  * Have the `submitpackage` RPC do the private broadcast as well, [draft diff in the comment below](https://github.com/bitcoin/bitcoin/pull/29415#pullrequestreview-2972293733), thanks ismaelsadeeq!
  * Add some stats via RPC, so that the user can better monitor what is going on during and after the broadcast. Currently this can be done via the debug log, but that is not convenient.
  * Make the private broadcast storage, currently in peerman, persistent over node restarts.
  * Add (optional) random delay before starting to broadcast the transaction in order to avoid correlating unrelated transactions based on the time when they were broadcast. Suggested independently of this PR [here](https://github.com/bitcoin/bitcoin/issues/30471).
  * Consider periodically sending transactions that did not originate from the node as decoy, discussed [here](https://github.com/bitcoin/bitcoin/pull/29415#discussion_r2035414972).
  * Consider waiting for peer's FEEFILTER message and if the transaction that was sent to the peer is below that threshold, then assume the peer is going to drop it. Then use this knowledge to retry more aggressively with another peer, instead of the current 10 min. See [comment below](https://github.com/bitcoin/bitcoin/pull/29415#issuecomment-3258611648).
  * It may make sense to be able to override the default policy -- eg so submitrawtransaction can go straight to the mempool and relay, even if txs are normally privately relayed. See [comment below](https://github.com/bitcoin/bitcoin/pull/29415#issuecomment-3427086681).
  * As a side effect we have a new metric available - the time it takes for a transaction to reach a random node in the network (from the point of view of the private broadcast recipient the tx originator is a random node somewhere in the network). This can be useful for monitoring, unrelated to privacy characteristics of this feature.

  ---

  _A previous incarnation of this can be found at https://github.com/bitcoin/bitcoin/pull/27509. It puts the transaction in the mempool and (tries to) hide it from the outside observers. This turned out to be too error prone or maybe even impossible._

ACKs for top commit:
  l0rinc:
    code review diff ACK 8937221304
  andrewtoth:
    ACK 8937221304
  pinheadmz:
    ACK 8937221304
  w0xlt:
    ACK 8937221304 with nit https://github.com/bitcoin/bitcoin/pull/29415#discussion_r2654849875
  mzumsande:
    re-ACK 8937221304

Tree-SHA512: d51dadc865c2eb080c903cbe2f669e69a967e5f9fc64e9a20a68f39a67bf0db6ac2ad682af7fa24ef9f0942a41c89959341a16ba7b616475e1c5ab8e563b9b96
2026-01-12 15:02:14 -05:00
..
2025-05-01 03:05:57 +00:00

Unit tests

The sources in this directory are unit test cases. Boost includes a unit testing framework, and since Bitcoin Core already uses Boost, it makes sense to simply use this framework rather than require developers to configure some other framework (we want as few impediments to creating unit tests as possible).

The build system is set up to compile an executable called test_bitcoin that runs all of the unit tests. The main source file for the test library is found in util/setup_common.cpp.

The examples in this document assume the build directory is named build. You'll need to adapt them if you named it differently.

Compiling/running unit tests

Unit tests will be automatically compiled if dependencies were met during the generation of the Bitcoin Core build system and tests weren't explicitly disabled.

The unit tests can be run with ctest --test-dir build, which includes unit tests from subtrees.

Run build/bin/test_bitcoin --list_content for the full list of tests.

To run the unit tests manually, launch build/bin/test_bitcoin. To recompile after a test file was modified, run cmake --build build and then run the test again. If you modify a non-test file, use cmake --build build --target test_bitcoin to recompile only what's needed to run the unit tests.

To add more unit tests, add BOOST_AUTO_TEST_CASE functions to the existing .cpp files in the test/ directory or add new .cpp files that implement new BOOST_AUTO_TEST_SUITE sections.

To run the GUI unit tests manually, launch build/bin/test_bitcoin-qt

To add more GUI unit tests, add them to the src/qt/test/ directory and the src/qt/test/test_main.cpp file.

Running individual tests

The test_bitcoin runner accepts command line arguments from the Boost framework. To see the list of arguments that may be passed, run:

build/bin/test_bitcoin --help

For example, to run only the tests in the getarg_tests file, with full logging:

build/bin/test_bitcoin --log_level=all --run_test=getarg_tests

or

build/bin/test_bitcoin -l all -t getarg_tests

or to run only the doubledash test in getarg_tests

build/bin/test_bitcoin --run_test=getarg_tests/doubledash

The --log_level= (or -l) argument controls the verbosity of the test output.

The test_bitcoin runner also accepts some of the command line arguments accepted by bitcoind. Use -- to separate these sets of arguments:

build/bin/test_bitcoin --log_level=all --run_test=getarg_tests -- -printtoconsole=1

The -printtoconsole=1 after the two dashes sends debug logging, which normally goes only to debug.log within the data directory, to the standard terminal output as well.

Running test_bitcoin creates a temporary working (data) directory with a randomly generated pathname within test_common bitcoin/, which in turn is within the system's temporary directory (see temp_directory_path). This data directory looks like a simplified form of the standard bitcoind data directory. Its content will vary depending on the test, but it will always have a debug.log file, for example.

The location of the temporary data directory can be specified with the -testdatadir option. This can make debugging easier. The directory path used is the argument path appended with /test_common bitcoin/<test-name>/datadir. The directory path is created if necessary. Specifying this argument also causes the data directory not to be removed after the last test. This is useful for looking at what the test wrote to debug.log after it completes, for example. (The directory is removed at the start of the next test run, so no leftover state is used.)

$ build/bin/test_bitcoin --run_test=getarg_tests/doubledash -- -testdatadir=/somewhere/mydatadir
Test directory (will not be deleted): "/somewhere/mydatadir/test_common bitcoin/getarg_tests/doubledash/datadir"
Running 1 test case...

*** No errors detected
$ ls -l '/somewhere/mydatadir/test_common bitcoin/getarg_tests/doubledash/datadir'
total 8
drwxrwxr-x 2 admin admin 4096 Nov 27 22:45 blocks
-rw-rw-r-- 1 admin admin 1003 Nov 27 22:45 debug.log

If you run an entire test suite, such as --run_test=getarg_tests, or all the test suites (by not specifying --run_test), a separate directory will be created for each individual test.

Adding test cases

To add a new unit test file to our test suite, you need to add the file to either src/test/CMakeLists.txt or src/wallet/test/CMakeLists.txt for wallet-related tests. The pattern is to create one test file for each class or source file for which you want to create unit tests. The file naming convention is <source_filename>_tests.cpp and such files should wrap their tests in a test suite called <source_filename>_tests. For an example of this pattern, see uint256_tests.cpp.

Logging and debugging in unit tests

ctest --test-dir build will write to the log file build/Testing/Temporary/LastTest.log. You can additionally use the --output-on-failure option to display logs of the failed tests automatically on failure. For running individual tests verbosely, refer to the section above.

To write to logs from unit tests you need to use specific message methods provided by Boost. The simplest is BOOST_TEST_MESSAGE.

For debugging you can launch the test_bitcoin executable with gdb or lldb and start debugging, just like you would with any other program:

gdb build/bin/test_bitcoin

Segmentation faults

If you hit a segmentation fault during a test run, you can diagnose where the fault is happening by running gdb ./build/bin/test_bitcoin and then using the bt command within gdb.

Another tool that can be used to resolve segmentation faults is valgrind.

If for whatever reason you want to produce a core dump file for this fault, you can do that as well. By default, the boost test runner will intercept system errors and not produce a core file. To bypass this, add --catch_system_errors=no to the test_bitcoin arguments and ensure that your ulimits are set properly (e.g. ulimit -c unlimited).

Running the tests and hitting a segmentation fault should now produce a file called core (on Linux platforms, the file name will likely depend on the contents of /proc/sys/kernel/core_pattern).

You can then explore the core dump using

gdb build/bin/test_bitcoin core

(gdb) bt  # produce a backtrace for where a segfault occurred