8937221304doc: add release notes for 29415 (Vasil Dimov)582016fa5ftest: add unit test for the private broadcast storage (Vasil Dimov)e74d54e048test: add functional test for private broadcast (Vasil Dimov)818b780a05rpc: use private broadcast from sendrawtransaction RPC if -privatebroadcast is ON (Vasil Dimov)eab595f9cfnet_processing: retry private broadcast (Vasil Dimov)37b79f9c39net_processing: stop private broadcast of a transaction after round-trip (Vasil Dimov)2de53eee74net_processing: handle ConnectionType::PRIVATE_BROADCAST connections (Vasil Dimov)30a9853ad3net_processing: move a debug check in VERACK processing earlier (Vasil Dimov)d1092e5d48net_processing: modernize PushNodeVersion() (Vasil Dimov)9937a12a2fnet_processing: move the debug log about receiving VERSION earlier (Vasil Dimov)a098f37b9enet_processing: reorder the code that handles the VERSION message (Vasil Dimov)679ce3a0b8net_processing: store transactions for private broadcast in PeerManager (Vasil Dimov)a3faa6f944node: extend node::TxBroadcast with a 3rd option (Vasil Dimov)95c051e210net_processing: rename RelayTransaction() to better describe what it does (Vasil Dimov)bb49d26032net: implement opening PRIVATE_BROADCAST connections (Vasil Dimov)01dad4efe2net: introduce a new connection type for private broadcast (Vasil Dimov)94aaa5d31binit: introduce a new option to enable/disable private broadcast (Vasil Dimov)d6ee490e0alog: 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 ACK8937221304andrewtoth: ACK8937221304pinheadmz: ACK8937221304w0xlt: ACK8937221304with nit https://github.com/bitcoin/bitcoin/pull/29415#discussion_r2654849875 mzumsande: re-ACK8937221304Tree-SHA512: d51dadc865c2eb080c903cbe2f669e69a967e5f9fc64e9a20a68f39a67bf0db6ac2ad682af7fa24ef9f0942a41c89959341a16ba7b616475e1c5ab8e563b9b96
This directory contains integration tests that test bitcoind and its utilities in their entirety. It does not contain unit tests, which can be found in /src/test, /src/wallet/test, etc.
This directory contains the following sets of tests:
- fuzz A runner to execute all fuzz targets from /src/test/fuzz.
- functional which test the functionality of bitcoind and bitcoin-qt by interacting with them through the RPC and P2P interfaces.
- lint which perform various static analysis checks.
The fuzz tests, functional tests and lint scripts can be run as explained in the sections below.
Running tests locally
Before tests can be run locally, Bitcoin Core must be built. See the building instructions for help.
The following examples assume that the build directory is named build.
Fuzz tests
See /doc/fuzzing.md
Functional tests
Dependencies and prerequisites
The ZMQ functional test requires a python ZMQ library. To install it:
- on Unix, run
sudo apt-get install python3-zmq - on mac OS, run
pip3 install pyzmq
The IPC functional test requires a python IPC library. pip3 install pycapnp may work, but if not, install it from source:
git clone -b v2.2.1 https://github.com/capnproto/pycapnp
pip3 install ./pycapnp
If that does not work, try adding -C force-bundled-libcapnp=True to the pip command.
Depending on the system, it may be necessary to install and run in a venv:
python -m venv venv
git clone -b v2.2.1 https://github.com/capnproto/pycapnp
venv/bin/pip3 install ./pycapnp -C force-bundled-libcapnp=True
venv/bin/python3 build/test/functional/interface_ipc.py
The functional tests assume Python UTF-8 Mode, which is the default on most
systems.
On Windows the PYTHONUTF8 environment variable must be set to 1:
set PYTHONUTF8=1
Running the tests
Individual tests can be run by directly calling the test script, e.g.:
build/test/functional/feature_rbf.py
or can be run through the test_runner harness, eg:
build/test/functional/test_runner.py feature_rbf.py
You can run any combination (incl. duplicates) of tests by calling:
build/test/functional/test_runner.py <testname1> <testname2> <testname3> ...
Wildcard test names can be passed, if the paths are coherent and the test runner
is called from a bash shell or similar that does the globbing. For example,
to run all the wallet tests:
build/test/functional/test_runner.py test/functional/wallet*
functional/test_runner.py functional/wallet* # (called from the build/test/ directory)
test_runner.py wallet* # (called from the build/test/functional/ directory)
but not
build/test/functional/test_runner.py wallet*
Combinations of wildcards can be passed:
build/test/functional/test_runner.py ./test/functional/tool* test/functional/mempool*
test_runner.py tool* mempool*
Run the regression test suite with:
build/test/functional/test_runner.py
Run all possible tests with
build/test/functional/test_runner.py --extended
In order to run backwards compatibility tests, first run:
test/get_previous_releases.py
to download the necessary previous release binaries.
By default, up to 4 tests will be run in parallel by test_runner. To specify
how many jobs to run, append --jobs=n
The individual tests and the test_runner harness have many command-line
options. Run build/test/functional/test_runner.py -h to see them all.
Speed up test runs with a RAM disk
If you have available RAM on your system you can create a RAM disk to use as the cache and tmp directories for the functional tests in order to speed them up.
Speed-up amount varies on each system (and according to your RAM speed and other variables), but a 2-3x speed-up is not uncommon.
Linux
To create a 4 GiB RAM disk at /mnt/tmp/:
sudo mkdir -p /mnt/tmp
sudo mount -t tmpfs -o size=4g tmpfs /mnt/tmp/
Configure the size of the RAM disk using the size= option.
The size of the RAM disk needed is relative to the number of concurrent jobs the test suite runs.
For example running the test suite with --jobs=100 might need a 4 GiB RAM disk, but running with --jobs=32 will only need a 2.5 GiB RAM disk.
To use, run the test suite specifying the RAM disk as the cachedir and tmpdir:
build/test/functional/test_runner.py --cachedir=/mnt/tmp/cache --tmpdir=/mnt/tmp
Once finished with the tests and the disk, and to free the RAM, simply unmount the disk:
sudo umount /mnt/tmp
macOS
To create a 4 GiB RAM disk named "ramdisk" at /Volumes/ramdisk/:
diskutil erasevolume HFS+ ramdisk $(hdiutil attach -nomount ram://8388608)
Configure the RAM disk size, expressed as the number of blocks, at the end of the command
(4096 MiB * 2048 blocks/MiB = 8388608 blocks for 4 GiB). To run the tests using the RAM disk:
build/test/functional/test_runner.py --cachedir=/Volumes/ramdisk/cache --tmpdir=/Volumes/ramdisk/tmp
To unmount:
umount /Volumes/ramdisk
Troubleshooting and debugging test failures
Resource contention
The P2P and RPC ports used by the bitcoind nodes-under-test are chosen to make conflicts with other processes unlikely. However, if there is another bitcoind process running on the system (perhaps from a previous test which hasn't successfully killed all its bitcoind nodes), then there may be a port conflict which will cause the test to fail. It is recommended that you run the tests on a system where no other bitcoind processes are running.
On linux, the test framework will warn if there is another bitcoind process running when the tests are started.
If there are zombie bitcoind processes after test failure, you can kill them by running the following commands. Note that these commands will kill all bitcoind processes running on the system, so should not be used if any non-test bitcoind processes are being run.
killall bitcoind
or
pkill -9 bitcoind
Data directory cache
A pre-mined blockchain with 200 blocks is generated the first time a functional test is run and is stored in build/test/cache. This speeds up test startup times since new blockchains don't need to be generated for each test. However, the cache may get into a bad state, in which case tests will fail. If this happens, remove the cache directory (and make sure bitcoind processes are stopped as above):
rm -rf build/test/cache
killall bitcoind
Test logging
The tests contain logging at five different levels (DEBUG, INFO, WARNING, ERROR
and CRITICAL). From within your functional tests you can log to these different
levels using the logger included in the test_framework, e.g.
self.log.debug(object). By default:
- when run through the test_runner harness, all logs are written to
test_framework.logand no logs are output to the console. - when run directly, all logs are written to
test_framework.logand INFO level and above are output to the console. - when run by our CI (Continuous Integration), no logs are output to the console. However, if a test
fails, the
test_framework.logand bitcoinddebug.logs will all be dumped to the console to help troubleshooting.
These log files can be located under the test data directory (which is always printed in the first line of test output):
<test data directory>/test_framework.log<test data directory>/node<node number>/regtest/debug.log.
The node number identifies the relevant test node, starting from node0, which
corresponds to its position in the nodes list of the specific test,
e.g. self.nodes[0].
To change the level of logs output to the console, use the -l command line
argument.
test_framework.log and bitcoind debug.logs can be combined into a single
aggregate log by running the combine_logs.py script. The output can be plain
text, colorized text or html. For example:
build/test/functional/combine_logs.py -c <test data directory> | less -r
will pipe the colorized logs from the test into less.
Use --tracerpc to trace out all the RPC calls and responses to the console. For
some tests (eg any that use submitblock to submit a full block over RPC),
this can result in a lot of screen output.
By default, the test data directory will be deleted after a successful run.
Use --nocleanup to leave the test data directory intact. The test data
directory is never deleted after a failed test.
Attaching a debugger
A python debugger can be attached to tests at any point. Just add the line:
import pdb; pdb.set_trace()
anywhere in the test. You will then be able to inspect variables, as well as call methods that interact with the bitcoind nodes-under-test.
If further introspection of the bitcoind instances themselves becomes
necessary, this can be accomplished by first setting a pdb breakpoint
at an appropriate location, running the test to that point, then using
gdb (or lldb on macOS) to attach to the process and debug.
For instance, to attach to self.node[1] during a run you can get
the pid of the node within pdb.
(pdb) self.node[1].process.pid
Alternatively, you can find the pid by inspecting the temp folder for the specific test you are running. The path to that folder is printed at the beginning of every test run:
2017-06-27 14:13:56.686000 TestFramework (INFO): Initializing test directory /tmp/user/1000/testo9vsdjo3
Use the path to find the pid file in the temp folder:
cat /tmp/user/1000/testo9vsdjo3/node1/regtest/bitcoind.pid
Then you can use the pid to start gdb:
gdb /home/example/bitcoind <pid>
Note: gdb attach step may require ptrace_scope to be modified, or sudo preceding the gdb.
See this link for considerations: https://www.kernel.org/doc/Documentation/security/Yama.txt
Often while debugging RPC calls in functional tests, the test might time out before the
process can return a response. Use --timeout-factor 0 to disable all RPC timeouts for that particular
functional test. Ex: build/test/functional/wallet_hd.py --timeout-factor 0.
Profiling
An easy way to profile node performance during functional tests is provided
for Linux platforms using perf.
Perf will sample the running node and will generate profile data in the node's
datadir. The profile data can then be presented using perf report or a graphical
tool like hotspot.
To generate a profile during test suite runs, use the --perf flag.
To see render the output to text, run
perf report -i /path/to/datadir/send-big-msgs.perf.data.xxxx --stdio | c++filt | less
For ways to generate more granular profiles, see the README in test/functional.
Lint tests
See the README in test/lint.
Writing functional tests
You are encouraged to write functional tests for new or existing features. Further information about the functional test framework and individual tests is found in test/functional.