Commit graph

25659 commits

Author SHA1 Message Date
furszy
ca09415e63
rpc, doc: encryptwallet, mention HD seed rotation and new backup
Better to notify users about the HD seed rotation and the new
backup requirement before executing the encryption process.
Ensuring they are prepared to update previous backups and
securely safeguard the updated wallet file.

Co-authored-by: jonatack <jon@atack.com>
2023-12-05 18:46:58 -03:00
Andrew Chow
406b71abcb wallet: Migrate entire address book entries 2023-12-05 13:35:55 -05:00
Martin Zumsande
494a926d05 rpc: fix getrawtransaction segfault
The crash would happen when querying a mempool transaction with verbosity=2, while pruning.
2023-12-05 13:11:02 -05:00
MarcoFalke
fa8adbe7c1
build: Enable -Wunreachable-code 2023-12-05 15:36:08 +01:00
fanquake
b3ab0c3819
Merge bitcoin/bitcoin#28997: fuzz: txorphan check wtxids using GenTxid::Wtxid not GenTxid::Txid
38816ff64e fuzz: txorphan check wtxids using GenTxid::Wtxid not GenTxid::Txid (Greg Sanders)

Pull request description:

  Fixes the bugs in the fuzz test with no more changes as an alternative to https://github.com/bitcoin/bitcoin/pull/28658

ACKs for top commit:
  naumenkogs:
    ACK 38816ff64e
  dergoegge:
    ACK 38816ff64e

Tree-SHA512: 5e46a83f2b2a2ac0672a63eb6200b019e01089ab1aa80c4ab869b6fcf27ccf2e84a064e96397f1a1869ccfa43b0c9638cbae681a27c4ca3c96ac71f41262601e
2023-12-05 10:56:07 +00:00
Kashif Smith
c2b836b119 bitcoin-tx: Make replaceable value optional 2023-12-04 16:14:00 -05:00
Greg Sanders
38816ff64e fuzz: txorphan check wtxids using GenTxid::Wtxid not GenTxid::Txid 2023-12-04 14:42:13 -05:00
Ryan Ofsky
6db04be102 Get rid of shutdown.cpp/shutdown.h, use SignalInterrupt directly
This change is mostly a refectoring that removes some code and gets rid of an
unnecessary layer of indirection after #27861

But it is not a pure refactoring since StartShutdown, AbortShutdown, and
WaitForShutdown functions used to abort on failure, and the replacement code
logs or returns errors instead.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
213542b625 refactor: Add InitContext function to initialize NodeContext with global pointers
Having InitContext() avoids the need to add duplicate code to src/init/*.cpp
files in the next commit. It also lets these files avoid referencing global
variables like gArgs.

There is no change in behavior in this commit.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
feeb7b816a refactor: Remove calls to StartShutdown from KernelNotifications
Use SignalInterrupt object instead. There is a slight change in behavior here
because the previous StartShutdown code used to abort on failure and the
new code logs errors instead.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
6824eecaf1 refactor: Remove call to StartShutdown from stop RPC
Use SignalInterrupt object instead. There is a slight change in behavior here
because the previous StartShutdown code used to abort on failure and the
new code returns an RPC error instead.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
1d92d89edb util: Get rid of uncaught exceptions thrown by SignalInterrupt class
Replace exceptions thrown by signal and wait methods with [[nodiscard]] return
values.

This is mostly a refactoring, but there is a slight change of behavior if
AbortShutdown function fails. The original behavior which was unintentionally
changed in #27861 is restored, so it now triggers an assert failure again
instead of throwing an exception. (The AbortShutdown function is only ever
called in the the GUI version of Bitcoin Core when corruption is detected on
loading and the user tries to reindex.)

Problems with using exceptions were pointed out by MarcoFalke in
https://github.com/bitcoin/bitcoin/pull/27861#discussion_r1255496707.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
ba93966368 refactor: Remove call to ShutdownRequested from IndexWaitSynced
Use the node interrupt object instead.

There is no change in behavior in this commit.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
42e5829d97 refactor: Remove call to ShutdownRequested from HTTPRequest
Pass HTTP server an interrupt object instead of having it depend on shutdown.h
and global shutdown state.

There is no change in behavior in this commit.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
73133c36aa refactor: Add NodeContext::shutdown member
Add NodeContext::shutdown variable and start using it to replace the
kernel::Context::interrupt variable. The latter can't easily be removed right
away but will be removed later in this PR.

Moving the interrupt object from the kernel context to the node context
increases flexibility of the kernel API so it is possible to use multiple
interrupt objects, or avoid creating one if one is not needed. It will also
allow getting rid of the kernel::g_context global later in this PR, replacing
it with a private SignalInterrupt instance in init.cpp

There is no change in behavior in this commit outside of unit tests. In unit
tests there should be no visible change either, but internally now each test
has its own interrupt variable so the variable will be automatically reset
between tests.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
f4a8bd6e2f refactor: Remove call to StartShutdown from qt
Use interfaces::Node object instead.

There is a minor change in behavior in this commit, because the new code calls
InterruptRPC() and StopRPC() when previous code did not do this.  But this
should be a good thing since it makes sense to interrupt RPC when the system is
shutting down, and it is better for the GUI shut down in a consistent way
regardless of how the shutdown is triggered.
2023-12-04 15:39:15 -04:00
Ryan Ofsky
f0c73c1336 refactor: Remove call to ShutdownRequested from rpc/mining
Use chainman.m_interrupt object instead

There is no change in behavior in this commit
2023-12-04 15:39:15 -04:00
Ryan Ofsky
263b23f008 refactor: Remove call to ShutdownRequested from chainstate init
Use chainman.m_interrupt object instead

There is no change in behavior in this commit
2023-12-04 15:39:15 -04:00
willcl-ark
8f6ab31863
init: don't delete PID file if it was not generated
Previously, starting a second bitcoind using the same datadir would
correctly fail to init and shutdown. However during shutdown the PID
file belonging to the first instance would be erroneously removed by
the second process shutting down.

Fix this to only delete the PID file if we created it.
2023-12-04 12:54:20 +00:00
Hennadii Stepanov
55e3dc3e03
test: Fix test by checking the actual exception instance
The BOOST_REQUIRE_THROW passes even if the command raises an exception
in the underlying subprocess implementation, which might have a type
derived from std::runtime_error.
2023-12-03 16:04:20 +00:00
Fabian Jahr
3ea54e5db7
net: Add continuous ASMap health check logging 2023-12-02 22:03:08 +01:00
Andrew Chow
a97a89244e
Merge bitcoin/bitcoin#28368: Fee Estimator updates from Validation Interface/CScheduler thread
91504cbe0d rpc: `SyncWithValidationInterfaceQueue` on fee estimation RPC's (ismaelsadeeq)
714523918b tx fees, policy: CBlockPolicyEstimator update from `CValidationInterface` notifications (ismaelsadeeq)
dff5ad3b99 CValidationInterface: modify the parameter of `TransactionAddedToMempool` (ismaelsadeeq)
91532bd382 tx fees, policy: update `CBlockPolicyEstimator::processBlock` parameter (ismaelsadeeq)
bfcd401368 CValidationInterface, mempool: add new callback to `CValidationInterface` (ismaelsadeeq)
0889e07987 tx fees, policy: cast with static_cast instead of C-Style cast (ismaelsadeeq)
a0e3eb7549 tx fees, policy: bugfix: move `removeTx` into reason != `BLOCK` condition (ismaelsadeeq)

Pull request description:

  This is an attempt to  #11775

  This Pr will enable fee estimator to listen to ValidationInterface notifications to process new transactions added and removed from the mempool.

  This PR includes the following changes:

  - Added a new callback to the Validation Interface `MempoolTransactionsRemovedForConnectedBlock`, which notifies listeners about the transactions that have been removed due to a new block being connected, along with the height at which the transactions were removed.
  - Modified the `TransactionAddedToMempool` callback parameter to include additional information about the transaction needed for fee estimation.
  - Updated `CBlockPolicyEstimator` to process transactions using` CTransactionRef` instead of `CTxMempoolEntry.`
  - Implemented the `CValidationInterface` interface in `CBlockPolicyEstimater` and overridden the `TransactionAddedToMempool`, `TransactionRemovedFromMempool`, and `MempoolTransactionsRemovedForConnectedBlock` methods to receive updates from their notifications.

  Prior to this PR, the fee estimator updates from the mempool, i.e whenever a new block is connected all transactions in the block that are in our mempool are going to be removed using the `removeForBlock` function in `txmempool.cpp`.

  This removal triggered updates to the fee estimator. As a result, the fee estimator would block mempool's `cs` until it finished updating every time a new block was connected.
  Instead of being blocked only on mempool tx removal, we were blocking on both tx removal and fee estimator updating.
  If we want to further improve fee estimation, or add heavy-calulation steps to it, it is currently not viable as we would be slowing down block relay in the process

  This PR is smaller in terms of the changes made compared to #11775, as it focuses solely on enabling fee estimator updates from the validationInterface/cscheduler thread notifications.

  I have not split the validation interface because, as I understand it, the rationale behind the split in #11775 was to have `MempoolInterface` signals come from the mempool and `CValidationInterface` events come from validation. I believe this separation can be achieved in a separate refactoring PR when the need arises.

  Also left out some commits from #11775
  - Some refactoring which are no longer needed.
  - Handle reorgs much better in fee estimator.
  - Track witness hash malleation in fee estimator

  I believe they are a separate change that can come in a follow-up after this.

ACKs for top commit:
  achow101:
    ACK 91504cbe0d
  TheCharlatan:
    Re-ACK 91504cbe0d
  willcl-ark:
    ACK 91504cbe0d

Tree-SHA512: 846dfb9da57a8a42458827b8975722d153907fe6302ad65748d74f311e1925557ad951c3d95fe71fb90ddcc8a3710c45abb343ab86b88780871cb9c38c72c7b1
2023-12-01 15:07:23 -05:00
Andrew Chow
18bed148af
Merge bitcoin/bitcoin#28784: rpc: keep .cookie file if it was not generated
7cb9367157 rpc: keep .cookie if it was not generated (Roman Zeyde)

Pull request description:

  Otherwise, starting bitcoind twice may cause the `.cookie` file generated by the first instance to be deleted by the second instance shutdown (after failing to obtain a lock).

ACKs for top commit:
  willcl-ark:
    re-ACK 7cb9367157
  achow101:
    ACK 7cb9367157
  kristapsk:
    re-ACK 7cb9367157
  stickies-v:
    ACK 7cb9367157

Tree-SHA512: 0960dbc457975b0e0535f3d814824a879d7f85c9f1191537415b3fc253429a316a8e4badde56c8bc139778f132392983cec5fbe03891fb15ff61d3bc3f6e681b
2023-12-01 12:24:29 -05:00
Andrew Chow
6b3927f79a
Merge bitcoin/bitcoin#28848: bugfix, Change up submitpackage results to return results for all transactions
f23ba24aa0 test_submitpackage: only make a chain of 3 txns (Greg Sanders)
e67a345162 doc: submitpackage vsize results are sigops-adjusted (Greg Sanders)
b67db52c39 RPC submitpackage: change return format to allow partial errors (Greg Sanders)

Pull request description:

  This was prompted by errors being returned that didn't "make any sense" to me, because it would for example return a "fee too low" error, when the "real" error was the child had something invalid, which disallowed CPFP evaluation. Rather than make judgment calls on what error is important(which is currently just return the "first"!), we simply return all errors and let the callers determine what's best.

  Added a top level `package_msg` for quick eye-balling of general success of the package.

  This PR also fixes a couple bugs:

  1) Currently we don't actually broadcast a transaction, even if it was entered into our mempool, if a subsequent transaction causes `PKG_TX` failure.
  2) "other-wtxid" is uncovered by tests, but IIUC was previously required to return "fees" and "vsize" results, but did not. I just make those results optional.

ACKs for top commit:
  Sjors:
    Light re-utACK f23ba24aa0
  achow101:
    ACK f23ba24aa0
  glozow:
    utACK f23ba24aa0, thanks for taking the suggestions

Tree-SHA512: ebfd716a4fed9e8c2dea3d2181ba6a6171b06718d29ac2324c67b7a30b374d199f7e1739f91ab5d036be172d0479de9bc89c32263ee62143c0338b9b622d0cca
2023-12-01 12:17:15 -05:00
Andrew Chow
498994b6f5
Merge bitcoin/bitcoin#26762: bugfix: Make CCheckQueue RAII-styled (attempt 2)
5b3ea5fa2e refactor: Move `{MAX,DEFAULT}_SCRIPTCHECK_THREADS` constants (Hennadii Stepanov)
6e17b31680 refactor: Make `CCheckQueue` non-copyable and non-movable explicitly (Hennadii Stepanov)
8111e74653 refactor: Drop unneeded declaration (Hennadii Stepanov)
9cf89f7a5b refactor: Make `CCheckQueue` constructor start worker threads (Hennadii Stepanov)
d03eaacbcf Make `CCheckQueue` destructor stop worker threads (Hennadii Stepanov)
be4ff3060b Move global `scriptcheckqueue` into `ChainstateManager` class (Hennadii Stepanov)

Pull request description:

  This PR:
  - makes `CCheckQueue` RAII-styled
  - gets rid of the global `scriptcheckqueue`
  - fixes https://github.com/bitcoin/bitcoin/issues/25448

  The previous attempt was in https://github.com/bitcoin/bitcoin/pull/18731.

ACKs for top commit:
  martinus:
    ACK 5b3ea5fa2e
  achow101:
    ACK 5b3ea5fa2e
  TheCharlatan:
    ACK 5b3ea5fa2e

Tree-SHA512: 45cca846e7ed107e3930149f0b616ddbaf2648d6cde381f815331b861b5d67ab39e154883ae174b8abb1dae485bc904318c50c51e5d6b46923d89de51c5eadb0
2023-11-30 14:28:46 -05:00
Ryan Ofsky
ffb021612b
Merge bitcoin/bitcoin#28451: refactor: Remove unused SER_DISK, SER_NETWORK, CDataStream
fa98a097a3 Rename version.h to node/protocol_version.h (MarcoFalke)
fa4fbd5816 Remove unused version.h include (MarcoFalke)
fa0ae22ff2 Remove unused SER_NETWORK, SER_DISK (MarcoFalke)
fae00fe9c2 Remove unused CDataStream (MarcoFalke)
fa7eb4f5c3 fuzz: Drop unused version from fuzz input format (MarcoFalke)

Pull request description:

  Seems odd to have code that is completely dead.

  Fix this by removing all of it.

ACKs for top commit:
  sipa:
    utACK fa98a097a3
  ajtowns:
    ACK fa98a097a3
  ryanofsky:
    Seems odd to not code review ACK fa98a097a3 (looks good)

Tree-SHA512: 9f1b9d9f92bda0512610bda6653e892756f637860362a9abfa439faab62de233cbad94b7df78ebacc160d9667aadfed4d9df08c0edefa618c040a049050fb913
2023-11-30 11:11:51 -05:00
fanquake
05d3f8e822
Merge bitcoin/bitcoin#28951: fuzz: BIP324: damage ciphertext/aad in full byte range
e67634ef19 fuzz: BIP324: damage ciphertext/aad in full byte range (Sebastian Falbesoner)

Pull request description:

  This PR is a tiny improvement for the `bip324_cipher_roundtrip` fuzz target: currently the damaging of input data for decryption (either ciphertext or aad) only ever happens in the lower nibble within the byte at the damage position, as the bit position for the `damage_val` byte was calculated with `damage_bit & 3` (corresponding to `% 4`) rather than `damage_bit & 7` (corresponding to the expected `% 8`).

  Noticed while reviewing #28263 which uses similar constructs.

ACKs for top commit:
  stratospher:
    ACK e67634ef.
  dergoegge:
    utACK e67634ef19

Tree-SHA512: 1bab4df28708e079874feee939beef45eff235215375c339decc696f4c9aef04e4b417322b045491c8aec6e88ec8ec2db564e27ef1b0be352b6ff4ed38bad49a
2023-11-30 15:03:53 +00:00
MarcoFalke
fa98a097a3
Rename version.h to node/protocol_version.h 2023-11-30 11:28:31 +01:00
MarcoFalke
fa4fbd5816
Remove unused version.h include 2023-11-30 11:28:19 +01:00
MarcoFalke
fa0ae22ff2
Remove unused SER_NETWORK, SER_DISK 2023-11-30 11:28:17 +01:00
MarcoFalke
fae00fe9c2
Remove unused CDataStream 2023-11-30 11:27:54 +01:00
MarcoFalke
fa7eb4f5c3
fuzz: Drop unused version from fuzz input format 2023-11-30 11:27:21 +01:00
Greg Sanders
e67a345162 doc: submitpackage vsize results are sigops-adjusted 2023-11-29 12:56:26 -05:00
Greg Sanders
b67db52c39 RPC submitpackage: change return format to allow partial errors
Behavior prior to this commit allows some transactions to
enter into the local mempool but not be reported to the user
when encountering a PackageValidationResult::PCKG_TX result.

This is further compounded with the fact that any transactions
submitted to the mempool during this call would also not be
relayed to peers, resulting in unexpected behavior.

Fix this by, if encountering a package error, reporting all
wtxids, along with a new error field, and broadcasting every
transaction that was found in the mempool after submission.

Note that this also changes fees and vsize to optional,
which should also remove an issue with other-wtxid cases.
2023-11-29 12:56:26 -05:00
fanquake
7bc8c5312b
Merge bitcoin/bitcoin#28969: fuzz: Avoid signed-integer-overflow in wallet_notifications fuzz target
fab164f342 fuzz: Avoid signed-integer-overflow in wallet_notifications fuzz target (MarcoFalke)

Pull request description:

  Should avoid

  ```
  policy/feerate.cpp:29:63: runtime error: signed integer overflow: 77600710321911316 * 149 cannot be represented in type 'int64_t' (aka 'long')
      #0 0x563a1775ed66 in CFeeRate::GetFee(unsigned int) const src/policy/feerate.cpp:29:63
      #1 0x563a15913a69 in wallet::COutput::COutput(COutPoint const&, CTxOut const&, int, int, bool, bool, bool, long, bool, std::optional<CFeeRate>) src/./wallet/coinselection.h:91:57
      #2 0x563a16fa6a6d in wallet::FetchSelectedInputs(wallet::CWallet const&, wallet::CCoinControl const&, wallet::CoinSelectionParams const&) src/wallet/spend.cpp:297:17
      #3 0x563a16fc4512 in wallet::CreateTransactionInternal(wallet::CWallet&, std::vector<wallet::CRecipient, std::allocator<wallet::CRecipient>> const&, int, wallet::CCoinControl const&, bool) src/wallet/spend.cpp:1105:33
      #4 0x563a16fbec74 in wallet::CreateTransaction(wallet::CWallet&, std::vector<wallet::CRecipient, std::allocator<wallet::CRecipient>> const&, int, wallet::CCoinControl const&, bool) src/wallet/spend.cpp:1291:16
      #5 0x563a16fcf6df in wallet::FundTransaction(wallet::CWallet&, CMutableTransaction&, long&, int&, bilingual_str&, bool, std::set<int, std::less<int>, std::allocator<int>> const&, wallet::CCoinControl) src/wallet/spend.cpp:1361:16
      #6 0x563a1597b7b9 in wallet::(anonymous namespace)::FuzzedWallet::FundTx(FuzzedDataProvider&, CMutableTransaction) src/wallet/test/fuzz/notifications.cpp:162:15
      #7 0x563a15958240 in wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>)::$_0::operator()() const src/wallet/test/fuzz/notifications.cpp:228:23
      #8 0x563a15958240 in unsigned long CallOneOf<wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>)::$_0, wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>)::$_1>(FuzzedDataProvider&, wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>)::$_0, wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>)::$_1) src/./test/fuzz/util.h:43:27
      #9 0x563a15958240 in wallet::(anonymous namespace)::wallet_notifications_fuzz_target(Span<unsigned char const>) src/wallet/test/fuzz/notifications.cpp:196:9
      #10 0x563a15fdef0c in std::function<void (Span<unsigned char const>)>::operator()(Span<unsigned char const>) const /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/bits/std_function.h:591:9
      #11 0x563a15fdef0c in LLVMFuzzerTestOneInput src/test/fuzz/fuzz.cpp:178:5
      #12 0x563a158032a4 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x19822a4) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #13 0x563a15802999 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x1981999) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #14 0x563a15804586 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::vector<fuzzer::SizedFile, std::allocator<fuzzer::SizedFile>>&) (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x1983586) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #15 0x563a15804aa7 in fuzzer::Fuzzer::Loop(std::vector<fuzzer::SizedFile, std::allocator<fuzzer::SizedFile>>&) (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x1983aa7) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #16 0x563a157f21fb in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x19711fb) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #17 0x563a1581c766 in main (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x199b766) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)
      #18 0x7f499e17b0cf  (/lib/x86_64-linux-gnu/libc.so.6+0x280cf) (BuildId: 96ab1a8f3b2c9a2ed37c7388615e6a726d037e89)
      #19 0x7f499e17b188 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x28188) (BuildId: 96ab1a8f3b2c9a2ed37c7388615e6a726d037e89)
      #20 0x563a157e70c4 in _start (/ci_container_base/ci/scratch/build/bitcoin-x86_64-pc-linux-gnu/src/test/fuzz/fuzz+0x19660c4) (BuildId: 8acb42ad599d7f6d25b6f93e18fd564d80df7c06)

  SUMMARY: UndefinedBehaviorSanitizer: signed-integer-overflow policy/feerate.cpp:29:63 in
  MS: 0 ; base unit: 0000000000000000000000000000000000000000
  0x3f,0x0,0x2f,0x5f,0x5f,0x5f,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0x7d,0xff,0xff,0xff,0xff,0xff,0x53,0xff,0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x13,0x5e,0x5f,0x5f,0x8,0x25,0x0,0x5f,0x5f,0x5f,0x5f,0x5f,0x5f,0x8,0x25,0xca,0x7f,0x5f,0x5f,0x5f,0x13,0x13,0x5f,0x5f,0x5f,0x2,0xdb,0xca,0x0,0x0,0xe7,0xe6,0x66,0x65,0x0,0x0,0x0,0x0,0x44,0x3f,0xa,0xa,0xff,0xff,0xff,0xff,0xff,0x61,0x76,0x6f,0x69,0x0,0xb5,0x15,
  ?\000/___}}}}}}}}}}}}}}}}}}}}\377\377\377\377\377S\377\377\377\377\377\000\000\000\000\000\000\023^__\010%\000______\010%\312\177___\023\023___\002\333\312\000\000\347\346fe\000\000\000\000D?\012\012\377\377\377\377\377avoi\000\265\025
  artifact_prefix='./'; Test unit written to ./crash-4d3bac8a64d4e58b2f0943e6d28e6e1f16328d7d
  Base64: PwAvX19ffX19fX19fX19fX19fX19fX19fX3//////1P//////wAAAAAAABNeX18IJQBfX19fX18IJcp/X19fExNfX18C28oAAOfmZmUAAAAARD8KCv//////YXZvaQC1FQ==

ACKs for top commit:
  dergoegge:
    ACK fab164f342
  brunoerg:
    ACK fab164f342

Tree-SHA512: f416828f4394aa7303ee437f141e9bbd23c0e0f1b830e4ef3932338858249ba68a811b9837c5b7ad8c6ab871b6354996434183597c1a910a8d8e8d829693e4b2
2023-11-29 17:18:01 +00:00
fanquake
dd73c22976
Merge bitcoin/bitcoin#28486: test, bench: Initialize and terminate use of Winsock properly
fd4c6a10f2 test: Setup networking globally (Hennadii Stepanov)

Pull request description:

  On the master branch, when compiling without external signer support, the `bench_bitcoin.exe` does not initialize Winsock DLL that is required, for example, here: 459272d639/src/bench/addrman.cpp (L124)

  Moreover, Windows docs explicitly [state](https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup) that `WSAStartup` and `WSACleanup` must be balanced:
  > There must be a call to `WSACleanup` for each successful call to `WSAStartup`. Only the final `WSACleanup` function call performs the actual cleanup. The preceding calls simply decrement an internal reference count in the WS2_32.DLL.

  That is not the case for our unit tests because the `SetupNetworking()` call is a part of the `BasicTestingSetup` fixture and is invoked multiple times, while `~CNetCleanup()` is invoked once only, at the end of the test binary execution.

  This PR fixes Winsock DLL initialization and termination.

  More docs:
  - https://learn.microsoft.com/en-us/windows/win32/winsock/initializing-winsock
  - https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup
  - https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup

  Fix https://github.com/bitcoin/bitcoin/issues/28940.

ACKs for top commit:
  maflcko:
    lgtm ACK fd4c6a10f2

Tree-SHA512: d360eaf776943f7f7a35ed5a5f9f3228d9e3d18eb824e5997cdc8eadddf466abe9f2da4910ee3bb86bf5411061e758259f7e1ec344f234ef7996f1bf8781dcda
2023-11-29 17:14:34 +00:00
MarcoFalke
fab164f342
fuzz: Avoid signed-integer-overflow in wallet_notifications fuzz target 2023-11-29 17:12:50 +01:00
MarcoFalke
faecde9102
fuzz: Fix nullptr deref in scriptpubkeyman
Also, add missing includes to scriptpubkeyman.

Also, export dependecies of the BasicTestingSetup from setup_common.h,
to avoid having to include them when setup_common.h is already included.
2023-11-29 16:04:08 +01:00
fanquake
8cf2137dbe
Merge bitcoin/bitcoin#28958: refactor: Use Txid in CMerkleBlock
fa02c08c93 refactor: Use Txid in CMerkleBlock (MarcoFalke)

Pull request description:

  This should also fix a gcc-13 compiler warning, see https://github.com/bitcoin/bitcoin/pull/28922#discussion_r1407856376

  ```
  rpc/txoutproof.cpp: In lambda function:
  rpc/txoutproof.cpp:72:33: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
     72 |                     const Coin& coin = AccessByTxid(active_chainstate.CoinsTip(), Txid::FromUint256(tx));
        |                                 ^~~~
  rpc/txoutproof.cpp:72:52: note: the temporary was destroyed at the end of the full expression ‘AccessByTxid((*(const CCoinsViewCache*)(&(& active_chainstate)->Chainstate::CoinsTip())), transaction_identifier<false>::FromUint256((* & tx)))’
     72 |                     const Coin& coin = AccessByTxid(active_chainstate.CoinsTip(), Txid::FromUint256(tx));
        |                                        ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  cc1plus: all warnings being treated as errors

ACKs for top commit:
  TheCharlatan:
    Re-ACK fa02c08c93
  dergoegge:
    reACK fa02c08c93

Tree-SHA512: 2e6837b9d0c90bd6e9d766330e7086d68c6ec80bb27fe2cfc4702b251b00d91a79f8bfbc76d998cbcd90bee5317402cf617f61099eee96d94e7ac8f37ba7a642
2023-11-29 10:55:18 +00:00
Andrew Chow
16b5b4b674
Merge bitcoin/bitcoin#28579: refactor: Remove redundant checks in compat/assumptions.h
fa1a384706 Move compat.h include from system.h to system.cpp (MarcoFalke)
88887531b7 Move compat/assumptions.h include to one place that actually needs it (MarcoFalke)
77774110f4 Remove __cplusplus from compat/assumptions.h (MarcoFalke)
faa3d4f1d8 Remove duplicate NDEBUG check from compat/assumptions.h (MarcoFalke)

Pull request description:

  Generally, compile-time checks should be close to the code that use them. Especially, since `compat/assumptions.h` is only included in one place, where iwyu suggests to remove it.

  Fix all issues:
  * The `NDEBUG` check is used in `util/check`, so it is redundant in `compat/assumptions.h`.
  * The `__cplusplus` check is redundant with `doc/dependencies.md` (see commit message).
  * Add missing `// IWYU pragma: keep` to avoid removing the include by accident.

ACKs for top commit:
  achow101:
    ACK fa1a384706
  TheCharlatan:
    re-ACK fa1a384706
  theuni:
    ACK fa1a384706

Tree-SHA512: f8b6db84be5d8844a2267345c0b1405fcbc39b8b5eeaa24db5b8412a74145fe44cf188b6b0c39cc2b062690ed37ca5b4662473484afe28dbec6469e79961389b
2023-11-28 16:51:28 -05:00
Andrew Chow
75462b39d2
Merge bitcoin/bitcoin#28554: bugfix: throw an error if an invalid parameter is passed to getnetworkhashps RPC
9ac114e5cd Throw error if invalid parameters passed to getnetworkhashps RPC endpoint (Jameson Lopp)

Pull request description:

  When writing some scripts that iterated over many blocks to generate hashrate estimates I realized that my script was going out of range of the current chain tip height but was not encountering any errors.

  I believe that passing an invalid block height to this function but receiving the hashrate estimate for the chain tip instead should be considered unexpected behavior.

ACKs for top commit:
  Sjors:
    re-utACK 9ac114e5cd
  kevkevinpal:
    reACK [9ac114e](9ac114e5cd)
  achow101:
    ACK 9ac114e5cd

Tree-SHA512: eefb465c2dd654fc48267f444e1809597ec5363cdd131ea9ec812458fed1e4bffbbbb0617d74687c9f7bb16274b598d8292f5eeb7953421e5d2a8dc2cc081f2b
2023-11-28 16:26:04 -05:00
Andrew Chow
535424a10b
Merge bitcoin/bitcoin#28903: refactor: Make CTxMemPoolEntry only explicitly copyable
705e3f1de0 refactor: Make CTxMemPoolEntry only explicitly copyable (TheCharlatan)

Pull request description:

  This has the goal of prohibiting users from accidentally creating runtime failures, e.g. by interacting with iterator_to with a copied entry. This was brought up here:  https://github.com/bitcoin/bitcoin/pull/28886#issuecomment-1814794954.

  CTxMemPoolEntry is already implicitly not move-constructable. So be explicit about this and use a std::list to collect the values in the policy_estimator fuzz test instead of a std::vector.

ACKs for top commit:
  maflcko:
    ACK 705e3f1de0 🌯
  achow101:
    ACK 705e3f1de0
  ajtowns:
    ACK 705e3f1de0
  ismaelsadeeq:
    ACK 705e3f1de0

Tree-SHA512: 62056905c679c919d00f9ae065ed66ac986e7e7062015aea542843d8deecda57104d7a68d002f7b20afa3164f8e9215d2d2d002c167224129540e3b1bd0712cc
2023-11-28 14:45:23 -05:00
Hennadii Stepanov
fd4c6a10f2
test: Setup networking globally 2023-11-28 19:11:52 +00:00
Ryan Ofsky
6acec6b9ff multiprocess: Add type conversion code for UniValue types
Extend IPC unit test to cover this and verify the serialization happens
correctly.
2023-11-28 12:35:50 -05:00
fanquake
fe4e83f50d
Merge bitcoin/bitcoin#28912: refactor: VectorWriter and SpanReader without nVersion
fae76a1f2a scripted-diff: Use DataStream in most places (MarcoFalke)
fac39b56b7 refactor: SpanReader without nVersion (MarcoFalke)

Pull request description:

  The serialize version is unused, so remove it. This also allows to remove `GCS_SER_VERSION` and allows a scripted-diff to remove most of `CDataStream`.

ACKs for top commit:
  ajtowns:
    ACK fae76a1f2a
  ryanofsky:
    Code review ACK fae76a1f2a

Tree-SHA512: 3b487dba8ea380f1eacff9fdfb9197f025dbc30906813d3f4c3e6f1e9e4d9f2a169c6f163f51d135e18af538be78e2d2b13d694073ad25c5762980ae971a4c83
2023-11-28 17:35:50 +00:00
Ryan Ofsky
0cc74fce72 multiprocess: Add type conversion code for serializable types
Allow any C++ object that has Serialize and Unserialize methods and can be
serialized to a bitcoin CDataStream to be converted to a capnproto Data field
and passed as arguments or return values to capnproto methods using the Data
type.

Extend IPC unit test to cover this and verify the serialization happens
correctly.
2023-11-28 12:35:50 -05:00
Ryan Ofsky
4aaee23921 test: add ipc test to test multiprocess type conversion code
Add unit test to test IPC method calls and type conversion between bitcoin c++
types and capnproto messages.

Right now there are custom type hooks in bitcoin IPC code, so the test is
simple, but in upcoming commits, code will be added to convert bitcoin types to
capnproto messages, and the test will be expanded.
2023-11-28 12:35:50 -05:00
MarcoFalke
fa02c08c93
refactor: Use Txid in CMerkleBlock 2023-11-28 17:49:41 +01:00
fanquake
31ce305d46
Merge bitcoin/bitcoin#28952: fuzz: Avoid timeout in process_messages
fa825975b5 fuzz: Avoid timeout in process_messages (MarcoFalke)

Pull request description:

  Reduce the number of messages per fuzz input. There should be no reason to have more messages than that.

  This should also avoid timeouts, such as https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=64548. CC https://github.com/bitcoin/bitcoin/issues/28812

ACKs for top commit:
  dergoegge:
    utACK fa825975b5

Tree-SHA512: eeff732f7b0bd9a71f23aeecbf813d31fe34d355b906fd0384a43075cbc3cebc46a26df741b0f337208d8b33b3e28210c9b9437e2eed77844f03131bb8f5f2a1
2023-11-28 16:24:06 +00:00
Andrew Chow
26b7bcf10e
Merge bitcoin/bitcoin#28766: Improve peformance of CTransaction::HasWitness (28107 follow-up)
af1d2ff883 [primitives] Precompute result of CTransaction::HasWitness (dergoegge)

Pull request description:

  This addresses https://github.com/bitcoin/bitcoin/pull/28107#discussion_r1364961590 from #28107.

ACKs for top commit:
  theStack:
    ACK af1d2ff883
  achow101:
    ACK af1d2ff883
  stickies-v:
    ACK af1d2ff883
  TheCharlatan:
    ACK af1d2ff883

Tree-SHA512: a77654ae429d0d7ce12daa309770e75beec4f8984734f80ed203156199425af43b50ad3d8aab85a89371a71356464ebd4503a0248fd0103579adfc74a55aaf51
2023-11-28 08:44:41 -05:00
MarcoFalke
fae76a1f2a
scripted-diff: Use DataStream in most places
The remaining places are handled easier outside a scripted-diff.

-BEGIN VERIFY SCRIPT-
 sed --regexp-extended -i 's/CDataStream ([0-9a-zA-Z_]+)\(SER_[A-Z]+, [A-Z_]+_VERSION\);/DataStream \1{};/g' $( git grep -l CDataStream)
 sed -i 's/, CDataStream/, DataStream/g' src/wallet/walletdb.cpp
-END VERIFY SCRIPT-
2023-11-28 12:42:37 +01:00
MarcoFalke
fac39b56b7
refactor: SpanReader without nVersion
The field is unused, so remove it.

This is also required for future commits.
2023-11-28 12:42:07 +01:00
fanquake
c252a0fc0f
Merge bitcoin/bitcoin#28892: refactor: P2P transport without serialize version and type
fa79a881ce refactor: P2P transport without serialize version and type (MarcoFalke)
fa9b5f4fe3 refactor: NetMsg::Make() without nVersion (MarcoFalke)
66669da4a5 Remove unused Make() overload in netmessagemaker.h (MarcoFalke)
fa0ed07941 refactor: VectorWriter without nVersion (MarcoFalke)

Pull request description:

  Now that the serialize framework ignores the serialize version and serialize type, everything related to it can be removed from the code.

  This is the first step, removing dead code from the P2P stack. A different pull will remove it from the wallet and other parts.

ACKs for top commit:
  ajtowns:
    reACK fa79a881ce

Tree-SHA512: 785b413580d980f51f0d4f70ea5e0a99ce14cd12cb065393de2f5254891be94a14f4266110c8b87bd2dbc37467676655bce13bdb295ab139749fcd8b61bd5110
2023-11-28 11:24:09 +00:00
fanquake
dc369af3f5
Merge bitcoin/bitcoin#28936: Change petertodd seeds to petertodd.net
ecb46837e7 Change petertodd seeds to petertodd.net (Peter Todd)

Pull request description:

  I changed my DNS seeds to .net from .org to avoid issues with DNS blacklisting, that falsely thinks my domain name is pointing to IP addresses with malware and similar things. Right now there are CNAME records, so the .org addresses still work. But eventually, if needed, I'll remove those CNAME's.

ACKs for top commit:
  pablomartin4btc:
    tACK ecb46837e7
  fanquake:
    ACK ecb46837e7 - tested that usable addresses are being returned.

Tree-SHA512: 285f7101198ea8e2e20900c17b38aa86db812308c6985d762e5fa8b6f1bc5b0d2d278da841fe2e10cf32e3fe18d4c984bc8cf195bd8d40c86b092b545c62acfa
2023-11-28 10:53:27 +00:00
MarcoFalke
fa825975b5
fuzz: Avoid timeout in process_messages 2023-11-28 09:58:10 +01:00
Sebastian Falbesoner
e67634ef19 fuzz: BIP324: damage ciphertext/aad in full byte range
Currently the damaging of input data for decryption (either ciphertext
or aad) only ever happens in the lower nibble within the byte at the
damage position, as the bit position for the `damage_val` byte was
calculated with `damage_bit & 3` (corresponding to `% 4`) rather than
`damage_bit & 7` (corresponding to the expected `% 8`).
2023-11-28 02:30:09 +01:00
fanquake
794f971607
Merge bitcoin/bitcoin#28933: fuzz: Faster wallet_notifications target
fa15861763 fuzz: Faster wallet_notifications target (MarcoFalke)
fa971c09f2 Export assert from util/check.h (MarcoFalke)

Pull request description:

  Avoid read/write from storage to speed the target up.

ACKs for top commit:
  dergoegge:
    reACK fa15861763
  brunoerg:
    reACK fa15861763

Tree-SHA512: 90aa856ae31db27a55ef0dfa2cb303d98e6c4d530d2937ad8d808c5f4048389b7ed3c78c27df92db8fe29531b5530aecbb06a0e8274dda424149f46cd6c19f98
2023-11-27 17:35:45 +00:00
MarcoFalke
fa15861763
fuzz: Faster wallet_notifications target 2023-11-27 12:06:06 +01:00
Andrew Toth
1c4b9cbe90
bench: add readblock benchmark 2023-11-26 13:24:05 -05:00
fanquake
5f9fd11680
Merge bitcoin/bitcoin#28931: fuzz: Limit fuzz buffer size in script_flags target
faf1fb207f Fix IWYU for the script_flags fuzz target (MarcoFalke)
fa71285b73 fuzz: Limit fuzz buffer size in script_flags target (MarcoFalke)
fa6b87b9ee fuzz: CDataStream -> DataStream in script_flags (MarcoFalke)

Pull request description:

  Most fuzz targets have an upper limit on the buffer size to avoid excessive runtime. Do the same for `script_flags` to avoid timeouts such as https://github.com/bitcoin/bitcoin/issues/28812#issuecomment-1824696971

  Also, fix iwyu. Also, remove legacy `CDataStream`.

ACKs for top commit:
  dergoegge:
    ACK faf1fb207f
  brunoerg:
    utACK faf1fb207f

Tree-SHA512: 9301917b353f7409e448b6fd3635de19330856e0742431db5ef04e62873501b5b4cd6cb78ad81ada2747fa2bdae033115b5951d10489dd5d0d320426c8b96bee
2023-11-26 12:22:50 +00:00
Peter Todd
ecb46837e7
Change petertodd seeds to petertodd.net
I changed my DNS seeds to .net from .org to avoid issues with DNS blacklisting,
that falsely thinks my domain name is pointing to IP addresses with malware and
similar things. Right now there are CNAME records, so the .org addresses still
work. But eventually, if needed, I'll remove those CNAME's.
2023-11-25 13:59:41 +00:00
fanquake
b5a271334c
Merge bitcoin/bitcoin#28922: Use Txid in COutpoint
9e58c5bcd9 Use Txid in COutpoint (dergoegge)

Pull request description:

  This PR changes the type of the hash of a transaction outpoint from `uint256` to `Txid`.

ACKs for top commit:
  Sjors:
    ACK 9e58c5bcd9
  stickies-v:
    ACK 9e58c5bcd9. A sizeable diff, but very straightforward changes. Didn't see anything controversial. Left a few nits, but nothing blocking, only if you have to retouch.
  TheCharlatan:
    ACK 9e58c5bcd9

Tree-SHA512: 58f61ce1c58668f689513e62072a7775419c4d5af8f607669cd8cdc2e7be9645ba14af7f9e2d65da2670da3ec1ce7fc2a744037520caf799aba212fd1ac44b34
2023-11-24 14:41:58 +00:00
MarcoFalke
fa971c09f2
Export assert from util/check.h
This avoids having to include both headers when assert and Assert are
used at the same time.
2023-11-24 13:11:36 +01:00
fanquake
f4073c5395
Merge bitcoin/bitcoin#28578: fuzz: add target for DescriptorScriptPubKeyMan
47e5c9994c fuzz: add target for `DescriptorScriptPubKeyMan` (brunoerg)
641dddf018 fuzz: create ConsumeCoins (brunoerg)
2e1833ca13 fuzz: move `MockedDescriptorConverter` to `fuzz/util` (brunoerg)

Pull request description:

  This PR adds fuzz target for `DescriptorScriptPubKeyMan`. Also, moves `MockedDescriptorConverter` to `fuzz/util/descriptor` to be used here and in `descriptor` target.

ACKs for top commit:
  maflcko:
    lgtm ACK 47e5c9994c 🏓
  dergoegge:
    ACK 47e5c9994c

Tree-SHA512: 519acca6d7b7a3a0bfc031441b02d5980b12bfb97198bd1958a83cd815ceb9eb1499a48a3f0a7fe20e5d06d83b89335d987376fc0a014e2106b0bc0e9838dd02
2023-11-23 17:34:03 +00:00
MarcoFalke
faf1fb207f
Fix IWYU for the script_flags fuzz target
Also, export script_error.h from interpreter.h, because there should
rarely be a case where script_error.h is included without interpreter.h
2023-11-23 17:57:53 +01:00
MarcoFalke
fa71285b73
fuzz: Limit fuzz buffer size in script_flags target 2023-11-23 17:56:52 +01:00
MarcoFalke
fa6b87b9ee
fuzz: CDataStream -> DataStream in script_flags 2023-11-23 17:50:33 +01:00
furszy
75fbf444c1
wallet: birth time update during tx scanning
As the user could have imported a descriptor with
a newer timestamp (by blindly setting 'timestamp=now'),
the wallet needs to update the birth time when it detects
a transaction older than the oldest descriptor timestamp.
2023-11-23 09:55:10 -03:00
furszy
b4306e3c8d
refactor: rename FirstKeyTimeChanged to MaybeUpdateBirthTime
In the following-up commit, the wallet birth time will also
be modified by the transactions scanning process. When a tx
older than all descriptor's timestamp is detected.
2023-11-23 09:55:09 -03:00
MarcoFalke
fa79a881ce
refactor: P2P transport without serialize version and type 2023-11-23 13:43:39 +01:00
fanquake
4374a87879
Merge bitcoin/bitcoin#28895: p2p: do not make automatic outbound connections to addnode peers
5e7cc4144b test: add unit test for CConnman::AddedNodesContain() (Jon Atack)
cc62716920 p2p: do not make automatic outbound connections to addnode peers (Jon Atack)

Pull request description:

  to allocate our limited outbound slots correctly, and to ensure addnode
  connections benefit from their intended protections.

  Our addnode logic usually connects the addnode peers before the automatic
  outbound logic does, but not always, as a connection race can occur.  If an
  addnode peer disconnects us and if it was the only one from its network, there
  can be a race between reconnecting to it with the addnode thread, and it being
  picked as automatic network-specific outbound peer.  Or our internet connection
  or router or the addnode peer could be temporarily offline, and then return
  online during the automatic outbound thread.  Or we could add a new manual peer
  using the addnode RPC at that time.

  The race can be more apparent when our node doesn't know many peers, or with
  networks like cjdns that currently have few bitcoin peers.

  When an addnode peer is connected as an automatic outbound peer and is the only
  connection we have to a network, it can be protected by our new outbound
  eviction logic and persist in the "wrong role".

  Finally, there does not seem to be a reason to make block-relay or short-lived
  feeler connections to addnode peers, as the addnode logic will ensure we connect
  to them if they are up, within the addnode connection limit.

  Fix these issues by checking if the address is an addnode peer in our automatic
  outbound connection logic.

ACKs for top commit:
  mzumsande:
    Tested ACK 5e7cc4144b
  brunoerg:
    utACK 5e7cc4144b
  vasild:
    ACK 5e7cc4144b
  guggero:
    utACK 5e7cc4144b

Tree-SHA512: 2438c3ec92e98aebca2a0da960534e4655a9c6e1192a24a085fc01326d95cdb1b67d8c44e4ee706bc1d8af8564126d446a21b5579dcbec61bdea5fce2f0115ee
2023-11-22 11:47:18 +00:00
fanquake
ca041fc4ab
Merge bitcoin/bitcoin#28904: Drop CAutoFile
4eb2a9ea4b streams: Drop unused CAutoFile (Anthony Towns)
cde9a4b137 refactor: switch from CAutoFile to AutoFile (Anthony Towns)
bbd4646a2e blockstorage: switch from CAutoFile to AutoFile (Anthony Towns)
c72ddf04db streams: Remove unused CAutoFile::GetVersion (Anthony Towns)
e63f643079 streams: Base BufferedFile on AutoFile instead of CAutoFile (Anthony Towns)

Pull request description:

  Continuing the move away from `GetVersion()`, replace uses of `CAutoFile` with `AutoFile`.

ACKs for top commit:
  maflcko:
    re-ACK 4eb2a9ea4b 🖼
  TheCharlatan:
    ACK 4eb2a9ea4b
  stickies-v:
    ACK 4eb2a9ea4b

Tree-SHA512: 1a68c42fdb725ca4bf573e22794fe7809fea764a5f97ecb33435add3c609d40f336038fb22ab1ea72567530efd39678278c9016f92ed04891afdb310631b4e82
2023-11-22 11:24:39 +00:00
fanquake
3dca308bd7
Merge bitcoin/bitcoin#28891: test: fix AddNode unit test failure on OpenBSD
007d6f0e85 test: fix `AddNode` unit test failure on OpenBSD (Sebastian Falbesoner)

Pull request description:

  On OpenBSD 7.4, the following check of the unit test `test_addnode_getaddednodeinfo_and_connection_detection` currently fails:
  ```
  BOOST_CHECK(!connman->AddNode({/*m_added_node=*/"127.1", /*m_use_v2transport=*/true}));
  ```
  The reason for that is that this OS seemingly doesn't support the IPv4 shorthand notation with omitted zero-bytes:

  ```
  $ ping 127.1
  ping: no address associated with name
  ```

  As a simple fix, this PR skips the check for this with a pre-processor #if. On NetBSD and FreeBSD, `127.1` is resolved correctly to localhost and hence the test passes (thanks to vasild for verifying on the latter!).

ACKs for top commit:
  vasild:
    ACK 007d6f0e85

Tree-SHA512: 8ab8393c490e1ecc140e8ff74f6fa4d26d0dd77e6a77a241cd198314b8c5afee7422f95351ca05f4c1742433dab77016a8ccb8d28062f8edd4b703a918a2bbda
2023-11-22 11:18:24 +00:00
ismaelsadeeq
91504cbe0d rpc: SyncWithValidationInterfaceQueue on fee estimation RPC's
This ensures that the most recent fee estimation data is used for the
fee estimation with `estimateSmartfee` and `estimaterawfee` RPC's.
2023-11-22 11:48:21 +01:00
ismaelsadeeq
714523918b tx fees, policy: CBlockPolicyEstimator update from CValidationInterface notifications
`CBlockPolicyEstimator` will implement `CValidationInterface` and
subscribe to its notification to process transactions added and removed
from the mempool.

Re-delegate calculation of `validForFeeEstimation` from validation to fee estimator.

Also clean up the validForFeeEstimation arg thats no longer needed in `CTxMempool`.

Co-authored-by: Matt Corallo <git@bluematt.me>
2023-11-22 11:48:21 +01:00
ismaelsadeeq
dff5ad3b99 CValidationInterface: modify the parameter of TransactionAddedToMempool
Create a new struct `NewMempoolTransactionInfo` that will be used as the new parameter of
`TransactionAddedToMempool` callback.
2023-11-22 11:48:21 +01:00
ismaelsadeeq
91532bd382 tx fees, policy: update CBlockPolicyEstimator::processBlock parameter
Update `processBlock` parameter to reference to a vector of `RemovedMempoolTransactionInfo`.
2023-11-22 11:48:21 +01:00
ismaelsadeeq
bfcd401368 CValidationInterface, mempool: add new callback to CValidationInterface
This commit adds a new callback `MempoolTransactionsRemovedForBlock` which notify
its listeners of the transactions that are removed from the mempool because a new
block is connected, along with the block height the transactions were removed.
The transactions are in `RemovedMempoolTransactionInfo` format.

`CTransactionRef`, base fee, virtual size, and height which the transaction was added
to the mempool are all members of the struct called `RemovedMempoolTransactionInfo`.

A struct `NewMempoolTransactionInfo`, which has fields similar to `RemovedMempoolTransactionInfo`,
will be added in a later commit, create a struct `TransactionInfo` with all similar fields.
They can both have a member with type `TransactionInfo`.
2023-11-22 11:48:21 +01:00
ismaelsadeeq
0889e07987 tx fees, policy: cast with static_cast instead of C-Style cast 2023-11-22 11:48:21 +01:00
ismaelsadeeq
a0e3eb7549 tx fees, policy: bugfix: move removeTx into reason != BLOCK condition
If the removal reason of a transaction is BLOCK, then the `removeTx`
boolean argument should be true.

Before this PR, `CBlockPolicyEstimator` have to complete updating the fee stats
before the mempool clears that's why having removeTx call outside reason!= `BLOCK`
in `addUnchecked` was not a bug.

But in a case where the `CBlockPolicyEstimator` update is asynchronous, the mempool might
clear before we update the `CBlockPolicyEstimator` fee stats.
Transactions that are removed for `BLOCK` reasons will also be incorrectly removed from
`CBlockPolicyEstimator` stats as failures.
2023-11-22 11:48:21 +01:00
Sjors Provoost
f053024273
wallet: batch external signer descriptor import
Co-authored-by: furszy <matiasfurszyfer@protonmail.com>
2023-11-21 23:07:00 -03:00
furszy
1f65241b73
wallet: descriptors setup, batch db operations
Instead of doing one db transaction per descriptor setup,
batch all descriptors' setup writes in a single db txn.

Speeding up the process and preventing the wallet from entering
an inconsistent state if any of the intermediate transactions
fail.
2023-11-21 23:01:42 -03:00
furszy
3eb769f150
wallet: batch legacy spkm TopUp
Instead of performing multiple atomic write
operations per legacy spkm setup call, batch
them all within a single atomic db txn.
2023-11-21 23:01:30 -03:00
furszy
075aa44ceb
wallet: batch descriptor spkm TopUp
Instead of performing multiple atomic write
operations per descriptor setup call, batch
them all within a single atomic db txn.
2023-11-21 23:01:30 -03:00
MarcoFalke
fa63f16018
test: Add uint256 string parse tests 2023-11-21 17:37:57 +01:00
MarcoFalke
facf629ce8
refactor: Remove unused and fragile string interface from arith_uint256 2023-11-21 17:37:25 +01:00
dergoegge
9e58c5bcd9 Use Txid in COutpoint 2023-11-21 13:15:44 +00:00
brunoerg
47e5c9994c fuzz: add target for DescriptorScriptPubKeyMan 2023-11-20 15:57:56 -03:00
brunoerg
641dddf018 fuzz: create ConsumeCoins 2023-11-20 15:57:56 -03:00
brunoerg
2e1833ca13 fuzz: move MockedDescriptorConverter to fuzz/util 2023-11-20 15:57:50 -03:00
Martin Leitner-Ankerl
d5b4c0b69e pool: change memusage_test to use int64_t, add allocation check
If alignment of the PoolAllocator would be insufficient, then the test would fail. This also catches the issue with ARM 32bit,
where int64_t is aligned to 8 bytes but void* is aligned to 4 bytes. The test adds a check to ensure the pool has allocated
a minimum number of chunks
2023-11-20 17:10:34 +01:00
MarcoFalke
fa9b5f4fe3
refactor: NetMsg::Make() without nVersion
The nVersion field is unused, so remove it.

This is also required for future commits.

Also, add PushMessage aliases in PeerManagerImpl to make calling code
less verbose.

Co-Authored-By: Anthony Towns <aj@erisian.com.au>
2023-11-20 14:02:27 +01:00
Martin Leitner-Ankerl
ce881bf9fc pool: make sure PoolAllocator uses the correct alignment
This changes the PoolAllocator to default the alignment to the given type. This makes the code simpler, and most importantly
fixes a bug on ARM 32bit that caused OOM: The class CTxOut has a member CAmount which is an int64_t and on ARM 32bit int64_t
are 8 byte aligned which is larger than the pointer alignment of 4 bytes. So for CCoinsMap to be able to use the pool, we
need to use the alignment of the member instead of just alignof(void*).
2023-11-19 18:43:29 +01:00
TheCharlatan
705e3f1de0
refactor: Make CTxMemPoolEntry only explicitly copyable
This has the goal of prohibiting users from accidentally creating
runtime failures, e.g. by interacting with iterator_to with a copied
entry.

CTxMemPoolEntry is already implicitly not move-constructable. So be
explicit about this and use a std::list to collect the values in the
policy_estimator fuzz test instead of a std::vector.

Co-authored-by: Anthony Towns <aj@erisian.com.au>
2023-11-17 23:02:02 +01:00
Anthony Towns
4eb2a9ea4b streams: Drop unused CAutoFile 2023-11-18 03:01:41 +10:00
Anthony Towns
cde9a4b137 refactor: switch from CAutoFile to AutoFile 2023-11-18 03:01:41 +10:00
Anthony Towns
bbd4646a2e blockstorage: switch from CAutoFile to AutoFile
Also bump includes per suggestions from iwyu.
2023-11-18 03:01:03 +10:00
Anthony Towns
c72ddf04db streams: Remove unused CAutoFile::GetVersion 2023-11-18 00:15:25 +10:00
Anthony Towns
e63f643079 streams: Base BufferedFile on AutoFile instead of CAutoFile 2023-11-18 00:15:22 +10:00
MarcoFalke
66669da4a5
Remove unused Make() overload in netmessagemaker.h 2023-11-17 14:38:40 +01:00
MarcoFalke
fa0ed07941
refactor: VectorWriter without nVersion
The field is unused, so remove it.

This is also required for future commits.
2023-11-17 14:38:26 +01:00
fanquake
950af7c876
Merge bitcoin/bitcoin#28878: Remove version field from GetSerializeSize
83986f464c Include version.h in fewer places (Anthony Towns)
c7b61fd61b Convert some CDataStream to DataStream (Anthony Towns)
1410d300df serialize: Drop useless version param from GetSerializeSize() (Anthony Towns)
bf574a7501 serialize: drop GetSerializeSizeMany (Anthony Towns)
efa9eb6d7c serialize: Drop nVersion from [C]SizeComputer (Anthony Towns)

Pull request description:

  Drops the version field from `GetSerializeSize()`, simplifying the code in various places. Also drop `GetSerializeSizeMany()` (as just removing the version parameter could result in silent bugs) and remove unnecessary instances of `#include <version.h>`.

ACKs for top commit:
  maflcko:
    ACK 83986f464c 📒
  theuni:
    ACK 83986f464c.

Tree-SHA512: 36617b6dfbb1b4b0afbf673e905525fc6d623d3f568d3f86e3b9d4f69820db97d099e83a88007bfff881f731ddca6755ebf1549e8d8a7762437dfadbf434c62e
2023-11-17 10:56:41 +00:00
fanquake
afd3e99856
Merge bitcoin/bitcoin#28873: fuzz: AutoFile with XOR
faa25718b3 fuzz: AutoFile with XOR (MarcoFalke)
fab5cb9066 fuzz: Reduce LIMITED_WHILE limit for file fuzzing (MarcoFalke)
fa5388fad3 fuzz: Remove FuzzedAutoFileProvider (MarcoFalke)

Pull request description:

  This should help to get fuzz coverage for https://maflcko.github.io/b-c-cov/fuzz.coverage/src/streams.cpp.gcov.html

  Also, remove unused code and fix a timeout bug.

ACKs for top commit:
  dergoegge:
    ACK faa25718b3

Tree-SHA512: 56f1e6fd5cb2b66ffd9a7d9c09c9b8e396be3e7485feb03b35b6bd3c48e624fdaed50b472e4ffec21f09efb5e949d7ee32a13851849c9140b6b4cf25917dd7ac
2023-11-17 10:12:35 +00:00
Jon Atack
5e7cc4144b test: add unit test for CConnman::AddedNodesContain() 2023-11-16 10:38:25 -06:00
Jon Atack
cc62716920 p2p: do not make automatic outbound connections to addnode peers
to allocate our limited outbound slots correctly, and to ensure addnode
connections benefit from their intended protections.

Our addnode logic usually connects the addnode peers before the automatic
outbound logic does, but not always, as a connection race can occur.  If an
addnode peer disconnects us and if it was the only one from its network, there
can be a race between reconnecting to it with the addnode thread, and it being
picked as automatic network-specific outbound peer.  Or our internet connection
or router, or the addnode peer, could be temporarily offline, and then return
online during the automatic outbound thread.  Or we could add a new manual peer
using the addnode RPC at that time.

The race can be more apparent when our node doesn't know many peers, or with
networks like cjdns that currently have few bitcoin peers.

When an addnode peer is connected as an automatic outbound peer and is the only
connection we have to a network, it can be protected by our new outbound
eviction logic and persist in the "wrong role".

Examples on mainnet using logging added in the same pull request:

2023-08-12T14:51:05.681743Z [opencon] [net.cpp:1949] [ThreadOpenConnections]
[net:debug] Not making automatic network-specific outbound-full-relay connection
to i2p peer selected for manual (addnode) connection: [geh...odq.b32.i2p]:0

2023-08-13T03:59:28.050853Z [opencon] [net.cpp:1949] [ThreadOpenConnections]
[net:debug] Not making automatic block-relay-only connection to onion peer
selected for manual (addnode) connection: kpg...aid.onion:8333

2023-08-13T16:21:26.979052Z [opencon] [net.cpp:1949] [ThreadOpenConnections]
[net:debug] Not making automatic network-specific outbound-full-relay connection
to cjdns peer selected for manual (addnode) connection: [fcc...8ce]:8333

2023-08-14T20:43:53.401271Z [opencon] [net.cpp:1949] [ThreadOpenConnections]
[net:debug] Not making automatic network-specific outbound-full-relay connection
to cjdns peer selected for manual (addnode) connection: [fc7...59e]:8333

2023-08-15T00:10:01.894147Z [opencon] [net.cpp:1949] [ThreadOpenConnections]
[net:debug] Not making automatic feeler connection to i2p peer selected for
manual (addnode) connection: geh...odq.b32.i2p:8333

Finally, there does not seem to be a reason to make block-relay or short-lived
feeler connections to addnode peers, as the addnode logic will ensure we connect
to them if they are up, within the addnode connection limit.

Fix these issues by checking if the address is an addnode peer in our automatic
outbound connection logic.
2023-11-16 10:38:25 -06:00
Sebastian Falbesoner
007d6f0e85 test: fix AddNode unit test failure on OpenBSD 2023-11-16 16:00:14 +01:00
furszy
bb4554c81e
bench: add benchmark for wallet creation procedure 2023-11-16 11:27:17 -03:00
fanquake
22025d06e5
Merge bitcoin/bitcoin#28605: Fix typos
43de4d3630 doc: fix typos (Sjors Provoost)

Pull request description:

  This PR fixes typos found by lint-spelling.py using codespell 2.2.6.

  Our CI linter job uses codespell 2.2.5 and found fewer typos that I did locally. In any case it's happy now.

ACKs for top commit:
  pablomartin4btc:
    re ACK 43de4d3630

Tree-SHA512: c032fe86cb49c924a468385653b31f309a9db68c478d70335bba3e65a1ff3826abe80284fe00a090ab5a509e1edbf17e476f6922fb15d055e50f1103dad2ccb0
2023-11-16 10:35:49 +00:00
fanquake
6b7bf907f5
Merge bitcoin/bitcoin#28825: fuzz: Minor improvements to tx_package_eval target
6a917918b7 fuzz: allow fake and duplicate inputs in tx_package_eval target (Greg Sanders)
a0626ccdad fuzz: allow reaching MempoolAcceptResult::ResultType::DIFFERENT_WITNESS in tx_package_eval target (Greg Sanders)

Pull request description:

  Exercises `DIFFERENT_WITNESS` by using "blank" WSH() and allowing witness to determine wtxid, and attempts to make invalid/duplicate inputs.

ACKs for top commit:
  dergoegge:
    Coverage looks good to me ACK 6a917918b7

Tree-SHA512: db894f5f5b81c6b454874baf11f296462832285f41ccb09f23c0db92b9abc98f8ecacd72fc8f60dc92cb7947f543a2e55bed2fd210b0e8ca7c7d5389d90b14af
2023-11-16 10:16:02 +00:00
fanquake
eb2ab3de1a
Merge bitcoin/bitcoin#28877: bench: Update nanobench to 4.3.11
fe434a4695 bench: Update nanobench to 4.3.11 (TheCharlatan)

Pull request description:

  The newest version fixes the false positive `* Turbo is enabled, CPU frequency will fluctuate` warning on AMD CPUs. The file was directly taken from the release page: https://github.com/martinus/nanobench/releases/tag/v4.3.11.

  Other changes from the release notes:

  * Check for failures in parseFile(), perf events tweaks by tommi-cujo in https://github.com/martinus/nanobench/pull/84
  * Workaround missing noexcept for std::string move assignment by tommi-cujo in https://github.com/martinus/nanobench/pull/87
  * removed the link by martinus in https://github.com/martinus/nanobench/pull/89
  * Lots of minor cleanups by martinus in https://github.com/martinus/nanobench/pull/85
  * Add linter for version & clang-format. Updated version by martinus in https://github.com/martinus/nanobench/pull/90

ACKs for top commit:
  fanquake:
    ACK fe434a4695 - have not tested.

Tree-SHA512: a8f15e1db1d993673e4b295a3bab22e67ee3c9f3c0bcbef28974fe9ff37dbb741967a526088d5b148c8d25c9d57cd3b844238100c17b23038638787461805678
2023-11-16 09:49:05 +00:00
Anthony Towns
83986f464c Include version.h in fewer places 2023-11-16 11:36:22 +10:00
Anthony Towns
c7b61fd61b Convert some CDataStream to DataStream 2023-11-16 11:14:13 +10:00
Anthony Towns
1410d300df serialize: Drop useless version param from GetSerializeSize() 2023-11-16 11:14:13 +10:00
Anthony Towns
bf574a7501 serialize: drop GetSerializeSizeMany 2023-11-16 11:14:10 +10:00
Anthony Towns
efa9eb6d7c serialize: Drop nVersion from [C]SizeComputer
Protocol version is no longer needed to work out the serialized size
of objects so drop that information from CSizeComputer and rename the
class to SizeComputer.
2023-11-16 10:20:30 +10:00
fanquake
108462139b
Merge bitcoin/bitcoin#28438: Use serialization parameters for CTransaction
a0c254c13a Drop CHashWriter (Anthony Towns)
c94f7e5b1c Drop OverrideStream (Anthony Towns)
6e9e4e6130 Use ParamsWrapper for witness serialization (Anthony Towns)

Pull request description:

  Choose whether witness is included in transaction serialization via serialization parameter rather than the stream version. See #25284 and #19477 for previous context.

ACKs for top commit:
  maflcko:
    re-ACK a0c254c13a 🐜
  theuni:
    ACK a0c254c13a

Tree-SHA512: 8fd5cadfd84c5128e36c34a51fb94fdccd956280e7f65b7d73c512d6a9cdb53cdd3649de99ffab5322bd34be26cb95ab4eb05932b3b9de9c11d85743f50dcb13
2023-11-15 15:16:19 +00:00
TheCharlatan
fe434a4695
bench: Update nanobench to 4.3.11 2023-11-14 20:22:12 +01:00
MarcoFalke
faa25718b3
fuzz: AutoFile with XOR 2023-11-14 17:41:54 +01:00
MarcoFalke
fab5cb9066
fuzz: Reduce LIMITED_WHILE limit for file fuzzing
A higher limit is not needed, and only leads to timeouts, see for
example the buffered_file one in
https://github.com/bitcoin/bitcoin/issues/28812#issue-1981386486
2023-11-14 17:41:49 +01:00
MarcoFalke
fa5388fad3
fuzz: Remove FuzzedAutoFileProvider
The code is clearer without it.

This is also needed for a future commit.
2023-11-14 17:41:26 +01:00
fanquake
830583eb9d
Merge bitcoin/bitcoin#28858: doc: rewrite explanation for -par=
d799ea26ed doc: rewrite explanation for -par= (fanquake)

Pull request description:

  The negative bound for script threads comes from the machine which generates the man pages, so may only be correct for that machine. Any other placeholder value will also be wrong for some machines. Fix this be removing the value. This also fixes help2man incorrectly bolding the value, as if it were a paramater.

  Closes #28850.

ACKs for top commit:
  maflcko:
    lgtm ACK d799ea26ed
  theStack:
    ACK d799ea26ed

Tree-SHA512: 2eec0086faf4cc64bbf46b22949662f84d8546d2322c3d507fc44a4e1f64d228a2901af4fa4535c0771e3e14600be8308fc5dbd407b66ae6ae4f8878d8372c0a
2023-11-14 15:45:04 +00:00
fanquake
8992a34ee4
Merge bitcoin/bitcoin#28857: test, refactor: Magic bytes array followup
1e5b86171e test: Add test for array serialization (TheCharlatan)
d49d198840 refactor: Initialize magic bytes in constructor initializer (TheCharlatan)

Pull request description:

  This is a followup-PR for #28423

  * Initialize magic bytes in constructor
  * Add a small unit test for serializing arrays.

ACKs for top commit:
  sipa:
    utACK 1e5b86171e
  maflcko:
    lgtm ACK 1e5b86171e

Tree-SHA512: 0f58d2332dc501ca9fd419f40ed4f977c83dce0169e9a0eee1ffc9f8daa2d2ef7e7df18205ba076f55d90ae6c4a20d2b51ab303150d38470a962bcc58a66f6e7
2023-11-14 15:44:12 +00:00
Anthony Towns
a0c254c13a Drop CHashWriter 2023-11-14 08:45:32 +10:00
Anthony Towns
c94f7e5b1c Drop OverrideStream 2023-11-14 08:45:32 +10:00
Anthony Towns
6e9e4e6130 Use ParamsWrapper for witness serialization 2023-11-14 08:45:30 +10:00
Andrew Chow
d232e36abd
Merge bitcoin/bitcoin#28207: mempool: Persist with XOR
fa6b053b5c mempool: persist with XOR (MarcoFalke)

Pull request description:

  Currently the `mempool.dat` file stores data received from remote peers as-is. This may be problematic when a program other than Bitcoin Core tries to interpret them by accident. For example, an anti-virus program or other program may scan the file and move it into quarantine, or delete it, or corrupt it.

  While the local wallet is expected to re-submit any pending transactions, unrelated transactions may be missing from the mempool after a restart. This may cause fee estimates to be off, or may cause block relay to be slower.

  Fix this, similar to https://github.com/bitcoin/bitcoin/pull/6650, by rolling a random XOR pattern over the dat file when writing or reading it.

  Obviously this can only protect against programs that accidentally and unintentionally are trying to mess with the dat file. Any program that intentionally wants to mess with the dat file can still trivially do so.

ACKs for top commit:
  achow101:
    re-ACK fa6b053b5c
  glozow:
    reACK fa6b053b5c
  ismaelsadeeq:
    ACK fa6b053b5c

Tree-SHA512: ded2ce3d81bc944b828263534e3178a1e45a914fe8e024f4a14c6561a73e301820944ecc75dd704b3d4221a7a3a5c0597ccab79546250c1197609ee981fe324e
2023-11-13 11:28:15 -05:00
fanquake
6342348072
Merge bitcoin/bitcoin#28076: util: Replace std::filesystem with util/fs.h
bbbbdb0cd5 ci: Add filesystem lint check (MarcoFalke)
fada2f9110 refactor: Replace <filesystem> with <util/fs.h> (MarcoFalke)

Pull request description:

  Using `std::filesystem` is problematic:

  * There is a `fs` namespace wrapper for it. So having two ways to achieve the same is confusing.
  * Not using the `fs` wrapper is dangerous and buggy, because it disables known bugs by deleting problematic functions.

  Fix all issues by removing use of it and adding a linter to avoid using it again in the future.

ACKs for top commit:
  TheCharlatan:
    ACK  bbbbdb0cd5
  fanquake:
    ACK bbbbdb0cd5 🦀

Tree-SHA512: 0e2d49742b08eb2635e6fce41485277cb9c40fe20b81017c391d3472a43787db1278a236825714ca1e41c9d2f59913865cfb0c649e3c8ab1fb598c849f80c660
2023-11-13 14:10:54 +00:00
TheCharlatan
1e5b86171e
test: Add test for array serialization 2023-11-13 14:18:09 +01:00
TheCharlatan
d49d198840
refactor: Initialize magic bytes in constructor initializer
Also remove an assert that is already enforced by the compiler checking
that the length of the std::array matches.
2023-11-13 14:17:59 +01:00
fanquake
29c2c90362
Merge bitcoin/bitcoin#28721: multiprocess compatibility updates
3b70f7b615 doc: fix broken doc/design/multiprocess.md links after #24352 (Ryan Ofsky)
6d43aad742 span: Make Span template deduction guides work in SFINAE context (Ryan Ofsky)
8062c3bdb9 util: Add ArgsManager SetConfigFilePath method (Ryan Ofsky)
441d00c60f interfaces: Rename CalculateBumpFees methods to be compatible with capn'proto (Ryan Ofsky)
156f49d682 interfaces: Change getUnspentOutput return type to avoid multiprocess segfault (Ryan Ofsky)
4978754c00 interfaces: Add schedulerMockForward method so mockscheduler RPC can work across processes (Ryan Ofsky)
924327eaf3 interfaces: Fix const virtual method that breaks multiprocess support (Ryan Ofsky)
82a379eca8 streams: Add SpanReader ignore method (Russell Yanofsky)

Pull request description:

  This is a collection of small changes to interfaces and code which were needed as part of multiprocess PR #10102, but have been moved here to make that PR smaller.

  All of these changes are refactoring changes which do not affect behavior of current code

  ---

  This PR is part of the [process separation project](https://github.com/bitcoin/bitcoin/issues/28722).

ACKs for top commit:
  achow101:
    ACK 3b70f7b615
  naumenkogs:
    ACK 3b70f7b615
  maflcko:
    re-ACK 3b70f7b615  🎆

Tree-SHA512: 2368772b887056ad8a9f84c299cfde76ba45943770e3b5353130580900afa9611302195b899ced7b6e303b11f053ff204cae7c28ff4e12c55562fcc81119ba4c
2023-11-13 12:32:55 +00:00
fanquake
d799ea26ed
doc: rewrite explanation for -par=
The negative bound for script threads comes from the machine which
generates the man pages, so may only be correct for that machine. Any
other placeholder value will also be wrong for some machines. Fix this
be removing the value. This also fixes help2man incorrectly bolding the
value, as if it were a paramater.

Closes #28850.
2023-11-13 11:37:55 +00:00
fanquake
e862bceb17
Merge bitcoin/bitcoin#27935: fuzz: call lookup functions before calling Ban
fca0a8938e ci: remove "--exclude banman" for fuzzing in mac (brunoerg)
f9b286353f fuzz: call lookup functions before calling `Ban` (brunoerg)

Pull request description:

  Fixes #27924

  To not have any discrepancy, it's required to call lookup functions before calling `Ban`. If we don't do it, the assertion `assert(banmap == banmap_read);` may fail because `BanMapFromJson` will call `LookupSubNet` and cause the discrepancy between the banned and the loaded one. It happens especially in MacOS (#27924).

  Also, calling lookup functions before banning is what RPC `setban` does.

ACKs for top commit:
  maflcko:
    lgtm ACK fca0a8938e
  dergoegge:
    ACK fca0a8938e

Tree-SHA512: a3d635088a556df4507e65542157f10b41d4f87dce42927b58c3b812f262f4544b6b57f3384eef1097ffdd7c32b8dd1556aae201254960cbfbf48d45551200f7
2023-11-13 10:57:01 +00:00
fanquake
dd5f5713bc
Merge bitcoin/bitcoin#28391: refactor: Simplify CTxMempool/BlockAssembler fields, remove some external mapTx access
4dd94ca18f [refactor] remove access to mapTx in validation_block_tests (TheCharlatan)
d0cd2e804e [refactor] rewrite BlockAssembler inBlock and failedTx as sets of txids (glozow)
55b0939cab scripted-diff: rename vTxHashes to txns_randomized (TheCharlatan)
a03aef9cec [refactor] rewrite vTxHashes as a vector of CTransactionRef (glozow)
938643c3b2 [refactor] remove access to mapTx in validation.cpp (glozow)
333367a940 [txmempool] make CTxMemPoolEntry::lockPoints mutable (glozow)
1bf4855016 [refactor] use CheckPackageLimits for checkChainLimits (glozow)
dbc5bdbf59 [refactor] remove access to mapTx.find in mempool_tests.cpp (glozow)
f80909e7a3 [refactor] remove access to mapTx in blockencodings_tests.cpp (glozow)
8892d6b744 [refactor] remove access to mapTx from rpc/mempool.cpp (glozow)
fad61aa561 [refactor] get wtxid from entry instead of vTxHashes (glozow)
9cd8cafb77 [refactor] use exists() instead of mapTx.find() (glozow)
14804699e5 [refactor] remove access to mapTx from policy/rbf.cpp (glozow)
1c6a73abbd [refactor] Add helper for retrieving mempool entry (TheCharlatan)
453b4813eb [refactor] Add helper for iterating through mempool entries (stickies-v)

Pull request description:

  Motivation
  * It seems preferable to use stdlib data structures instead of boost if they can achieve close to the same thing.
  * Code external to mempool should ideally use its public helper methods instead of accessing `mapTx` or its iterators directly.
  * Reduce the number of complex boost multi index type interactions
  * Also see #28335 for further context/motivation. This PR together with #28385 simplifies that one.

  Overview of things done in this PR:
  * Make `vTxHashes` a vector of transaction references instead of a pair of transaction hash and iterator. The trade off here is that the data is retrieved on the fly with `GetEntry` instead of being cached in `vTxHashes`.
  * Introduce `GetEntry` helper method to replace the more involved `GetIter` where applicable
  * Replace `mapTx` access with `CTxMemPool` helper methods
  * Simplify `checkChainLimits` call in `node/interfaces.cpp`
  * Make `CTxMemPoolEntry`s `lockPoints`mutable such that they can be changed with a const iterator directly instead of going through `mapTx`
  * Make `BlockAssembler`'s `inBlock` and `failedTx` sets of transaction hashes.

ACKs for top commit:
  glozow:
    reACK 4dd94ca
  maflcko:
    re-ACK 4dd94ca18f 👝
  stickies-v:
    re-ACK 4dd94ca18f

Tree-SHA512: c4d043f2186e4fde337591883fac66cade3058173987b49502bd65cecf69207a3df1077f6626809652ab63230013167b7f39a2b39f1c5166959e5495df57065f
2023-11-13 10:51:41 +00:00
TheCharlatan
4dd94ca18f
[refactor] remove access to mapTx in validation_block_tests
Use the helper function instead of reaching into the mapTx member
object.
2023-11-10 16:44:47 +01:00
glozow
d0cd2e804e
[refactor] rewrite BlockAssembler inBlock and failedTx as sets of txids 2023-11-10 16:44:45 +01:00
TheCharlatan
55b0939cab
scripted-diff: rename vTxHashes to txns_randomized
-BEGIN VERIFY SCRIPT-
git grep -l "vTxHashesIdx" src | xargs sed -i "s/vTxHashesIdx/idx_randomized/g"
git grep -l "vTxHashes" src | xargs sed -i "s/vTxHashes/txns_randomized/g"
-END VERIFY SCRIPT-
2023-11-10 16:44:44 +01:00
glozow
a03aef9cec
[refactor] rewrite vTxHashes as a vector of CTransactionRef
vTxHashes exposes a complex mapTx iterator type that its external users
don't need. Directly populate it with CTransactionRef instead.
2023-11-10 16:44:42 +01:00
glozow
938643c3b2
[refactor] remove access to mapTx in validation.cpp 2023-11-10 16:44:40 +01:00
glozow
333367a940
[txmempool] make CTxMemPoolEntry::lockPoints mutable
Allows calling UpdateLockPoints() with a (const) txiter. Note that this
was already possible for caller using mapTx.modify(txiter). The point
here is to not be accessing mapTx when doing so.
2023-11-10 16:44:39 +01:00
glozow
1bf4855016
[refactor] use CheckPackageLimits for checkChainLimits
The behavior is the same as CalculateMemPoolAncestors. The only
difference is the string returned, and the string is discarded anyway
since checkChainLimits only cares about pass/fail.
2023-11-10 16:44:37 +01:00
glozow
dbc5bdbf59
[refactor] remove access to mapTx.find in mempool_tests.cpp 2023-11-10 16:44:35 +01:00
glozow
f80909e7a3
[refactor] remove access to mapTx in blockencodings_tests.cpp 2023-11-10 16:44:33 +01:00
glozow
8892d6b744
[refactor] remove access to mapTx from rpc/mempool.cpp 2023-11-10 16:44:32 +01:00
glozow
fad61aa561
[refactor] get wtxid from entry instead of vTxHashes 2023-11-10 16:44:30 +01:00
glozow
9cd8cafb77
[refactor] use exists() instead of mapTx.find() 2023-11-10 16:44:29 +01:00
glozow
14804699e5
[refactor] remove access to mapTx from policy/rbf.cpp 2023-11-10 16:44:27 +01:00
TheCharlatan
1c6a73abbd
[refactor] Add helper for retrieving mempool entry
In places where the iterator is only needed for accessing the actual
entry, it should not be required to first retrieve the iterator.
2023-11-10 16:44:25 +01:00
stickies-v
453b4813eb
[refactor] Add helper for iterating through mempool entries
Instead of reaching into the mapTx data structure, use a helper method
that provides the required vector of CTxMemPoolEntry pointers.
2023-11-10 16:44:20 +01:00
MarcoFalke
fa6b053b5c
mempool: persist with XOR 2023-11-09 19:44:50 +01:00
Greg Sanders
6a917918b7 fuzz: allow fake and duplicate inputs in tx_package_eval target 2023-11-09 09:07:03 -05:00
Greg Sanders
a0626ccdad fuzz: allow reaching MempoolAcceptResult::ResultType::DIFFERENT_WITNESS in tx_package_eval target 2023-11-09 09:07:03 -05:00
brunoerg
f9b286353f fuzz: call lookup functions before calling Ban
Also, compare banmaps only if there are no invalid
entries.
2023-11-09 10:11:51 -03:00
glozow
d60ebea597
Merge bitcoin/bitcoin#28808: refactor: Miniminer package linearization followups
b4b01d3fb4 [refactor] updating miniminer comments to be more accurate (kevkevin)
83933eff00 [refactor] Miniminer var cached_descendants to descendants (kevkevin)
43423fd834 [refactor] Change MiniMinerMempoolEntry order (kevkevin)

Pull request description:

  ### Motivation
  In https://github.com/bitcoin/bitcoin/pull/28762 there were some post merge comments which are being addressed in this PR with the following commits

  ### [8d4c46f](8d4c46f54d) Reorganizing `MiniMinerMempoolEntry` to match the order we have elsewhere
  * https://github.com/bitcoin/bitcoin/pull/28762#discussion_r1381775670

  ### [7505ec2](7505ec2054) Renaming `cached_descendants` to `descendants` for simpler variable naming
  * https://github.com/bitcoin/bitcoin/pull/28762#discussion_r1381819567

  ### [b21f2f2](b21f2f2f55) Code comment modifications to be more accurate to what is actually happening
  * https://github.com/bitcoin/bitcoin/pull/28762#discussion_r1381902909 and
  * https://github.com/bitcoin/bitcoin/pull/28762#discussion_r1382002278 and
  * https://github.com/bitcoin/bitcoin/pull/28762#discussion_r1383041819

ACKs for top commit:
  murchandamus:
    reACK b4b01d3fb4
  theStack:
    LGTM ACK b4b01d3fb4

Tree-SHA512: 54f044a578fb203d8a3c1aa0bcd1fc4bcdff0bc9b024351925a4caf0ccece7c7736b0694ad1168c3cbb447bdb58a91f4cac365f46114da29a889fbc8ea595b82
2023-11-09 09:30:58 +00:00
kevkevin
b4b01d3fb4
[refactor] updating miniminer comments to be more accurate 2023-11-08 14:45:18 -06:00
Andrew Chow
19d1ba1b41
Merge bitcoin/bitcoin#28787: init: completely remove -zapwallettxes (remaining hidden option)
5039c346ca init: completely remove `-zapwallettxes` (remaining hidden option) (Sebastian Falbesoner)

Pull request description:

  The `-zapwallettxes` functionality has been removed in v0.21.0 (see commit 3340dbadd3 / PR #19671), with the parameter being kept as hidden option, to inform users via an exit error that `abandontransaction` should be used instead.

  As any guides that still suggest to use `-zapwallettxes` would refer to a Bitcoin Core version that is EOL since many years (i.e. <= v0.20.x), it is highly unlikely that the error caused by the option is still relevant for any user, hence it seems fine to remove it now.

ACKs for top commit:
  achow101:
    ACK 5039c346ca
  BrandonOdiwuor:
    ACK 5039c346ca
  fanquake:
    ACK 5039c346ca

Tree-SHA512: e3ccc6918e0f8fa68dbd1a7ec4999cc2a44e28038711919fcddaf0727648c73a9ba0fb77674317147592a113fad20755d4e727f48176bc17b048fbdebad2d6c9
2023-11-08 10:53:42 -05:00
fanquake
f1f3f2d9cc
Merge bitcoin/bitcoin#28815: fuzz: Avoid timeout and bloat in fuzz targets
fabb5046a7 fuzz: Avoid timeout and bloat in fuzz targets (MarcoFalke)

Pull request description:

  If the fuzz input contains invalid data *in a loop*, abort early. This will teach the fuzz engine to look for useful data and avoids bloating the fuzz input folder with useless (repeated) data.

ACKs for top commit:
  dergoegge:
    utACK fabb5046a7
  brunoerg:
    crACK fabb5046a7

Tree-SHA512: 26da100d7558ae6fdd5292fb146d8858b2af8f78c546ca2509b9d27b33a33e9462ecb6035de142f9f36dd5de32f8cbad099d6c7a697902d23e1bb621cd27dc88
2023-11-08 14:19:35 +00:00
glozow
9ad19fc7c7
Merge bitcoin/bitcoin#28155: net: improves addnode / m_added_nodes logic
0420f99f42 Create net_peer_connection unit tests (Jon Atack)
4b834f6499 Allow unit tests to access additional CConnman members (Jon Atack)
34b9ef443b net/rpc: Makes CConnman::GetAddedNodeInfo able to return only non-connected address on request (Sergi Delgado Segura)
94e8882d82 rpc: Prevents adding the same ip more than once when formatted differently (Sergi Delgado Segura)
2574b7e177 net/rpc: Check all resolved addresses in ConnectNode rather than just one (Sergi Delgado Segura)

Pull request description:

  ## Rationale

  Currently, `addnode` has a couple of corner cases that allow it to either connect to the same peer more than once, hence wasting outbound connection slots, or add redundant information to `m_added_nodes`, hence making Bitcoin iterate through useless data on a regular basis.

  ### Connecting to the same node more than once

  In general, connecting to the same node more than once is something we should try to prevent. Currently, this is possible via `addnode` in two different ways:

  1. Calling `addnode` more than once in a short time period, using two equivalent but distinct addresses
  2. Calling `addnode add` using an IP, and `addnode onetry` after with an address that resolved to the same IP

  For the former, the issue boils down to `CConnman::ThreadOpenAddedConnections` calling `CConnman::GetAddedNodeInfo` once, and iterating over the result to open connections (`CConman::OpenNetworkConnection`) on the same loop for all addresses.`CConnman::ConnectNode` only checks a single address, at random, when resolving from a hostname, and uses it to check whether we are already connected to it.

  An example to test this would be calling:

  ```
  bitcoin-cli addnode "127.0.0.1:port" add
  bitcoin-cli addnode "localhost:port" add
  ```

  And check how it allows us to perform both connections some times, and some times it fails.

  The latter boils down to the same issue, but takes advantage of `onetry` bypassing the `CConnman::ThreadOpenAddedConnections` logic and calling `CConnman::OpenNetworkConnection` straightaway. A way to test this would be:

  ```
  bitcoin-cli addnode "127.0.0.1:port" add
  bitcoin-cli addnode "localhost:port" onetry
  ```

  ### Adding the same peer with two different, yet equivalent, addresses

  The current implementation of `addnode` is pretty naive when checking what data is added to `m_added_nodes`. Given the collection stores strings, the checks at `CConnman::AddNode()` basically check wether the exact provided string is already in the collection. If so, the data is rejected, otherwise, it is accepted. However, ips can be formatted in several ways that would bypass those checks.

  Two examples would be `127.0.0.1` being equal to `127.1` and `[::1]` being equal to `[0:0:0:0:0:0:0:1]`. Adding any pair of these will be allowed by the rpc command, and both will be reported as connected by `getaddednodeinfo`, given they map to the same `CService`.

  This is less severe than the previous issue, since even tough both nodes are reported as connected by `getaddednodeinfo`, there is only a single connection to them (as properly reported by `getpeerinfo`). However, this adds redundant data to `m_added_nodes`, which is undesirable.

  ### Parametrize `CConnman::GetAddedNodeInfo`
  Finally, this PR also parametrizes `CConnman::GetAddedNodeInfo` so it returns either all added nodes info, or only info about the nodes we are **not** connected to. This method is used both for `rpc`, in `getaddednodeinfo`, in which we are reporting all data to the user, so the former applies, and to check what nodes we are not connected to, in `CConnman::ThreadOpenAddedConnections`, in which we are currently returning more data than needed and then actively filtering using `CService.fConnected()`

ACKs for top commit:
  jonatack:
    re-ACK 0420f99f42
  kashifs:
    > > tACK [0420f9](0420f99f42)
  sr-gi:
    > > > tACK [0420f9](0420f99f42)
  mzumsande:
    Tested ACK 0420f99f42

Tree-SHA512: a3a10e748c12d98d439dfb193c75bc8d9486717cda5f41560f5c0ace1baef523d001d5e7eabac9fa466a9159a30bb925cc1327c2d6c4efb89dcaf54e176d1752
2023-11-08 11:31:36 +00:00
fanquake
d690f89b57
Merge bitcoin/bitcoin#28785: validation: return more helpful results for reconsiderable fee failures and skipped transactions
1147e00e59 [validation] change package-fee-too-low, return wtxid(s) and effective feerate (glozow)
10dd9f2441 [test] use CheckPackageMempoolAcceptResult in previous tests (glozow)
3979f1afcb [validation] add TxValidationResult::TX_RECONSIDERABLE, TX_UNKNOWN (glozow)
5c786a026a [refactor] use Wtxid for m_wtxids_fee_calculations (glozow)

Pull request description:

  Split off from #26711 (suggested in https://github.com/bitcoin/bitcoin/pull/26711#issuecomment-1786392253). This is part of #27463.

  - Add 2 new TxValidationResults
    - `TX_RECONSIDERABLE` helps us encode transactions who have failed fee checks that can be bypassed using package validation. This is distinguished from `TX_MEMPOOL_POLICY` so that we re-validate a transaction if and only if it is eligible for package CPFP. In the future, we will have a separate cache for reconsiderable rejects so these transactions don't go in `m_recent_rejects`.
    - `TX_UNKNOWN` helps us communicate that we aborted package validation and didn't finish looking at this transaction: it's not valid but it's also not invalid (i.e. don't cache it as a rejected tx)
  - Return effective feerate and the wtxids of transactions used to calculate that effective feerate when the error is `TX_SINGLE_FAILURE`. Previously, we would only provide this information if the transaction passed. Now that we have package validation, it's much more helpful to the caller to know how the failing feerate was calculated. This can also be used to improve our submitpackage RPC result (which is currently a bit unhelpful when things fail).
  - Use the newly added `CheckPackageMempoolAcceptResult` for existing package validation tests. This increases test coverage and helps test the changes made in this PR.

ACKs for top commit:
  instagibbs:
    reACK 1147e00e59
  achow101:
    ACK 1147e00e59
  murchandamus:
    reACK 1147e00e59
  ismaelsadeeq:
    ACK 1147e00e59

Tree-SHA512: ac1cd73c2b487a1b99d329875d39d8107c91345a5b0b241d54a6a4de67faf11be69a2721cc732c503024a9cca381dac33d61e187957279e3c82653bea118ba91
2023-11-08 10:17:05 +00:00
MarcoFalke
fabb5046a7
fuzz: Avoid timeout and bloat in fuzz targets
Also, fix iwyu
2023-11-08 09:51:54 +01:00
Andrew Chow
82ea4e787c
Merge bitcoin/bitcoin#28464: net: improve max-connection limits code
df69b22f2e doc: improve documentation around connection limit maximums (Amiti Uttarwar)
adc171edf4 scripted-diff: Rename connection limit variables (Amiti Uttarwar)
e9fd9c0225 net: add m_max_inbound to connman (Amiti Uttarwar)
c25e0e0555 net, refactor: move calculations for connection type limits into connman (Amiti Uttarwar)

Pull request description:

  This is joint work with amitiuttarwar.

  This has the first few commits of #28463. It is not strictly a prerequisite for that, but has changes that in our opinion make sense on their own.
  It improves the handling of maximum numbers for different connection types (that are set during init and don’t change after) by:
  * moving all calculations into one place, `CConnMan::Init()`. Before, they were dispersed between `Init`, `CConnman::Init` and other parts of `CConnman`, resulting in some duplicated test code.
  * removing the possibility of having a negative maximum of inbound connections, which is hard to argue about
  * renaming of variables and doc improvements

ACKs for top commit:
  amitiuttarwar:
    co-author review ACK df69b22f2e
  naumenkogs:
    ACK df69b22f2e
  achow101:
    ACK df69b22f2e

Tree-SHA512: 913d56136bc1df739978de50db67302f88bac2a9d34748ae96763288d97093e998fc0f94f9b6eff12867712d7e86225af6128f4170bf2b5b8ab76f024870a22c
2023-11-07 17:01:02 -05:00
Andrew Chow
c981771bc3
Merge bitcoin/bitcoin#28224: shutdown: Destroy kernel last, make test shutdown order consistent
c1144f0076 tests: Reset node context members on ~BasicTestingSetup (TheCharlatan)
9759af17ff shutdown: Destroy kernel last (TheCharlatan)

Pull request description:

  The destruction/resetting of node context members in the tests should roughly follow the behavior of the `Shutdown` function in `init.cpp`.

  This was originally requested by MarcoFalke in this [comment](https://github.com/bitcoin/bitcoin/pull/25065#discussion_r890161249) in response to the [original pull request](https://github.com/bitcoin/bitcoin/pull/25065) introducing the `kernel::Context`.

ACKs for top commit:
  maflcko:
    ACK c1144f0076 🗣
  achow101:
    ACK c1144f0076
  ryanofsky:
    Code review ACK c1144f0076. No code changes since last review, just updated commits and descriptions

Tree-SHA512: 819bb85ff82a5c6c60e429674d5684f3692fe9062500d00a87b361cc59e6bda145be21b5a4466dee6791faed910cbde4d26baab325bf6daa1813af13a63588ff
2023-11-07 16:17:29 -05:00
Andrew Chow
c8a883a412
Merge bitcoin/bitcoin#26839: Add support for RNDR/RNDRRS for AArch64 on Linux
aee5404e02 Add support for RNDR/RNDRRS for aarch64 on Linux (John Moffett)

Pull request description:

  This checks whether the ARMv8.5-A optional TRNG extensions [RNDR](https://developer.arm.com/documentation/ddi0601/2022-12/AArch64-Registers/RNDR--Random-Number) and [RNDRRS](https://developer.arm.com/documentation/ddi0601/2022-12/AArch64-Registers/RNDRRS--Reseeded-Random-Number) are available and, if they are, uses them for random entropy purposes.

  They are nearly functionally identical to the x86 RDRAND/RDSEED extensions and are used in a similar manner.

  Currently, there [appears to be](https://marcin.juszkiewicz.com.pl/download/tables/arm-socs.html) only one actual hardware implementation -- the Amazon Graviton 3. (See the `rnd` column in the link.) However, future hardware implementations may become available.

  It's not possible to directly query for the capability in userspace, but the Linux kernel [added support](1a50ec0b3b) for querying the extension via `getauxval` in version 5.6 (in 2020), so this is limited to Linux-only for now.

  Reviewers may want to launch any of the `c7g` instances from AWS to test the Graviton 3 hardware. Alternatively, QEMU emulates these opcodes for `aarch64` with CPU setting `max`.

  Output from Graviton 3 hardware:

  ```
  ubuntu@ip:~/bitcoin$ src/bitcoind -regtest
  2023-01-06T20:01:48Z Bitcoin Core version v24.99.0-3670266ce89a (release build)
  2023-01-06T20:01:48Z Using the 'arm_shani(1way,2way)' SHA256 implementation
  2023-01-06T20:01:48Z Using RNDR and RNDRRS as additional entropy sources
  2023-01-06T20:01:48Z Default data directory /home/ubuntu/.bitcoin
  ```

  Graviton 2 (doesn't support extensions):

  ```
  ubuntu@ip:~/bitcoin$ src/bitcoind -regtest
  2023-01-06T20:05:04Z Bitcoin Core version v24.99.0-3670266ce89a (release build)
  2023-01-06T20:05:04Z Using the 'arm_shani(1way,2way)' SHA256 implementation
  2023-01-06T20:05:04Z Default data directory /home/ubuntu/.bitcoin
  ```

  This partially closes #26796. As noted in that issue, OpenSSL [added support](https://github.com/openssl/openssl/pull/15361) for these extensions a little over a year ago.

ACKs for top commit:
  achow101:
    ACK aee5404e02
  laanwj:
    Tested ACK aee5404e02

Tree-SHA512: 1c1eb345d6690f5307a87e9bac8f06a0d1fdc7ca35db38fa22192510a44289a03252e4677dc7cbf731a27e6e3a9a4e42b6eb4149fe063bc1c905eb2536cdb1d3
2023-11-07 15:00:38 -05:00
Andrew Chow
e77339632e
Merge bitcoin/bitcoin#28136: refactor: move GetServicesNames from rpc/util.{h,cpp} to rpc/net.cpp
bbb68ffdbd refactor: drop protocol.h include header in rpc/util.h (Jon Atack)
1dd62c5295 refactor: move GetServicesNames from rpc/util.{h,cpp} to rpc/net.cpp (Jon Atack)

Pull request description:

  Move `GetServicesNames()` from `rpc/util` to `rpc/net.cpp`, as it is only called from that compilation unit and there is no reason for other ones to need it.

  Remove the `protocol.h` include in `rpc/util.h`, as it was only needed for `GetServicesNames()`, drop an unneeded forward declaration (the other IWYU suggestions would require more extensive changes in other files), and add 3 already-missing include headers in other translation units that are needed to compile without `protocol.h` in `rpc/util.h`, as `protocol.h` includes `netaddress.h`, which in turn includes `util/strencodings.h`.

ACKs for top commit:
  kevkevinpal:
    lgtm ACK [bbb68ff](bbb68ffdbd)
  ns-xvrn:
    ACK bbb68ff
  achow101:
    ACK bbb68ffdbd

Tree-SHA512: fcbe195874dd4aa9e86548685b6b28595a2c46f9869b79b6e2b3835f76b49cab4bef6a59c8ad6428063a41b7bb6f687229b06ea614fbd103e0531104af7de55d
2023-11-07 14:19:09 -05:00
Andrew Chow
0528cfd307
Merge bitcoin/bitcoin#28649: Do the SOCKS5 handshake reliably
af0fca530e netbase: use reliable send() during SOCKS5 handshake (Vasil Dimov)
1b19d1117c sock: change Sock::SendComplete() to take Span (Vasil Dimov)

Pull request description:

  The `Socks5()` function which does the SOCKS5 handshake with the SOCKS5 proxy sends bytes to the socket without retrying partial writes.

  `send(2)` may write only part of the provided data and return. In this case the caller is responsible for retrying the operation with the remaining data. Change `Socks5()` to do that. There is already a method `Sock::SendComplete()` which does exactly that, so use it in `Socks5()`.

  A minor complication for this PR is that `Sock::SendComplete()` takes `std::string` argument whereas `Socks5()` has `std::vector<uint8_t>`. Thus the necessity for the first commit. It is possible to do also in other ways - convert the data in `Socks5()` to `std::string` or have just one `Sock::SendComplete()` that takes `void*` and change the callers to pass `str.data(), str.size()` or `vec.data(), vec.size()`.

  This came up while testing https://github.com/bitcoin/bitcoin/pull/27375.

ACKs for top commit:
  achow101:
    ACK af0fca530e
  jonatack:
    ACK af0fca530e
  pinheadmz:
    ACK af0fca530e

Tree-SHA512: 1d4a53d0628f7607378038ac56dc3b8624ce9322b034c9547a0c3ce052eafb4b18213f258aa3b57bcb4d990a5e0548a37ec70af2bd55f6e8e6399936f1ce047a
2023-11-07 14:11:58 -05:00
Jameson Lopp
9ac114e5cd
Throw error if invalid parameters passed to getnetworkhashps RPC endpoint 2023-11-07 12:58:42 -05:00
Andrew Chow
3da69c464f
Merge bitcoin/bitcoin#28546: wallet: prevent bugs from invalid transaction heights with asserts, comments, and refactoring
f06016d77d wallet: Add asserts to detect unset transaction height values (Ryan Ofsky)
262a78b133 wallet, refactor: Add CWalletTx::updateState function (Ryan Ofsky)

Pull request description:

  Originally, this PR fixed a wallet migration bug that could cause the watchonly wallet created by legacy wallet migration to have incorrect transaction height values. A different fix for the bug was implemented in #28609, but that PR did not add any test coverage that would have caught the bug, and didn't include other changes from this PR intended to prevent problems from invalid transaction heights.

  This PR adds new asserts to catch invalid transaction heights, which would trigger test failures without bugfix in #28609. This PR also refactors code and adds comments to clarify assumptions and make it less likely a bug from invalid transaction height values would be introduced.

ACKs for top commit:
  achow101:
    ACK f06016d77d
  Sjors:
    utACK f06016d77d
  furszy:
    Code review ACK f06016d

Tree-SHA512: 82657c403724d60354f7676b53bcfcc95bdc5864e051a2eb8bfad09d8ad35615393b2d6b432b46f908def9be37bebded3a55ec9ae19e19371d35897fe842c92e
2023-11-07 11:29:29 -05:00
kevkevin
83933eff00
[refactor] Miniminer var cached_descendants to descendants
Refactored a variable name to be less confusing
2023-11-07 08:56:43 -06:00
kevkevin
43423fd834
[refactor] Change MiniMinerMempoolEntry order
Changes MiniMinerMempoolEntry order to match the order of the params
elsewhere in the codebase
2023-11-07 08:56:36 -06:00
glozow
1147e00e59 [validation] change package-fee-too-low, return wtxid(s) and effective feerate
With subpackage evaluation and de-duplication, it's not always the
entire package that is used in CheckFeerate. To be more helpful to the
caller, specify which transactions were included in the evaluation and
what the feerate was.

Instead of PCKG_POLICY (which is supposed to be for package-wide
errors), use PCKG_TX.
2023-11-07 11:26:17 +00:00
glozow
10dd9f2441 [test] use CheckPackageMempoolAcceptResult in previous tests
Increases test coverage (check every result field) and makes it easier
to test the changes in the next commit.
2023-11-07 11:23:07 +00:00
fanquake
2b3f43b96e
Merge bitcoin/bitcoin#28789: fuzz: Avoid utxo_total_supply timeout (take 2)
fa7ba92630 fuzz: Avoid utxo_total_supply timeout (MarcoFalke)

Pull request description:

  Looks like this still may take a long time to run large fuzz inputs. Thus, reduce it further, but still allow it to catch the regression, if re-introduced:

  ```diff
  diff --git a/src/consensus/tx_check.cpp b/src/consensus/tx_check.cpp
  index f949655909..4bdd15c5ee 100644
  --- a/src/consensus/tx_check.cpp
  +++ b/src/consensus/tx_check.cpp
  @@ -40,7 +40,7 @@ bool CheckTransaction(const CTransaction& tx, TxValidationState& state)
       std::set<COutPoint> vInOutPoints;
       for (const auto& txin : tx.vin) {
           if (!vInOutPoints.insert(txin.prevout).second)
  -            return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputs-duplicate");
  +            {}//return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputs-duplicate");
       }

       if (tx.IsCoinBase())
  ```

  This is the second take, see https://github.com/bitcoin/bitcoin/pull/27780. If in the future it still times out, I think the fuzz test can just be removed.

  Example input:

  ```
  JREROy5pcnAgQyw7IC4ODg4ODg4ODg4O0dEODg4ODg4ZDg4ODg4ODg4ODg7RDg4ODg4ODg4O0dEODg4ODg4ODg4ODg7R0Q4ODg4ODg4ODtHRDg4ODtHR0dEODg4O0dEODg7R0Q4ODg4ODg4ODtHRDg4ODg4ODg4ODg4O0dEODg4ODg4ODg7R0Q4ODg7R0Q4O0dEODg4ODg4ODg4ODg7R0Q4ODg4ODtHRDg4ODtHR

ACKs for top commit:
  dergoegge:
    ACK fa7ba92630
  brunoerg:
    utACK fa7ba92630

Tree-SHA512: 154a4895834babede6ce7b775562a7026637af1097e53e55676e92f6cf966ae0c092300ebf7e51a397eebd11f7b41d020586663e781f70d084efda1c0fe851b4
2023-11-07 11:17:00 +00:00
Sjors Provoost
43de4d3630
doc: fix typos
As found by lint-spelling.py using codespell 2.2.6.
2023-11-07 10:21:51 +09:00
Andrew Chow
0f5e31ce7d
Merge bitcoin/bitcoin#28799: wallet: cache descriptor ID to avoid repeated descriptor string creation
5e6bc6d830 test: remove custom rpc timeout for `wallet_miniscript.py`, reorder in test_runner (Sebastian Falbesoner)
f811a24421 wallet: cache descriptor ID to avoid repeated descriptor string creation (Sebastian Falbesoner)

Pull request description:

  Right now a wallet descriptor is converted to its string representation (via `Descriptor::ToString`) repeatedly at different instances:
  - on finding a `DescriptorScriptPubKeyMan` for a given descriptor (`CWallet::GetDescriptorScriptPubKeyMan`, e.g. used by the `importdescriptors` RPC); the string representation is created once for each spkm in the wallet and at each iteration again for the searched descriptor (`DescriptorScriptPubKeyMan::HasWalletDescriptor`)
  - whenever `DescriptorScriptPubKeyMan::GetID()` is called, e.g. in `TopUp` or any instances where a descriptor is written to the DB to determine the database key, also at less obvious places like `FastWalletRescanFilter` etc.

  As there is no good reason to calculate a fixed descriptor's string/ID more than once, add the ID as a field to `WalletDescriptor` and calculate it immediately at initialization (or deserialization). `HasWalletDescriptor` is changed to compare the spkm's and searched descriptor's ID instead of the string to take use of that.

  This speeds up the functional test `wallet_miniscript.py` by a factor of 5-6x on my machine (3m30.95s on master vs. 0m38.02s on PR). The recently introduced "max-size TapMiniscript" test-case introduced a descriptor that takes 2-3 seconds to create a string representation, so the repeated calls to that were significantly hurting the performance.

  Fixes https://github.com/bitcoin/bitcoin/issues/28800.

ACKs for top commit:
  Sjors:
    ACK 5e6bc6d830
  S3RK:
    Code Review ACK 5e6bc6d830
  achow101:
    ACK 5e6bc6d830
  BrandonOdiwuor:
    ACK 5e6bc6d830

Tree-SHA512: 98b43963a5dde6055bb26cecd3b878dadd837d6226af4c84142383310495da80b3c4bd552e73b9107f2f2ff1c11f5e18060c6fd3d9e44bbd5224114c4d245c1c
2023-11-06 15:18:45 -05:00
glozow
3979f1afcb [validation] add TxValidationResult::TX_RECONSIDERABLE, TX_UNKNOWN
With package validation rules, transactions that fail individually may
sometimes be eligible for reconsideration if submitted as part of a
(different) package. For now, that includes trasactions that failed for
being too low feerate.  Add a new TxValidationResult type to distinguish
these failures from others.  In the next commits, we will abort package
validation if a tx fails for any other reason. In the future, we will
also decide whether to cache failures in recent_rejects based on this
result (we won't want to reject a package containing a transaction that
was rejected previously for being low feerate).

Package validation also sometimes elects to skip some transactions when
it knows the package will not be submitted in order to quit sooner. Add
a result to specify this situation; we also don't want to cache these
as rejections.
2023-11-06 14:41:56 +00:00
glozow
5c786a026a [refactor] use Wtxid for m_wtxids_fee_calculations 2023-11-06 14:33:32 +00:00
Sebastian Falbesoner
f811a24421 wallet: cache descriptor ID to avoid repeated descriptor string creation
Right now a wallet descriptor is converted to it's string representation
(via `Descriptor::ToString`) repeatedly at different instances:
- on finding a `DescriptorScriptPubKeyMan` for a given descriptor
  (`CWallet::GetDescriptorScriptPubKeyMan`, e.g. used by the
  `importdescriptors` RPC); the string representation is created once
  for each spkm in the wallet and at each iteration again for
  the searched descriptor (`DescriptorScriptPubKeyMan::HasWalletDescriptor`)
- whenever `DescriptorScriptPubKeyMan::GetID()` is called, e.g. in
  `TopUp` or any instances where a descriptor is written to the DB
  to determine the database key etc.

As there is no good reason to calculate a fixed descriptor's string/ID
more than once, add the ID as a field to `WalletDescriptor` and
calculate it immediately at initialization (or deserialization).
`HasWalletDescriptor` is changed to compare the spkm's and searched
descriptor's ID instead of the string to take use of that.

This speeds up the functional test `wallet_miniscript.py` by a factor of
5-6x on my machine (3m30.95s on master vs. 0m38.02s on PR). The recently
introduced "max-size TapMiniscript" test-case introduced a descriptor
that takes 2-3 seconds to create a string representation, so the
repeated calls to that were significantly hurting the performance.
2023-11-05 23:50:58 +01:00
Mark Friedenbach
cdc6ac4126 snapshots: don't core dump when running -checkblockindex after loadtxoutset 2023-11-04 12:32:17 -07:00
MarcoFalke
fa7ba92630
fuzz: Avoid utxo_total_supply timeout 2023-11-03 21:16:12 +01:00
Greg Sanders
5380f05513 test: bugfix CheckPackageMempoolAcceptResult return all error strings 2023-11-03 16:05:55 -04:00
Sebastian Falbesoner
5039c346ca init: completely remove -zapwallettxes (remaining hidden option)
The `-zapwallettxes` functionality has been removed in v0.21.0
(see commit 3340dbadd3 / PR #19671),
with the parameter being kept as hidden option, to inform users via
an exit error that `abandontransaction` should be used instead.

As any guides that still suggest to use `-zapwallettxes` would refer to
a Bitcoin Core version that is EOL since many years (i.e. <= v0.20.x),
it is highly unlikely that the error caused by the option is still
relevant for any user, hence it seems fine to remove it now.
2023-11-03 20:00:44 +01:00
Roman Zeyde
7cb9367157
rpc: keep .cookie if it was not generated
Otherwise, starting bitcoind twice may cause the `.cookie`
file generated by the first instance to be deleted by the
second instance shutdown (after failing to obtain a lock).
2023-11-03 17:29:27 +02:00
Andrew Chow
d9007f51a7
Merge bitcoin/bitcoin#28762: MiniMiner changes for package linearization
d9cc99d04e [test] MiniMiner::Linearize and manual construction (glozow)
dfd6a3788c [refactor] unify fee amounts in miniminer_tests (glozow)
f4b1b24a3b [MiniMiner] track inclusion order and add Linearize() function (glozow)
004075963f [test] add case for MiniMiner working with negative fee txns (glozow)
fe6332c0ba [MiniMiner] make target_feerate optional (glozow)
5a83f55c96 [MiniMiner] allow manual construction with non-mempool txns (glozow)
e3b2e630b2 [refactor] change MiniMinerMempoolEntry ctor to take values, update includes (glozow)
4aa98b79b2 [lint] update expected boost includes (glozow)

Pull request description:

  This is part of #27463. It splits off the `MiniMiner`-specific changes from #26711 for ease of review, as suggested in https://github.com/bitcoin/bitcoin/pull/26711#issuecomment-1786392253.

  - Allow using `MiniMiner` on transactions that aren't in the mempool.
  - Make `target_feerate` param of `BuildMockTemplate` optional, meaning "don't stop building the template until all the transactions have been selected."
    - Add clarification for how this is different from `target_feerate=0` (https://github.com/bitcoin/bitcoin/pull/26711#discussion_r1377019133)
  - Track the order in which transactions are included in the template to get the "linearization order" of the transactions.
  - Tests

  Reviewers can take a look at #26711 to see how these functions are used to linearize the `AncestorPackage` there.

ACKs for top commit:
  TheCharlatan:
    ACK d9cc99d04e
  kevkevinpal:
    reACK [d9cc99d](d9cc99d04e)
  achow101:
    re-ACK d9cc99d04e

Tree-SHA512: 32b80064b6679536ac573d674825c5ca0cd6245e49c2fd5eaf260dc535335a57683c74ddd7ce1f249b5b12b2683de4362a7b0f1fc0814c3b3b9f14c682665583
2023-11-03 10:50:50 -04:00
fanquake
5d9f45082b
Merge bitcoin/bitcoin#28758: refactors for subpackage evaluation
b5a60abe87 MOVEONLY: CleanupTemporaryCoins into its own function (glozow)
10c0a8678c [test util] CreateValidTransaction multi-in/out, configurable feerate, signal BIP125 (glozow)
6ff647a7e0 scripted-diff: rename CheckPackage to IsWellFormedPackage (glozow)
da9aceba21 [refactor] move package checks into helper functions (glozow)

Pull request description:

  This is part of #27463. It splits off the more trivial changes from #26711 for ease of review, as requested in https://github.com/bitcoin/bitcoin/pull/26711#issuecomment-1786392253.

  - Split package sanitization in policy/packages.h into helper functions
    - Add some tests for its quirks (https://github.com/bitcoin/bitcoin/pull/26711#discussion_r1340521597)
  - Rename `CheckPackage` to `IsPackageWellFormed`
  - Improve the `CreateValidTransaction` unit test utility to:
    - Configure the target feerate and return the fee paid
    - Signal BIP125 on transactions to enable RBF tests
    - Allow the specification of multiple inputs and outputs
  - Move `CleanupTemporaryCoins` into its own function to be reused later without duplication

ACKs for top commit:
  dergoegge:
    Code review ACK b5a60abe87
  instagibbs:
    ACK b5a60abe87

Tree-SHA512: 39d67a5f0041e381f0d0f802a98ccffbff11e44daa3a49611189d6306b03f18613d5ff16c618898d490c97a216753e99e0db231ff14d327f92c17ae4d269cfec
2023-11-03 14:41:17 +00:00
glozow
f23ac10ca5
Merge bitcoin/bitcoin#28764: Fuzz: Check individual and package transaction invariants
fcb3069fa3 Use CheckPackageMempoolAcceptResult for package evaluation fuzzing (Greg Sanders)
34088d6c9e [test util] CheckPackageMempoolAcceptResult for sanity-checking results (glozow)
651fa404e4 fuzz: tx_pool checks ATMP result invariants (Greg Sanders)

Pull request description:

  Poached from https://github.com/bitcoin/bitcoin/pull/26711 since that PR is being split apart, and modified to match current behavior.

ACKs for top commit:
  glozow:
    reACK fcb3069fa3, only whitespace changes
  dergoegge:
    ACK fcb3069fa3

Tree-SHA512: abd687e526d8dfc8d65b3a873ece8ca35fdcbd6b0f7b93da6a723ef4e47cf85612de819e6f2b8631bdf897e1aba27cdd86f89b7bd85fc3356e74be275dcdf8cc
2023-11-03 13:51:12 +00:00
glozow
d9cc99d04e [test] MiniMiner::Linearize and manual construction 2023-11-03 10:39:29 +00:00
glozow
dfd6a3788c [refactor] unify fee amounts in miniminer_tests
Name {low,med,high}_fee constants for reuse across file.
2023-11-03 10:17:41 +00:00
glozow
f4b1b24a3b [MiniMiner] track inclusion order and add Linearize() function
Sometimes we are just interested in the order in which transactions
would be included in a block (we want to "linearize" the transactions).
Track and store this information.

This doesn't change any of the bump fee calculations.
2023-11-03 10:17:41 +00:00
glozow
004075963f [test] add case for MiniMiner working with negative fee txns 2023-11-03 10:17:41 +00:00
glozow
fe6332c0ba [MiniMiner] make target_feerate optional
Add an option to keep building the template regardless of feerate. We
can't just use target_feerate=0 because it's possible for transactions
to have negative modified feerates.

No behavior change for users that pass in a target_feerate.
2023-11-03 10:17:41 +00:00
glozow
5a83f55c96 [MiniMiner] allow manual construction with non-mempool txns
This is primarily intended for linearizing a package of transactions
prior to submitting them to mempool. Note that, if this ctor is used,
bump fees will not be calculated because we haven't instructed MiniMiner
which outpoints for which we want bump fees to be calculated.
2023-11-03 10:17:41 +00:00
glozow
e3b2e630b2 [refactor] change MiniMinerMempoolEntry ctor to take values, update includes
No behavior change. All we are doing is copying out these values before
passing them into the ctor instead of within the ctor.

This makes it possible to use the MiniMiner algorithms to analyze
transactions that haven't been submitted to the mempool yet.

It also iwyu's the mini_miner includes.
2023-11-03 10:17:41 +00:00
Andrew Chow
9b68c9b85e
Merge bitcoin/bitcoin#28172: refactor: use string_view for passing string literals to Parse{Hash,Hex}
bb91131d54 doc: remove out-of-date external link in src/util/strencodings.h (Jon Atack)
7d494a48dd refactor: use string_view to pass string literals to Parse{Hash,Hex} (Jon Atack)

Pull request description:

  as `string_view` is optimized to be trivially copiable, whereas the current code creates a `std::string` copy at each call.

  These utility methods are called by quite a few RPCs and tests, as well as by each other.

  ```
  $ git grep "ParseHashV\|ParseHashO\|ParseHexV\|ParseHexO" | wc -l
  61
  ```

  Also remove an out-of-date external link.

ACKs for top commit:
  jonatack:
    Rebased per `git range-diff c9273f6 b94581a bb91131` for an include header from the merge of https://github.com/bitcoin/bitcoin/pull/28230. Should be trivial to re-ACK.
  maflcko:
    lgtm ACK bb91131d54
  ns-xvrn:
    ACK bb91131d54
  achow101:
    ACK bb91131d54
  brunoerg:
    crACK bb91131d54

Tree-SHA512: 9734fe022c9e43fd93c23a917770d332dbbd3132c80a234059714c32faa6469391e59349954749fc86c4ef0b18d5fd99bf8f4b7b82d9f799943799c1253272ae
2023-11-02 15:45:13 -04:00
Andrew Chow
0857f2935f
Merge bitcoin/bitcoin#24097: Replace RecursiveMutex m_cs_banned with Mutex, and rename it
37d150d8c5 refactor: Add more negative `!m_banned_mutex` thread safety annotations (Hennadii Stepanov)
0fb2908708 refactor: replace RecursiveMutex m_banned_mutex with Mutex (w0xlt)
784c316f9c scripted-diff: rename m_cs_banned -> m_banned_mutex (w0xlt)
46709c5f27 refactor: Get rid of `BanMan::SetBannedSetDirty()` (Hennadii Stepanov)
d88c0d8440 refactor: Get rid of `BanMan::BannedSetIsDirty()` (Hennadii Stepanov)

Pull request description:

  This PR is an alternative to bitcoin/bitcoin#24092. Last two commit have been cherry-picked from the latter.

ACKs for top commit:
  maflcko:
    ACK 37d150d8c5 🎾
  achow101:
    ACK 37d150d8c5
  theStack:
    Code-review ACK 37d150d8c5
  vasild:
    ACK 37d150d8c5

Tree-SHA512: 5e9d40101a09af6e0645a6ede67432ea68631a1b960f9e6af0ad07415ca7718a30fcc1aad5182d1d5265dc54c26aba2008fc9973840255c09adbab8fedf10075
2023-11-02 14:09:27 -04:00
Greg Sanders
fcb3069fa3 Use CheckPackageMempoolAcceptResult for package evaluation fuzzing 2023-11-02 09:33:47 -04:00
glozow
34088d6c9e [test util] CheckPackageMempoolAcceptResult for sanity-checking results 2023-11-02 09:33:47 -04:00
glozow
2e9454a633
Merge bitcoin/bitcoin#21161: Fee estimation: extend bucket ranges consistently
a5e39d325d Fee estimation: extend bucket ranges consistently (Anthony Towns)

Pull request description:

  When calculating a median fee for a confirmation target at a particular threshold, we analyse buckets in ranges rather than individually in case some buckets have very little data. This patch ensures the breaks between ranges are independent of the the confirmation target.

  Fixes #20725

ACKs for top commit:
  ismaelsadeeq:
    Code review ACK a5e39d325d
  glozow:
    btw what I meant by [this](https://github.com/bitcoin/bitcoin/pull/21161#pullrequestreview-1350258467) was ACK a5e39d325d
  jonatack:
    Initial ACK a5e39d325d

Tree-SHA512: 0edf4e56717c4ab8d4ab0bc0f1d7ab36a13b99de12f689e55c9142c6b81691367ffd8df2e8260c5e14335310b1a51770c6c22995db31109976239befcb558ef8
2023-11-02 11:25:50 +00:00
glozow
023418a140
Merge bitcoin/bitcoin#28530: tests, bug fix: DisconnectedBlockTransactions rewrite followups
9b3da70bd0 [test] DisconnectedBlockTransactions::DynamicMemoryUsage (glozow)
b2d0447964 bugfix: correct DisconnectedBlockTransactions memory usage (stickies-v)
f4254e2098 assume duplicate transactions are not added to `iters_by_txid` (ismaelsadeeq)
29eb219c12 move only: move implementation code to disconnected_transactions.cpp (ismaelsadeeq)
81dfeddea7 refactor: update `MAX_DISCONNECTED_TX_POOL` from kb to bytes (ismaelsadeeq)

Pull request description:

  This PR is a follow-up to fix review comments and a bugfix from #28385

  The PR

  - Updated `DisconnectedBlockTransactions`'s `MAX_DISCONNECTED_TX_POOL` from kb to bytes.
  - Moved `DisconnectedBlockTransactions` implementation code to `kernel/disconnected_transactions.cpp`.
  - `AddTransactionsFromBlock` now assume duplicate transactions are not passed by asserting after inserting each transaction to `iters_by_txid`.
  - Included a Bug fix: In the current master we are underestimating the memory usage of `DisconnectedBlockTransactions`.

      * When adding and subtracting `cachedInnerUsage` we call `RecursiveDynamicUsage` with `CTransaction` which invokes this [`RecursiveDynamicUsage(const CTransaction& tx)`](6e721c923c/src/core_memusage.h (L32)) version of `RecursiveDynamicUsage`, the output of that call only account for the memory usage of the inputs and outputs of the `CTransaction`, this omits the memory usage of the `CTransaction` object and the control block.
      * This PR fixes this bug by calling `RecursiveDynamicUsage` with `CTransactionRef` when adding and subtracting `cachedInnerUsage` which invokes [`RecursiveDynamicUsage(const std::shared_ptr<X>& p)`](6e721c923c/src/core_memusage.h (L67)) version of `RecursiveDynamicUsage` the output of the calculation accounts for the` CTransaction` object, the control blocks, inputs and outputs memory usage.
      * see  [comment ](https://github.com/bitcoin/bitcoin/pull/28385#discussion_r1322948452)
  - Added test for DisconnectedBlockTransactions memory limit.

ACKs for top commit:
  stickies-v:
    ACK 9b3da70bd0 - nice work!
  BrandonOdiwuor:
    re ACK 9b3da70bd0
  glozow:
    ACK 9b3da70bd0

Tree-SHA512: 69b9595d09f4d0209038f97081d790cea92ccf63efb94e9e372749979fcbe527f7f17a8e454720cedd12021be0c8e11cf99874625d3dafd9ec602b12dbeb4098
2023-11-02 11:12:17 +00:00
glozow
b5a60abe87 MOVEONLY: CleanupTemporaryCoins into its own function
Avoid duplicate code. This will be used at the end of every
AcceptSubPackage and after PreChecks loop in AcceptPackage.
2023-11-01 17:21:54 +00:00
glozow
10c0a8678c [test util] CreateValidTransaction multi-in/out, configurable feerate, signal BIP125
Support the creation of a transaction with multiple specified inputs or
outputs. Also accept a target feerate and return the fee paid.

Also, signal BIP125 by default - a subsequent commit needs to RBF
something.

Co-authored-by: Andrew Chow <achow101@gmail.com>
2023-11-01 17:21:54 +00:00
glozow
6ff647a7e0 scripted-diff: rename CheckPackage to IsWellFormedPackage
-BEGIN VERIFY SCRIPT-
sed -i 's/CheckPackage(/IsWellFormedPackage(/g' $(git grep -l CheckPackage)
-END VERIFY SCRIPT-
2023-11-01 17:21:54 +00:00
glozow
da9aceba21 [refactor] move package checks into helper functions
This allows IsSorted() and IsConsistent() to be used by themselves.
IsSorted() with a precomputed set is used so that we don't create this
set multiple times.
2023-11-01 17:21:54 +00:00
MarcoFalke
fa7d31910a
refactor: Remove unused circular include dependency from validation.cpp 2023-11-01 17:45:48 +01:00
dergoegge
af1d2ff883 [primitives] Precompute result of CTransaction::HasWitness 2023-11-01 15:15:05 +00:00
fanquake
4733de3242
Merge bitcoin/bitcoin#28729: addrman: log AS only when using asmap
02a4f1a385 addrman: log AS only when using asmap (brunoerg)

Pull request description:

  This PR changes the log to just print the ASN when using asmap, same logic presented in other logs:

  afa081a39b/src/net_processing.cpp (L3552-L3556)

  afa081a39b/src/net_processing.cpp (L3598-L3604)

ACKs for top commit:
  naumenkogs:
    ACK 02a4f1a385
  mzumsande:
    Code Review ACK 02a4f1a385

Tree-SHA512: adad5904ab163660d47554b32dc2dc3dfdff8dd64b94e5320ad11706381264d1e338654fa8239430eed4ccbebc8f6670698b4278895794055c37fc4bcefe71bc
2023-11-01 10:25:53 +00:00
Hennadii Stepanov
04bfe8c9c3
Merge bitcoin-core/gui#774: Fix crash on selecting "Mask values" in transaction view
e26e665f9f gui: fix crash on selecting "Mask values" in transaction view (Sebastian Falbesoner)

Pull request description:

  This PR fixes a crash bug that can be caused with the following steps:
  - change to the "Transactions" view
  - right-click on an arbitrary transaction -> "Show transaction details"
  - close the transaction detail window again
  - select menu item "Settings" -> "Mask values"

  The problem is that the list of opened dialogs, tracked in the member variable `m_opened_dialogs` (introduced in https://github.com/bitcoin-core/gui/pull/708, commit 4492de1be1), is only ever appended with newly opened transaction detail dialog pointers, but never removed. This leads to dangling pointers in the list, and if the "Mask values" menu item is selected, a crash is caused in the course of trying to close the opened transaction detail dialogs (see `closeOpenedDialogs()` method). Fix this by removing a pointer of the list if the corresponding widget is destroyed.

ACKs for top commit:
  achow101:
    ACK e26e665f9f
  pablomartin4btc:
    tACK e26e665f9f
  furszy:
    utACK e26e665f9
  hebasto:
    ACK e26e665f9f, tested on Ubuntu 22.04.

Tree-SHA512: 37885c22abae0ab065b4878bae46fd362f41b09609d081fd59e26bb05474f427b98771ee73f5480526afaef04e016c5ba62c956e0e85a57b6a0f44a905b68a83
2023-11-01 09:57:17 +00:00
Greg Sanders
651fa404e4 fuzz: tx_pool checks ATMP result invariants 2023-10-31 14:52:45 -04:00
Jon Atack
0420f99f42 Create net_peer_connection unit tests
for initial partial unit test coverage of these CConnman class methods:

- AddNode()
- ConnectNode()
- GetAddedNodeInfo()
- AlreadyConnectedToAddress()
- ThreadOpenAddedConnections()

and of the GetAddedNodeInfo() call in RPC addnode.
2023-10-31 13:37:12 -04:00
Vasil Dimov
af0fca530e
netbase: use reliable send() during SOCKS5 handshake
`send(2)` can be interrupted or for another reason it may not fully
complete sending all the bytes. We should be ready to retry the send
with the remaining bytes. This is what `Sock::SendComplete()` does,
thus use it in `Socks5()`.

Since `Sock::SendComplete()` takes a `CThreadInterrupt` argument,
change also the recv part of `Socks5()` to use `CThreadInterrupt`
instead of a boolean.

Easier reviewed with `git show -b` (ignore white-space changes).
2023-10-31 18:19:37 +01:00
Vasil Dimov
1b19d1117c
sock: change Sock::SendComplete() to take Span
This would make it easier to pass other than `std::string` types,
to be used in the `Socks5()` function.
2023-10-31 18:19:22 +01:00
fanquake
d51fb9caa6
Merge bitcoin/bitcoin#28503: refactor: Remove WithParams serialization helper, use SER_PARAMS_OPFUNC
99990194ce Remove WithParams serialization helper (MarcoFalke)
ffffb4af83 scripted-diff: Use ser params operator (MarcoFalke)
fae9054793 test: Use SER_PARAMS_OPFUNC in serialize_tests.cpp (MarcoFalke)

Pull request description:

  Every serialization parameter struct already has the `SER_PARAMS_OPFUNC`, except for one in the tests.

  For consistency, and to remove verbose code, convert the test to `SER_PARAMS_OPFUNC`, and use it everywhere, then remove the `WithParams` helper.

ACKs for top commit:
  ajtowns:
    reACK 99990194ce
  TheCharlatan:
    Re-ACK 99990194ce

Tree-SHA512: be9cae4225a502486fe8d552aaf4b2cd2904a9f73cce9d931c6b7c757594ff1982fcc2c30d00d012cd12b0a9531fd609f8bcd7c94b811e965ac087eb8a3589d3
2023-10-31 11:11:25 +00:00
Sebastian Falbesoner
e26e665f9f gui: fix crash on selecting "Mask values" in transaction view
This commits fixes a crash bug that can be caused with the following steps:
- change to the "Transactions" view
- right-click on an arbitrary transaction -> "Show transaction details"
- close the transaction detail window again
- select "Settings" -> "Mask values"

The problem is that the list of opened dialogs, tracked in the member
variable `m_opened_dialogs`, is only ever appended with newly opened
transaction detail dialog pointers, but never removed. This leads to
dangling pointers in the list, and if the "Mask values" menu item is
selected, a crash is caused in the course of trying to close the opened
transaction detail dialogs (see `closeOpenedDialogs()` method). Fix this
by removing the pointer from the list if the corresponding widget is
destroyed.
2023-10-31 00:27:26 +01:00
brunoerg
02a4f1a385 addrman: log AS only when using asmap 2023-10-30 18:46:06 -03:00
fanquake
4458ae811a
Merge bitcoin/bitcoin#28741: refactor: Fix bugprone-string-constructor warning
fa56067a8f refactor: Fix bugprone-string-constructor warning (MarcoFalke)

Pull request description:

  String literals in C++ have a trailing null character, so the current code is fine to rely on that implicitly. However,
  * the sqlite documentation explicitly mentions the null character
  * code readers may wonder if the code is intentional
  * clang-tidy warns about the code via `bugprone-string-constructor`

  Address the points by putting the null character into the code and enable the clang-tidy `bugprone-string-constructor` check.

ACKs for top commit:
  stickies-v:
    ACK fa56067a8f

Tree-SHA512: da519184d792a885a8151ffc44c8da5781f5aaae12ef768a187cc6d9e542ca8952aebc2ec6c1a05f673f29a86ef44902ee96e7b491af7b4705ad38e14624882e
2023-10-30 16:36:14 +00:00
Jon Atack
4b834f6499 Allow unit tests to access additional CConnman members
that are otherwise private:
- CConnman::m_nodes
- CConnman::ConnectNodes()
- CConnman::AlreadyConnectedToAddress()

and update the #include headers per iwyu.
2023-10-30 11:44:59 -04:00
Sergi Delgado Segura
34b9ef443b net/rpc: Makes CConnman::GetAddedNodeInfo able to return only non-connected address on request
`CConnman::GetAddedNodeInfo` is used both to get a list of addresses to manually connect to
in `CConnman::ThreadOpenAddedConnections`, and to report about manually added connections in
`getaddednodeinfo`. In both cases, all addresses added to `m_added_nodes` are returned, however
the nodes we are already connected to are only relevant to the latter, in the former they are
actively discarded.

Parametrizes `CConnman::GetAddedNodeInfo` so we can ask for only addresses we are not connected to,
to avoid passing useless information around.
2023-10-30 11:39:21 -04:00
Sergi Delgado Segura
94e8882d82 rpc: Prevents adding the same ip more than once when formatted differently
Currently it is possible to add the same node twice when formatting IPs in
different, yet equivalent, manner. This applies to both ipv4 and ipv6, e.g:

127.0.0.1 = 127.1 | [::1] = [0:0:0:0:0:0:0:1]

`addnode` will accept both and display both as connected (given they translate to
the same IP). This will not result in multiple connections to the same node, but
will report redundant info when querying `getaddednodeinfo` and populate `m_added_nodes`
with redundant data.

This can be avoided performing comparing the contents of `m_added_addr` and the address
to be added as `CServices` instead of as strings.
2023-10-30 11:39:19 -04:00
Sergi Delgado Segura
2574b7e177 net/rpc: Check all resolved addresses in ConnectNode rather than just one
The current `addnode` rpc command has some edge cases in where it is possible to
connect to the same node twice by combining ip and address requests. This can happen under two situations:

The two commands are run one right after each other, in which case they will be processed
under the same loop in `CConnman::ThreadOpenAddedConnections` without refreshing `vInfo`, so both
will go trough. An example of this would be:

```
bitcoin-cli addnode "localhost:port" add

```

A node is added by IP using `addnode "add"` while the other is added by name using
`addnode "onetry"` with an address that resolves to multiple IPs. In this case, we currently
only check one of the resolved IPs (picked at random), instead of all the resolved ones, meaning
this will only probabilistically fail/succeed. An example of this would be:

```
bitcoin-cli addnode "127.0.0.1:port" add
[...]
bitcoin-cli addnode "localhost:port" onetry
```

Both cases can be fixed by iterating over all resolved addresses in `CConnman::ConnectNode` instead
of picking one at random
2023-10-30 11:21:57 -04:00
MarcoFalke
fa5423b5b5
refactor: Remove unused gcc-9 workaround in txrequest 2023-10-30 15:18:40 +01:00
MarcoFalke
faea58eee4
Bump g++ minimum supported version to 10
Also, enable -Werror=maybe-uninitialized in
ci/test/00_setup_env_native_qt5.sh
2023-10-30 15:12:26 +01:00
MarcoFalke
fa56067a8f
refactor: Fix bugprone-string-constructor warning 2023-10-30 14:59:17 +01:00
fanquake
6391644b66
Merge bitcoin/bitcoin#28737: doc: Fix bugprone-lambda-function-name errors
faa769db5a Fix bugprone-lambda-function-name errors (MarcoFalke)

Pull request description:

  Inside a lambda, `__func__` will evaluate to something like `"operator()"`. Fix this by either removing it, or by using the real name.

  https://clang.llvm.org/extra/clang-tidy/checks/bugprone/lambda-function-name.html

ACKs for top commit:
  TheCharlatan:
    ACK faa769db5a
  darosior:
    utACK faa769db5a

Tree-SHA512: 0b562bd4ebd7f46ca3ebabeee67851ad30bd522fa57e5010e833b163664e51f5df645ff9ca35d22c3479fb27d9267d4e5d0d417d42729bf3ccf80d7944970e4e
2023-10-30 14:54:11 +01:00
fanquake
ec5116ae14
Merge bitcoin/bitcoin#28695: net: Sanity check private keys received from SAM proxy
5cf4d266d9 [test] Test i2p private key constraints (Vasil Dimov)
cf70a8d565 [net] Check i2p private key constraints (dergoegge)

Pull request description:

  Not sanity checking can lead to crashes or worse:

  ```
  ==1715589==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6140000055c2 at pc 0x5622ed66e7ad bp 0x7ffee547a2c0 sp 0x7ffee547a2b8
  READ of size 2 at 0x6140000055c2 thread T0 (b-test)
      #0 0x5622ed66e7ac in memcpy include/bits/string_fortified.h:29:10
      #1 0x5622ed66e7ac in i2p::sam::Session::MyDestination() const src/i2p.cpp:362:5
      #2 0x5622ed662e46 in i2p::sam::Session::CreateIfNotCreatedAlready() src/i2p.cpp:414:40
      #3 0x5622ed6619f2 in i2p::sam::Session::Listen(i2p::Connection&) src/i2p.cpp:143:9
  ```

ACKs for top commit:
  maflcko:
    code lgtm ACK 5cf4d266d9
  stickies-v:
    re-ACK 5cf4d266d9
  vasild:
    ACK 5cf4d266d9

Tree-SHA512: 3de3bd396538fa619de67957b9c8a58011ab911f0f51097c387e730c13908278b7322aa3357051fb245a20b15bef34b0e9fadcb1eff8ad751139d2aa634c78ad
2023-10-30 14:44:40 +01:00
MarcoFalke
99990194ce
Remove WithParams serialization helper 2023-10-30 13:54:52 +01:00
Vasil Dimov
5cf4d266d9 [test] Test i2p private key constraints 2023-10-30 11:41:11 +00:00
fanquake
feae4e0438
Merge bitcoin/bitcoin#28698: assumeutxo, blockstorage: Prevent core dump on invalid hash
811067ca1c test: add coverage for snapshot chainstate not matching AssumeUTXO parameters (pablomartin4btc)
4a5be10b92 assumeutxo, blockstorage: prevent core dump on invalid hash (pablomartin4btc)

Pull request description:

  While reviewing #27596 (ran `loadtxoutset` in `mainnet` before `m_assumeutxo_data` is empty as [currently](434495a8c1/src/kernel/chainparams.cpp (L175-L177)) in master  - back to 1b1d711), got a `core dumped`, so it seems there's a potential issue if new releases ever remove snapshot details or a semi-experienced user performs a `loadtxoutset` on a different "customised" binary version (not sure if this is a real use case).

  ```
  2023-10-18T17:42:52Z [init] Using obfuscation key for /tmp/.test_utxo_2/blocks/index: 0000000000000000
  node/blockstorage.cpp:390 LoadBlockIndex: Assertion `GetParams().AssumeutxoForBlockhash(*snapshot_blockhash)' failed.
  Aborted (core dumped)
  ```

  <details>
  <summary>This is also happening before IBD is completed (<code>background validation</code> still being performed as it can be seen in rpc <code>getchainstates</code>)</summary>

  ```
  /src/bitcoin-cli -datadir=${AU_DATADIR} getchainstates
  {
    "headers": 813097,
    "chainstates": [
      {
        "blocks": 368249,
        "bestblockhash": "00000000000000000b7a08224a1cb00d337100ba7a46c03d04b2c2d8964efc37",
        "difficulty": 52278304845.59168,
        "verificationprogress": 0.086288278873286,
        "coins_db_cache_bytes": 7969177,
        "coins_tip_cache_bytes": 14908338995,
        "validated": true
      },
      {
        "blocks": 813097,
        "bestblockhash": "0000000000000000000270c9fdce7b17db64cca91f90106964b58e33a4d91089",
        "difficulty": 61030681983175.59,
        "verificationprogress": 0.999997140098457,
        "coins_db_cache_bytes": 419430,
        "coins_tip_cache_bytes": 784649420,
        "snapshot_blockhash": "00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054",
        "validated": false
      }
    ]
  }
  ```
  </details>

  <details>
  <summary>Steps to reproduce the core dump error and its output:</summary>

  1. Perform a `loadtxoutset` in `mainnet` on compiled `bitcoind` adding the block hash from Sjors's [commit](24deb2022b).
  2. Once step 1 finishes, remove the added code from step 1 and compile again or just compile `master` without any changes on top.
  3. Run `bitcoind`, soon it'll crash with:

  ```
  2023-10-18T17:42:52Z [init] init message: Loading block index…
  2023-10-18T17:42:52Z [init] Assuming ancestors of block 00000000000000000001a0a448d6cf2546b06801389cc030b2b18c6491266815 have valid signatures.
  2023-10-18T17:42:52Z [init] Setting nMinimumChainWork=000000000000000000000000000000000000000052b2559353df4117b7348b64
  2023-10-18T17:42:52Z [init] Prune configured to target 3000 MiB on disk for block and undo files.
  2023-10-18T17:42:52Z [init] [snapshot] detected active snapshot chainstate (/tmp/.test_utxo_2/chainstate_snapshot) - loading
  2023-10-18T17:42:52Z [init] [snapshot] switching active chainstate to Chainstate [snapshot] @ height -1 (null)
  2023-10-18T17:42:52Z [init] Opening LevelDB in /tmp/.test_utxo_2/blocks/index
  2023-10-18T17:42:52Z [init] Opened LevelDB successfully
  2023-10-18T17:42:52Z [init] Using obfuscation key for /tmp/.test_utxo_2/blocks/index: 0000000000000000
  node/blockstorage.cpp:390 LoadBlockIndex: Assertion `GetParams().AssumeutxoForBlockhash(*snapshot_blockhash)' failed.
  Aborted (core dumped)
  ```
  </details>

  <details>
  <summary>After original change, error message output:</summary>

  ```
  2023-10-20T15:49:12Z [init] init message: Loading block index…
  2023-10-20T15:49:12Z [init] Assuming ancestors of block 00000000000000000001a0a448d6cf2546b06801389cc030b2b18c6491266815 have valid signatures.
  2023-10-20T15:49:12Z [init] Setting nMinimumChainWork=000000000000000000000000000000000000000052b2559353df4117b7348b64
  2023-10-20T15:49:12Z [init] Prune configured to target 3000 MiB on disk for block and undo files.
  2023-10-20T15:49:12Z [init] [snapshot] detected active snapshot chainstate (/tmp/.test_utxo_2/chainstate_snapshot) - loading
  2023-10-20T15:49:12Z [init] [snapshot] switching active chainstate to Chainstate [snapshot] @ height -1 (null)
  2023-10-20T15:49:12Z [init] Opening LevelDB in /tmp/.test_utxo_2/blocks/index
  2023-10-20T15:49:12Z [init] Opened LevelDB successfully
  2023-10-20T15:49:12Z [init] Using obfuscation key for /tmp/.test_utxo_2/blocks/index: 0000000000000000
  2023-10-20T15:49:13Z [init] *** Assumeutxo data not found for the given blockhash '00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054'.
  2023-10-20T15:49:13Z [init] Error: Assumeutxo data not found for the given blockhash '00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054'.
  Error: Assumeutxo data not found for the given blockhash '00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054'.
  2023-10-20T15:49:13Z [init] Shutdown requested. Exiting.
  2023-10-20T15:49:13Z [init] Shutdown: In progress...
  2023-10-20T15:49:13Z [scheduler] scheduler thread exit
  2023-10-20T15:49:13Z [shutoff] Flushed fee estimates to fee_estimates.dat.
  2023-10-20T15:49:13Z [shutoff] Shutdown: done
  ```
  </details>

  <details>
  <summary>Alternative on error handling using <code>return error()</code> instead of <code>return FatalError()</code> used in this PR, which produces a different output and perhaps confusing:</summary>

  ```
  2023-10-20T21:45:58Z [init] Using obfuscation key for /tmp/.test_utxo_2/blocks/index: 0000000000000000
  2023-10-20T21:45:59Z [init] ERROR: Assumeutxo data not found for the given blockhash '00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054'.
  2023-10-20T21:45:59Z [init] : Error loading block database.
  Please restart with -reindex or -reindex-chainstate to recover.
  : Error loading block database.
  Please restart with -reindex or -reindex-chainstate to recover.
  2023-10-20T21:45:59Z [init] Aborted block database rebuild. Exiting.
  2023-10-20T21:45:59Z [init] Shutdown: In progress...
  2023-10-20T21:45:59Z [scheduler] scheduler thread exit
  2023-10-20T21:45:59Z [shutoff] Flushed fee estimates to fee_estimates.dat.
  2023-10-20T21:45:59Z [shutoff] Shutdown: done
  ```

  </details>

  <details>
  <summary>Current state (including ryanofsky <a href="https://github.com/bitcoin/bitcoin/pull/28698#discussion_r1368635965">suggestion</a>), after code change, error message output:</summary>

  ```
  2023-10-25T02:29:57Z [init] Using obfuscation key for /home/pablo/.test_utxo_2/regtest/blocks/index: 0000000000000000
  2023-10-25T02:29:57Z [init] *** Assumeutxo data not found for the given blockhash 'f09b5835f3f8b39481f2af3257bbc2e82845552d4d2d6d31cf520fc24263ed5b'.
  2023-10-25T02:29:57Z [init] Error: A fatal internal error occurred, see debug.log for details
  Error: A fatal internal error occurred, see debug.log for details
  2023-10-25T02:29:57Z [init] Shutdown requested. Exiting.
  2023-10-25T02:29:57Z [init] Shutdown: In progress...
  2023-10-25T02:29:57Z [scheduler] scheduler thread exit
  2023-10-25T02:29:57Z [shutoff] Flushed fee estimates to fee_estimates.dat.
  2023-10-25T02:29:57Z [shutoff] Shutdown: done
  ```

  </details>

ACKs for top commit:
  naumenkogs:
    ACK 811067ca1c
  theStack:
    ACK 811067ca1c
  ryanofsky:
    Code review ACK 811067ca1c.

Tree-SHA512: cfc137b0a4f638b99fd7dac2c35cc729ef71ae1166a2a8960a91055ec90841cb33aed589834012cfe0e157937e2a76a88d1020ea1df2bc98e1114eb1fc8eaae4
2023-10-29 10:22:10 +01:00
MarcoFalke
faec889f93
refactor: Add LIFETIMEBOUND to all (w)txid getters
Then, use the compiler warnings to create copies only where needed.

Also, fix iwyu includes while touching the includes.
2023-10-27 13:01:42 +02:00
Andrew Chow
e789b30b25
Merge bitcoin/bitcoin#27116: doc: clarify that LOCK() internally checks whether the mutex is held
91d0888921 sync: unpublish LocksHeld() which is used only in sync.cpp (Vasil Dimov)
3df37e0c78 doc: clarify that LOCK() does AssertLockNotHeld() internally (Vasil Dimov)

Pull request description:

  Constructs like

  ```cpp
  AssertLockNotHeld(m);
  LOCK(m);
  ```

  are equivalent to (almost, modulo some logging differences, see below)

  ```cpp
  LOCK(m);
  ```

  for non-recursive mutexes, so it is ok to omit `AssertLockNotHeld()` in such cases. Requests to do the former keep coming during review process. `developer-notes.md` explicitly states "Combine annotations in function declarations with run-time asserts in function definitions", but that seems to be too strong or unclear. `LOCK()` is also a run-time assert in this case.

  Also remove `LocksHeld()` from the public interface in `sync.h` since it is only used in `sync.cpp`.

ACKs for top commit:
  achow101:
    ACK 91d0888921
  hebasto:
    ACK 91d0888921, I have reviewed the code and it looks OK.

Tree-SHA512: c4b7ef2c0bfeb28d1c4f55f497810f629873137e02f5a92137c02cb1ff603ac76473dcd2171e594491494a5cb87b8c0c803e06b86f190d4acb231791e28e802d
2023-10-26 15:02:13 -04:00
Andrew Chow
7be62df80f
Merge bitcoin/bitcoin#26078: p2p: return CSubNet in LookupSubNet
fb3e812277 p2p: return `CSubNet` in `LookupSubNet` (brunoerg)

Pull request description:

  Analyzing the usage of `LookupSubNet`, noticed that most cases uses check if the subnet is valid by calling `subnet.IsValid()`, and the boolean returned by `LookupSubNet` hasn't been used so much, see:
  29d540b7ad/src/httpserver.cpp (L172-L174)
  29d540b7ad/src/net_permissions.cpp (L114-L116)

  It makes sense to return `CSubNet` instead of `bool`.

ACKs for top commit:
  achow101:
    ACK fb3e812277
  vasild:
    ACK fb3e812277
  theStack:
    Code-review ACK fb3e812277
  stickies-v:
    Concept ACK, but Approach ~0 (for now). Reviewed the code (fb3e812277) and it all looks good to me.

Tree-SHA512: ba50d6bd5d58dfdbe1ce1faebd80dd8cf8c92ac53ef33519860b83399afffab482d5658cb6921b849d7a3df6d5cea911412850e08f3f4e27f7af510fbde4b254
2023-10-26 14:29:47 -04:00
Andrew Chow
5572f98f05
Merge bitcoin/bitcoin#28107: util: Type-safe transaction identifiers
940a49978c Use type-safe txid types in orphanage (dergoegge)
ed70e65016 Introduce types for txids & wtxids (dergoegge)
cdb14d79e8 [net processing] Use HasWitness over comparing (w)txids (dergoegge)

Pull request description:

  We currently have two different identifiers for transactions: `txid` (refering to the hash of a transaction without witness data) and `wtxid` (referring to the hash of a transaction including witness data). Both are typed as `uint256` which could lead to type-safety bugs in which one transaction identifier type is passed where the other would be expected.

  This PR introduces explicit `Txid` and `Wtxid` types that (if used) would cause compilation errors for such type confusion bugs.

  (Only the orphanage is converted to use these types in this PR)

ACKs for top commit:
  achow101:
    ACK 940a49978c
  stickies-v:
    ACK 940a49978c
  hebasto:
    ACK 940a49978c, I have reviewed the code and it looks OK.
  instagibbs:
    re-ACK 940a49978c
  BrandonOdiwuor:
    re-ACK 940a49978c
  glozow:
    reACK 940a49978c

Tree-SHA512: 55298d1c2bb82b7a6995e96e554571c22eaf4a89fb2a4d7a236d70e0f625e8cca62ff2490e1c179c47bd93153fe6527b56870198f026f5ee7753d64d7a424c92
2023-10-26 14:18:55 -04:00
dergoegge
cf70a8d565 [net] Check i2p private key constraints
Co-authored-by: Vasil Dimov <vd@FreeBSD.org>
2023-10-26 16:50:50 +01:00
Andrew Chow
cb8844e2b9
Merge bitcoin/bitcoin#28728: wallet: [bugfix] Mark CNoDestination and PubKeyDestination constructor explicit
1111475b41 bugfix: Mark CNoDestination and PubKeyDestination constructor explicit (MarcoFalke)
fa5ccc4137 iwyu: Export prevector.h from script.h (MarcoFalke)

Pull request description:

  It seems confusing to allow any script, even one with a corresponding address, to silently convert to `CNoDestination`.

  Make the converstion `explicit` in the code, and fix any bugs that were previously introduced.

  In a follow-up, the class can be renamed, or the documentation can be updated to better reflect what the code does.

ACKs for top commit:
  josibake:
    ACK 1111475b41
  achow101:
    ACK 1111475b41
  furszy:
    Code review ACK 1111475

Tree-SHA512: d8b5f54d0cd8649a31e227ef164bb13e5b81ee9820f1976fd70c7a0de6841fba72d549c2f63e351c8cdda37dceb4763eca203e1c8ef385f46d9da6f1855c39ec
2023-10-26 11:14:40 -04:00
MarcoFalke
faa769db5a
Fix bugprone-lambda-function-name errors
Can be reviewed with

--color-moved=dimmed-zebra
2023-10-26 16:58:36 +02:00
MarcoFalke
fa3da629a1
Remove DirIsWritable, GetUniquePath 2023-10-26 10:32:56 +02:00
MarcoFalke
fad3a9793b
Return LockResult::ErrorWrite in LockDirectory
This allows the caller to remove a call to DirIsWritable(), which did a
similar check. Users should not notice any different behavior.
2023-10-26 10:32:47 +02:00
MarcoFalke
fa0afe7408
refactor: Return enum in LockDirectory
This makes it easier to add more Error cases in the future. Also, add
missing util namespace.
2023-10-26 10:25:22 +02:00
MarcoFalke
1111475b41
bugfix: Mark CNoDestination and PubKeyDestination constructor explicit
This should fix the bug reported in
https://github.com/bitcoin/bitcoin/pull/28246#discussion_r1371640502,
which caused the GUI to not detect the destination type of recipients,
thus picking the wrong change destination type.

Also, add missing lifetimebound attribute to a getter method.
2023-10-25 22:46:55 +02:00
Hennadii Stepanov
64879f4c03
Merge bitcoin-core/gui#771: Avoid error-prone leading whitespace in translatable strings
856325fac1 lint: Add `lint-qt-translation.py` (Hennadii Stepanov)
294a018bf5 qt: Avoid error prone leading spaces in translatable strings (Hennadii Stepanov)
d8298e7f06 qt, refactor: Drop superfluous type conversions (Hennadii Stepanov)

Pull request description:

  While working on the GUI translation via Transifex web interface, I found it error-prone to have leading whitespace in translatable strings. This is because it is very easy to unintentionally drop them in translations unnoticed.

  Fixed all current cases. Added a linter to prevent similar cases in the future.

ACKs for top commit:
  furszy:
    utACK 856325f

Tree-SHA512: b1ca5effb2db6649e1e99382de79acf3a9f81cc9dad434db5623338489e597897e8addd60c1ab3dcc7506ae62753a7a4ad5a41d7a865f8fcdf94348b54baa7e7
2023-10-25 13:20:07 +01:00
Hennadii Stepanov
afa081a39b
Merge bitcoin-core/gui#742: Exit and show error if unrecognized command line args are present
51e4dc49f5 gui: Show error if unrecognized command line args are present (John Moffett)

Pull request description:

  Fixes https://github.com/bitcoin-core/gui/issues/741

  Starting bitcoin-qt with non-hyphen ("-") arguments causes it to silently ignore any later valid options. For instance, invoking `bitcoin-qt -server=1 foo -regtest` on a fresh install will run `mainnet` instead of `regtest`.

  This change makes the client exit with an error message if any such "loose" arguments are encountered. This mirrors how `bitcoind` handles it:

  c6287faae4/src/bitcoind.cpp (L127-L132)

  However, BIP-21 `bitcoin:` payment URIs are still allowed, but only if they're not followed by any additional options.

ACKs for top commit:
  maflcko:
    lgtm ACK 51e4dc49f5
  hernanmarino:
    tested ACK 51e4dc49f5
  pablomartin4btc:
    tACK 51e4dc49f5
  hebasto:
    ACK 51e4dc49f5, I have reviewed the code and it looks OK.

Tree-SHA512: 3997a7a9a747314f13e118aee63e8679e00ed832d9c6f115559a4c39c9c4091572207c60e362cb4c19fc8da980d4b0b040050aa70c5ef84a855cb7e3568bbf13
2023-10-25 13:12:59 +01:00
MarcoFalke
fa5ccc4137
iwyu: Export prevector.h from script.h
This should cut some include bloat and seems fine to do, because
prevector exists primarily to represent scripts.

Also, add missing includes to script.h and addresstype.h
2023-10-25 11:55:50 +02:00
pablomartin4btc
4a5be10b92 assumeutxo, blockstorage: prevent core dump on invalid hash 2023-10-24 23:39:10 -03:00
Andrew Chow
517c7f9cba gui: Check for private keys disabled before attempting unlock
Before trying to unlock a wallet, first check if it has private keys
disabled. If so, there is no need to unlock.

Note that such wallets are not expected to occur in typical usage.
However bugs in previous versions allowed such wallets to be created,
and so we need to handle them.
2023-10-24 17:23:36 -04:00
MarcoFalke
fae379b6b1
build: Bump minimum supported Clang to clang-13 2023-10-24 18:52:00 +02:00
TheCharlatan
c1144f0076
tests: Reset node context members on ~BasicTestingSetup
The destruction/resetting of node context members in the tests should
roughly follow the behaviour of the Shutdown function in `init.cpp`.
2023-10-24 08:39:45 +02:00
TheCharlatan
9759af17ff
shutdown: Destroy kernel last
Currently the shutdown function resets the kernel before the
chainman and scheduler. Invert this order by resetting the kernel
last, since they might rely on the kernel.
2023-10-24 08:37:22 +02:00
Ryan Ofsky
f06016d77d wallet: Add asserts to detect unset transaction height values
Also document GetTxDepthInMainChain preconditions better
2023-10-23 17:35:36 -04:00
Ryan Ofsky
d724bb5291
Merge bitcoin/bitcoin#28609: wallet: Reload watchonly and solvables wallets after migration
4814e4063e test: Check tx metadata is migrated to watchonly (Andrew Chow)
d616d30ea5 wallet: Reload watchonly and solvables wallets after migration (Andrew Chow)
118f2d7d70 wallet: Copy all tx metadata to watchonly wallet (Andrew Chow)
9af87cf348 test: Check that a failed wallet migration is cleaned up (Andrew Chow)

Pull request description:

  Some incomplete/incorrect state as a result of migration can be mitigated/cleaned up by simply restarting the migrated wallets. We already do this for a wallet when it is migrated, but we do not for the new watchonly and solvables wallets that may be created. This PR introduces this behavior, in addition to creating those wallets initially without an attached chain.

  While implementing this, I noticed that not all `CWalletTx` metadata was being copied over to the watchonly wallet and so some data, such as time received, was being lost. This PR fixes this as a side effect of not having a chain attached to the watchonly wallet. A test has also been added.

ACKs for top commit:
  ishaanam:
    light code review ACK 4814e4063e
  ryanofsky:
    Code review ACK 4814e4063e. Just implemented the suggested orderpos, copyfrom, and path set comments since last review
  furszy:
    ACK 4814e406

Tree-SHA512: 0b992430df9f452cb252c2212df8e876613f43564fcd1dc00c6c31fa497adb84dfff6b5ef597590f9b288c5f64cb455f108fcc9b6c9d1fe9eb2c39e7f2c12a89
2023-10-23 17:35:36 -04:00
Ryan Ofsky
262a78b133 wallet, refactor: Add CWalletTx::updateState function
No change in behavior, this just moves code which updates transaction state to
a new method so it can be used after offline processes such as wallet
migration.
2023-10-23 17:35:36 -04:00
Andrew Chow
da8e397e4a
Merge bitcoin/bitcoin#28685: coinstats, assumeutxo: fix hash_serialized2 calculation
4bfaad4eca chainparams, assumeutxo: Fix signet txoutset hash (Fabian Jahr)
a503cd0f0b chainparams, assumeutxo: Fix testnet txoutset hash (Fabian Jahr)
f6213929c5 assumeutxo: Check deserialized coins for out of range values (Fabian Jahr)
66865446a7 docs: Add release notes for #28685 (Fabian Jahr)
cb0336817e scripted-diff: Rename hash_serialized_2 to hash_serialized_3 (Fabian Jahr)
351370a1d2 coinstats: Fix hash_serialized2 calculation (Fabian Jahr)

Pull request description:

  Closes #28675

  The last commit demonstrates that theStack's analysis [here](https://github.com/bitcoin/bitcoin/issues/28675#issuecomment-1770389468) seems to be correct. There will be more changes needed for the rest of the test suite but the `feature_assumeutxo.py` with my additional tests pass.

ACKs for top commit:
  achow101:
    ACK 4bfaad4eca
  theStack:
    Code-review ACK 4bfaad4eca
  ryanofsky:
    Code review ACK 4bfaad4eca

Tree-SHA512: 2f6abc92b282f7c5da46391803cf0804d13978d191d541f2509b532c538abccd0a081e46cda23d80d47206a05fa2b5d41b7ab246e6a263db7a7461d6292116ef
2023-10-23 15:16:08 -04:00
Hennadii Stepanov
294a018bf5
qt: Avoid error prone leading spaces in translatable strings 2023-10-23 15:06:42 +01:00
Hennadii Stepanov
d8298e7f06
qt, refactor: Drop superfluous type conversions 2023-10-23 15:06:29 +01:00
Hennadii Stepanov
f09bfab4af
Revert "gui: provide wallet controller context to wallet actions"
This reverts commit 7066e8996d.
2023-10-23 12:14:37 +01:00
fanquake
0046f3dc27
Merge bitcoin/bitcoin#28693: build: Include config/bitcoin-config.h explicitly in util/trace.h
6bdff429ec build: Include `config/bitcoin-config.h` explicitly in `util/trace.h` (Hennadii Stepanov)

Pull request description:

  The `ENABLE_TRACING` macro is expected to be defined in the `config/bitcoin-config.h` header.

  Therefore, the current code is error-prone as it depends on whether the `config/bitcoin-config.h` header was included before or not.

  This bug was noticed while working on CMake [stuff](https://github.com/hebasto/bitcoin/pull/37).

ACKs for top commit:
  fanquake:
    ACK 6bdff429ec

Tree-SHA512: 22c4fdeb51628814050eb99a83db4268a4f3106207eeef918a07214bbc52f2b22490f6b05fcb96216f147afa4197c51102503738131e2583e750b6d195747a49
2023-10-23 11:32:43 +01:00
fanquake
f4e96c29a6
Merge bitcoin/bitcoin#28691: refactor: Remove CBlockFileInfo::SetNull
fac36b94ef refactor: Remove CBlockFileInfo::SetNull (MarcoFalke)

Pull request description:

  Seems better to use C++11 member initializers and then let the compiler figure out how to construct objects of this class.

ACKs for top commit:
  stickies-v:
    ACK fac36b94ef
  pablomartin4btc:
    ACK fac36b94ef
  theStack:
    LGTM ACK fac36b94ef

Tree-SHA512: aee741c8f668f0e5b658fc83f4ebd196b43fead3dd437afdb0a2dafe092ae3d559332b3d9d61985c92e1a59982d8f24942606e6a98598c6ef7ff43697e858725
2023-10-23 10:37:27 +01:00
Fabian Jahr
4bfaad4eca
chainparams, assumeutxo: Fix signet txoutset hash
Review hint: You can use devtools/utxo_snapshot.sh to validate this.

./contrib/devtools/utxo_snapshot.sh 160000 signet-utxo.dat ./src/bitcoin-cli
2023-10-20 22:53:07 +02:00
Fabian Jahr
a503cd0f0b
chainparams, assumeutxo: Fix testnet txoutset hash
Review hint: You can use devtools/utxo_snapshot.sh to validate this.

./contrib/devtools/utxo_snapshot.sh 2500000 testnet-utxo.dat ./src/bitcoin-cli
2023-10-20 22:53:07 +02:00
Fabian Jahr
f6213929c5
assumeutxo: Check deserialized coins for out of range values 2023-10-20 22:53:07 +02:00
Fabian Jahr
cb0336817e
scripted-diff: Rename hash_serialized_2 to hash_serialized_3
-BEGIN VERIFY SCRIPT-
sed -i 's/hash_serialized_2/hash_serialized_3/g' $( git grep -l 'hash_serialized_2' ./src ./contrib ./test )
-END VERIFY SCRIPT-
2023-10-20 22:53:06 +02:00
Fabian Jahr
351370a1d2
coinstats: Fix hash_serialized2 calculation
The legacy serialization was vulnerable to maleation and is fixed by
adopting the same serialization procedure as was already in use for
MuHash.

This also includes necessary test fixes where the hash_serialized2 was
hardcoded as well as correction of the regtest chainparams.

Co-authored-by: Sebastian Falbesoner <sebastian.falbesoner@gmail.com>
2023-10-20 22:53:05 +02:00
fanquake
abfc8c901d
Merge bitcoin/bitcoin#28692: fuzz: Delete i2p fuzz test
dd4dcbd4cd [fuzz] Delete i2p target (dergoegge)

Pull request description:

  closes #28665

  The target is buggy and doesn't reach basic coverage.

ACKs for top commit:
  maflcko:
    lgtm ACK dd4dcbd4cd
  glozow:
    ACK dd4dcbd4cd, agree it's better to delete this test until somebody wants to write a better one

Tree-SHA512: b6ca6cad1773b1ceb6e5ac0fd501ea615f66507ef811745799deaaa4460f1700d96ae03cf55b740a96ed8cd2283b3d6738cd580ba97f2af619197d6c4414ca21
2023-10-20 15:30:16 +01:00
Ryan Ofsky
6d43aad742 span: Make Span template deduction guides work in SFINAE context
Also add test to make sure this doesn't get broken in the future.

This was breaking vector<bool> serialization in multiprocess code because
template current deduction guides would make it appear like vector<bool> could
be converted to a span, but then the actual conversion to span would fail.
2023-10-20 10:30:16 -04:00
Ryan Ofsky
8062c3bdb9 util: Add ArgsManager SetConfigFilePath method
Needed by multiprocess support code to pass parsed configuration to a spawned process.
2023-10-20 10:30:16 -04:00
Ryan Ofsky
441d00c60f interfaces: Rename CalculateBumpFees methods to be compatible with capn'proto 2023-10-20 10:30:16 -04:00
Ryan Ofsky
156f49d682 interfaces: Change getUnspentOutput return type to avoid multiprocess segfault
Coin serialize method segfaults if IsSpent condition is true. This caused
multiprocess code to segfault when serializing the Coin& output argument to of
the Node::getUnspentOutput method if the coin was not found. Segfault could be
triggered by double clicking and viewing transaction details in the GUI
transaction list.

Fix this by replacing Coin& output argument with optional<Coin> return value to
avoid trying to serializing spent coins.
2023-10-20 10:30:16 -04:00
Ryan Ofsky
4978754c00 interfaces: Add schedulerMockForward method so mockscheduler RPC can work across processes
Needed to fix new wallet_groups.py and wallet_resendwallettransactions.py tests
with multiprocess bitcoin-node executable.
2023-10-20 10:30:16 -04:00
Ryan Ofsky
924327eaf3 interfaces: Fix const virtual method that breaks multiprocess support 2023-10-20 10:30:16 -04:00
Russell Yanofsky
82a379eca8 streams: Add SpanReader ignore method
Needed to deserialize some types from spans like CScripts
2023-10-20 09:30:16 -05:00
MarcoFalke
fac36b94ef
refactor: Remove CBlockFileInfo::SetNull 2023-10-20 16:29:02 +02:00
Hennadii Stepanov
6bdff429ec
build: Include config/bitcoin-config.h explicitly in util/trace.h
The `ENABLE_TRACING` macro is expected to be defined in the
`config/bitcoin-config.h` header.

Therefore, the current code is error-prone as it depends on whether the
`config/bitcoin-config.h` header was included before or not.
2023-10-20 14:40:26 +01:00
fanquake
3c856e2fe8
Merge bitcoin/bitcoin#28569: log: Don't log cache rebalancing in absense of a snapshot chainstate
ec84f999f1 log: Don't log cache rebalancing in absense of a snapshot chainstate (Fabian Jahr)

Pull request description:

  I have noticed that this log now is always printed, even if there is no snapshot chainstate present or even was present. I think this is confusing to users that have never even thought about using assumeutxo since in that case the rebalancing is just ensuring the normal environment with one chainstate. So I suggest we don't log in absence of a snapshot chainstate. We could also think about rewording the message instead but I think this is simpler.

ACKs for top commit:
  stickies-v:
    utACK ec84f999f1
  glozow:
    concept ACK ec84f999f1, don't have opinions other than removing confusing log
  theStack:
    utACK ec84f999f1

Tree-SHA512: 30bbfc648e7c788106f78d52e47a3aa1e1874f65d13743643dc50bcf7f450d8330711ff9fdeac361722542da6051533153829c6d49033227ed315e111afc899f
2023-10-20 14:39:34 +01:00
dergoegge
dd4dcbd4cd [fuzz] Delete i2p target 2023-10-20 14:03:34 +01:00
Fabian Jahr
ec84f999f1
log: Don't log cache rebalancing in absense of a snapshot chainstate 2023-10-20 14:53:44 +02:00
Andrew Chow
d616d30ea5 wallet: Reload watchonly and solvables wallets after migration
When migrating, create the watchonly and solvables wallets without a
context. Then unload and reload them after migration completes, as we do
for the actual wallet.

There is also additional handling for a failed reload.
2023-10-19 18:06:43 -04:00
Andrew Chow
118f2d7d70 wallet: Copy all tx metadata to watchonly wallet
When moving a tx to the watchonly wallet during migration, make sure
that all of the CWalletTx data follows it.
2023-10-19 18:06:43 -04:00
Andrew Chow
77f0ceb717
Merge bitcoin/bitcoin#28077: I2P: also sleep after errors in Accept() & destroy the session if we get an unexpected error
5c8e15c451 i2p: destroy the session if we get an unexpected error from the I2P router (Vasil Dimov)
762404a68c i2p: also sleep after errors in Accept() (Vasil Dimov)

Pull request description:

  ### Background

  In the `i2p::sam::Session` class:

  `Listen()` does:
  * if the session is not created yet
    * create the control socket and on it:
    * `HELLO`
    * `SESSION CREATE ID=sessid`
    * leave the control socked opened
  * create a new socket and on it:
  * `HELLO`
  * `STREAM ACCEPT ID=sessid`
  * read reply (`STREAM STATUS`), `Listen()` only succeeds if it contains `RESULT=OK`

  Then a wait starts, for a peer to connect. When connected,

  `Accept()` does:
  * on the socket from `STREAM ACCEPT` from `Listen()`: read the Base64 identification of the connecting peer

  ### Problem

  The I2P router may be in such a state that this happens in a quick succession (many times per second, see https://github.com/bitcoin/bitcoin/issues/22759#issuecomment-1609907115): `Listen()`-succeeds, `Accept()`-fails.

  `Accept()` fails because the I2P router sends something that is not Base64 on the socket: `STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"`

  We only sleep after failed `Listen()` because the assumption was that if `Accept()` fails then the next `Listen()` will also fail.

  ### Solution

  Avoid filling the log with "Error accepting:" messages and sleep also after a failed `Accept()`.

  ### Extra changes

  * Reset the error waiting time after one successful connection. Otherwise the timer will remain high due to problems that have been solved long time in the past.

  * Increment the wait time less aggressively.

  * Handle the unexpected "Session was closed" message more gracefully (don't log stupid messages like `Cannot decode Base64: "STREAM STATUS...`) and destroy the session right way.

ACKs for top commit:
  achow101:
    ACK 5c8e15c451
  jonatack:
    re-ACK 5c8e15c451

Tree-SHA512: 1d47958c50eeae9eefcb668b8539fd092adead93328e4bf3355267819304b99ab41cbe1b5dbedbc3452c2bc389dc8330c0e27eb5ccb880e33dc46930a1592885
2023-10-19 16:08:06 -04:00
Andrew Chow
0655e9dd92
Merge bitcoin/bitcoin#27071: Handle CJDNS from LookupSubNet()
0e6f6ebc06 net: remove unused CConnman::FindNode(const CSubNet&) (Vasil Dimov)
9482cb780f netbase: possibly change the result of LookupSubNet() to CJDNS (Vasil Dimov)
53afa68026 net: move MaybeFlipIPv6toCJDNS() from net to netbase (Vasil Dimov)
6e308651c4 net: move IsReachable() code to netbase and encapsulate it (Vasil Dimov)
c42ded3d9b fuzz: ConsumeNetAddr(): avoid IPv6 addresses that look like CJDNS (Vasil Dimov)
64d6f77907 net: put CJDNS prefix byte in a constant (Vasil Dimov)

Pull request description:

  `LookupSubNet()` would treat addresses that start with `fc` as IPv6 even if `-cjdnsreachable` is set. This creates the following problems where it is called:

  * `NetWhitelistPermissions::TryParse()`: otherwise `-whitelist=` fails to white list CJDNS addresses: when a CJDNS peer connects to us, it will be matched against IPv6 `fc...` subnet and the match will never succeed.

  * `BanMapFromJson()`: CJDNS bans are stored as just IPv6 addresses in `banlist.json`. Upon reading from disk they have to be converted back to CJDNS, otherwise, after restart, a ban entry like (`fc00::1`, IPv6) would not match a peer (`fc00::1`, CJDNS).

  * `RPCConsole::unbanSelectedNode()`: in the GUI the ban entries go through `CSubNet::ToString()` and back via `LookupSubNet()`. Then it must match whatever is stored in `BanMan`, otherwise it is impossible to unban via the GUI.

  These were uncovered by https://github.com/bitcoin/bitcoin/pull/26859.

  Thus, flip the result of `LookupSubNet()` to CJDNS if the network base address starts with `fc` and `-cjdnsreachable` is set. Since subnetting/masking does not make sense for CJDNS (the address is "random" bytes, like Tor and I2P, there is no hierarchy) treat `fc.../mask` as an invalid `CSubNet`.

  To achieve that, `MaybeFlipIPv6toCJDNS()` has to be moved from `net` to `netbase` and thus also `IsReachable()`. In the process of moving `IsReachable()`, `SetReachable()` and `vfLimited[]` encapsulate those in a class.

ACKs for top commit:
  jonatack:
    Code review ACK 0e6f6ebc06
  achow101:
    ACK 0e6f6ebc06
  mzumsande:
    re-ACK 0e6f6ebc06

Tree-SHA512: 4767a60dc882916de4c8b110ce8de208ff3f58daaa0b560e6547d72e604d07c4157e72cf98b237228310fc05c0a3922f446674492e2ba02e990a272d288bd566
2023-10-19 12:48:39 -04:00
glozow
9b3da70bd0 [test] DisconnectedBlockTransactions::DynamicMemoryUsage 2023-10-19 16:14:36 +01:00
stickies-v
b2d0447964 bugfix: correct DisconnectedBlockTransactions memory usage
With `queuedTx` owning the `CTransactionRef` shared ptrs, they (and
the managed objects) are entirely allocated on the heap. In
`DisconnectedBlockTransactions::DynamicMemoryUsage`, we account for
the 2 pointers that make up the shared_ptr, but not for the managed
object (CTransaction) or the control block.

Prior to this commit, by calculating the `RecursiveDynamicUsage` on
a `CTransaction` whenever modifying `cachedInnerUsage`, we account
for the dynamic usage of the `CTransaction`, i.e. the `vins` and
`vouts` vectors, but we do not account for the `CTransaction`
object itself, nor for the `CTransactionRef` control block.

This means prior to this commit, `DynamicMemoryUsage` underestimates
dynamic memory usage by not including the `CTransaction` objects and
the shared ptr control blocks.

Fix this by calculating `RecursiveDynamicUsage` on the
`CTransactionRef` instead of the `CTransaction` whenever modifying
`cachedInnerUsage`.
2023-10-19 16:14:36 +01:00
Andrew Chow
f1684bb88a rpc: mention that migratewallet can take a while 2023-10-19 09:58:16 -04:00
fanquake
9e616baec0
Merge bitcoin/bitcoin#22764: build: Include qt sources for parsing with extract_strings.py
b59b31ae0b build: Drop redundant qt/bitcoin.cpp (Hennadii Stepanov)
d90ad5a42e build: Include qt sources for parsing with extract_strings.py (Hennadii Stepanov)

Pull request description:

  On master (4fc15d1566) some strings are still untranslated.

  This PR fixes this issue.

  To verify:
  1) `./autogen.sh && ./configure && make -C src translate` _before_ applying this change
  2) apply this change
  3) `./autogen.sh && ./configure && make -C src translate` _after_ applying this change

  The result of `git diff src/qt/bitcoinstrings.cpp`:
  ```diff
  --- a/src/qt/bitcoinstrings.cpp
  +++ b/src/qt/bitcoinstrings.cpp
  @@ -126,6 +126,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", ""
   "You need to rebuild the database using -reindex to go back to unpruned "
   "mode.  This will redownload the entire blockchain"),
   QT_TRANSLATE_NOOP("bitcoin-core", "%s is set very high!"),
  +QT_TRANSLATE_NOOP("bitcoin-core", "(press q to shutdown and continue later)"),
   QT_TRANSLATE_NOOP("bitcoin-core", "-maxmempool must be at least %d MB"),
   QT_TRANSLATE_NOOP("bitcoin-core", "A fatal internal error occurred, see debug.log for details"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -%s address: '%s'"),
  @@ -204,6 +205,8 @@ QT_TRANSLATE_NOOP("bitcoin-core", "SQLiteDatabase: Failed to prepare statement t
   QT_TRANSLATE_NOOP("bitcoin-core", "SQLiteDatabase: Failed to read database verification error: %s"),
   QT_TRANSLATE_NOOP("bitcoin-core", "SQLiteDatabase: Unexpected application id. Expected %u, got %u"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Section [%s] is not recognized."),
  +QT_TRANSLATE_NOOP("bitcoin-core", "Settings file could not be read"),
  +QT_TRANSLATE_NOOP("bitcoin-core", "Settings file could not be written"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Specified -walletdir \"%s\" does not exist"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Specified -walletdir \"%s\" is a relative path"),
  @@ -242,4 +245,5 @@ QT_TRANSLATE_NOOP("bitcoin-core", "User Agent comment (%s) contains unsafe chara
   QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks…"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet(s)…"),
   QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart %s to complete"),
  +QT_TRANSLATE_NOOP("bitcoin-core", "press q to shutdown"),
   };
  ```

ACKs for top commit:
  ryanofsky:
    Code review ACK b59b31ae0b. Being able to use `_()` macro in qt would allow simplifying some code, for example replacing repetitive:
  TheCharlatan:
    ACK b59b31ae0b

Tree-SHA512: 13d9d86b487a1b6e718ae96c198a0a927c881bf33df318412793ec9efba3a7e59cfa836204f73f5b53ff4c99edce778c11bffaa88138b80e37b71e36df6b816f
2023-10-19 13:25:49 +01:00
ismaelsadeeq
f4254e2098 assume duplicate transactions are not added to iters_by_txid
In `AddTransactionsToBlock` description comment we have the asuumption
that callers will never pass multiple transactions with the same txid
We are asserting to assume that does not happen.
2023-10-18 15:31:51 +01:00
ismaelsadeeq
29eb219c12 move only: move implementation code to disconnected_transactions.cpp 2023-10-18 15:26:19 +01:00
Andrew Chow
c2d4e40e45
Merge bitcoin/bitcoin#28651: Make miniscript GetWitnessSize accurate for tapscript
b22810887b miniscript: make GetWitnessSize accurate for tapscript (Pieter Wuille)
8be9851408 test: add tests for miniscript GetWitnessSize (Pieter Wuille)
7ed2b2d430 test: remove mutable global contexts in miniscript fuzzer/test (Pieter Wuille)

Pull request description:

  So far, the same algorithm is used to compute an (upper bound on) the maximum witness size for both P2WSH and P2TR miniscript. That's unfortunate, because it means fee estimations for P2TR miniscript will miss out on the generic savings brought by P2TR witnesses (smaller signatures and public keys, specifically).

  Fix this by making the algorithm use script context specification calculations, and add tests for it. Also included is a cleanup for the tests to avoid mutable globals, as I found it hard to reason about what exactly was being tested.

ACKs for top commit:
  achow101:
    ACK b22810887b
  darosior:
    ACK b22810887b

Tree-SHA512: e4bda7376628f3e91cfc74917cefc554ca16eb5f2a0e1adddc33eb8717c4aaa071e56a40f85a2041ae74ec445a7bd0129bba48994c203e0e6e4d25af65954d9e
2023-10-17 18:27:52 -04:00
Hennadii Stepanov
9c30f5ef9d
Merge bitcoin-core/gui#766: Fix coin control input size accounting for taproot spends
00a52e6394 gui: fix coin control input size accounting for taproot spends (Sebastian Falbesoner)

Pull request description:

  If manual coin control is used in the GUI, the input size accounting for P2TR is currently overshooting, as it still assumes P2WPKH (segwitv0) spends which have a larger witness, as ECDSA signatures are longer and the pubkey also has to be provided. Fix that by adding sizes depending on the witness version. Note that the total accounting including outputs is still off and there is some weird logic involved depending on whether SFFO is used, but it's (hopefully) a first step into the right direction.

ACKs for top commit:
  maflcko:
    lgtm ACK 00a52e6394
  furszy:
    utACK 00a52e6394

Tree-SHA512: 9633642f8473247cc3d8e6e0ef502fd515e1dde0e2939d28d6754d0cececedd6a328df22a3d4c85eb2846fd0417cf224b92594613f6e84ada82d2d7d84fc455f
2023-10-17 22:26:25 +01:00
Andrew Chow
fbcf1029a7
Merge bitcoin/bitcoin#28544: wallet: Add TxStateString function for debugging and logging
8a553c9409 wallet: Add TxStateString function for debugging and logging (Ryan Ofsky)

Pull request description:

  I found this useful while debugging silent conflict between #10102 and #27469 recently

ACKs for top commit:
  ishaanam:
    utACK 8a553c9409
  achow101:
    ACK 8a553c9409
  furszy:
    Code ACK 8a553c9

Tree-SHA512: 87965c66bcb59a21e7639878bb567e583a0e624735721ff7ad1104eed6bb9fba60607d0e3de7be3304232b3a55f48bab7039ea9c26b0e81963e59f9acd94f666
2023-10-17 15:28:05 -04:00
fanquake
738ef44abb
Merge bitcoin/bitcoin#28652: assumeutxo: fail early if snapshot block hash doesn't match AssumeUTXO parameters
9620cb4493 assumeutxo: fail early if snapshot block hash doesn't match AssumeUTXO parameters (Sebastian Falbesoner)

Pull request description:

  Right now the `loadtxoutset` RPC call treats literally all files with a minimum size of 40 bytes (=size of metadata) as potential valid snapshot candidates and the waiting loop for seeing the metadata block hash in the headers chain is always entered, e.g.:
  ```
  $ ./src/bitcoin-cli loadtxoutset ~/.vimrc
  <wait>

  bitcoind log:
  ...
  2023-10-15T14:55:45Z [snapshot] waiting to see blockheader 626174207465730a7265626d756e207465730a656c62616e65207861746e7973 in headers chain before snapshot activation
  ...
  ```
  There is no point in doing any further action though if we already know from the start that the UTXO snapshot loading won't be successful. This PR adds an assumeutxo parameter check immediately after the metadata is read in, so we can fail immediately on a mismatch:
  ```
  $ ./src/bitcoin-cli loadtxoutset ~/.vimrc
  error code: -32603
  error message:
  Unable to load UTXO snapshot, assumeutxo block hash in snapshot metadata not recognized (626174207465730a7265626d756e207465730a656c62616e
  65207861746e7973)
  ```
  This way, users who mistakenly try to load files that are not snapshots don't have to wait 10 minutes (=the block header waiting timeout) anymore to get a negative response. If a file is loaded which is a valid snapshot (referencing to an existing block hash), but one which doesn't match the parameters, the feedback is also faster, as we don't have to wait anymore to see the hash in the headers chain before getting an error.

  This is also partially fixes #28621.

ACKs for top commit:
  maflcko:
    lgtm ACK 9620cb4493
  ryanofsky:
    Code review ACK 9620cb4493. This should fix an annoyance and bad UX.
  pablomartin4btc:
    tACK 9620cb4493

Tree-SHA512: f88b865e9d46254858e57c024463f389cd9d8760a7cb30c190aa1723a931e159987dfc2263a733825d700fa612e7416691e4d8aab64058f1aeb0a7fa9233ac9c
2023-10-17 10:20:08 +01:00
Andrew Chow
90f7d8a7f9
Merge bitcoin/bitcoin#28539: lib: add taproot support to libconsensus
ff8e2fc2e2 fuzz: add coverage for `bitcoinconsensus_verify_script_with_spent_outputs` (brunoerg)
c5f2a757d7 docs: add release notes for #28539 (brunoerg)
de54882348 docs: add docs for additional libconsensus functions (Jake Rawsthorne)
70106e0689 docs: link to rust-bitcoinconsensus (Jake Rawsthorne)
fb0db07e41 lib: add Taproot support to libconsensus (Jake Rawsthorne)

Pull request description:

  Grabbed from #21158. Closes #21133.

ACKs for top commit:
  achow101:
    ACK ff8e2fc2e2
  theStack:
    ACK ff8e2fc2e2
  darosior:
    re-ACK ff8e2fc2e2

Tree-SHA512: bf6f500c7e8c9ff6884137c2cd9b4522c586e52848dd639b774b94d998b0516b877498d24f3a6cc7425aedf81d18b0d30c1ccf19e2d527fdfdfa3955ca49b6e7
2023-10-16 12:59:39 -04:00
Sebastian Falbesoner
9620cb4493 assumeutxo: fail early if snapshot block hash doesn't match AssumeUTXO parameters 2023-10-16 17:20:59 +02:00
fanquake
08ea835220
Merge bitcoin/bitcoin#28583: refactor: [tidy] modernize-use-emplace
fa05a726c2 tidy: modernize-use-emplace (MarcoFalke)

Pull request description:

  Constructing a temporary unnamed object only to copy or move it into a container seems both verbose in code and a strict performance penalty.

  Fix both issues via the `modernize-use-emplace` tidy check.

ACKs for top commit:
  Sjors:
    re-utACK fa05a726c2
  hebasto:
    ACK fa05a726c2.
  TheCharlatan:
    ACK fa05a726c2

Tree-SHA512: 4408a094f406e7bf6c1468c2b0798f68f4d952a1253cf5b20bdc648ad7eea4a2c070051fed46d66fd37bce2ce6f85962484a1d32826b7ab8c9baba431eaa2765
2023-10-16 15:35:50 +01:00
Hennadii Stepanov
92704535f6
Merge bitcoin-core/gui#765: Fix wallet list hover crash on shutdown
8b6470a906 gui: disable top bar menu actions during shutdown (furszy)
7066e8996d gui: provide wallet controller context to wallet actions (furszy)

Pull request description:

  Small follow-up to #751.

  Fixes another crash cause during shutdown. Which occurs when the user hovers over the wallets list.

  Future Note:
  This surely happen in other places as well, we should re-work the way we connect signals. Register
  lambas without any precaution can leave dangling pointers.

ACKs for top commit:
  hebasto:
    ACK 8b6470a906, I've tested each commit separately on macOS Sonoma 14.0 (Apple M1).

Tree-SHA512: 6fbd1bcd6717a8c1633beb9371463ed22422f929cccf9b791ee292c5364134c501e099329cf77a06b74a84c64c1c3d22539199ec49ccd74b3950036316c0dab3
2023-10-16 13:37:35 +01:00
MarcoFalke
fa1a384706
Move compat.h include from system.h to system.cpp 2023-10-16 14:34:30 +02:00
Vasil Dimov
0e6f6ebc06
net: remove unused CConnman::FindNode(const CSubNet&) 2023-10-16 12:59:47 +02:00
Vasil Dimov
9482cb780f
netbase: possibly change the result of LookupSubNet() to CJDNS
All callers of `LookupSubNet()` need the result to be of CJDNS type if
`-cjdnsreachable` is set and the address begins with `fc`:

* `NetWhitelistPermissions::TryParse()`: otherwise `-whitelist=` fails
  to white list CJDNS addresses: when a CJDNS peer connects to us, it
  will be matched against IPv6 `fc...` subnet and the match will never
  succeed.

* `BanMapFromJson()`: CJDNS bans are stored as just IPv6 addresses in
  `banlist.json`. Upon reading from disk they have to be converted back
  to CJDNS, otherwise, after restart, a ban entry like (`fc00::1`, IPv6)
  would not match a peer (`fc00::1`, CJDNS).

* `setban()` (in `rpc/net.cpp`): otherwise `setban fc.../mask add` would
  add an IPv6 entry to BanMan. Subnetting does not make sense for CJDNS
  addresses, thus treat `fc.../mask` as invalid `CSubNet`. The result of
  `LookupHost()` has to be converted for the case of banning a single
  host.

* `InitHTTPAllowList()`: not necessary since before this change
  `-rpcallowip=fc...` would match IPv6 subnets against IPv6 peers even
  if they started with `fc`. But because it is necessary for the above,
  `HTTPRequest::GetPeer()` also has to be adjusted to return CJDNS peer,
  so that now CJDNS peers are matched against CJDNS subnets.
2023-10-16 12:57:49 +02:00
fanquake
22fa1f4702
Merge bitcoin/bitcoin#28565: rpc: getaddrmaninfo followups
e6e444c06c refactor: add and use EnsureAnyAddrman in rpc (stratospher)
bf589a50a0 doc: add release notes for #27511 (stratospher)
3931e6abc3 rpc: `getaddrmaninfo` followups (stratospher)

Pull request description:

  - make `getaddrmaninfo` RPC public since it's not for development purposes only and regular users might find it useful. [#26988 (comment)](https://github.com/bitcoin/bitcoin/pull/26988#issuecomment-1738371584)
  - add missing `all_networks` key to RPC help. [#27511 (comment)](https://github.com/bitcoin/bitcoin/pull/27511#discussion_r1335084087)
  - fix clang format spacing
  - add and use `EnsureAddrman` in RPC code. [#27511 (comment)](https://github.com/bitcoin/bitcoin/pull/27511#discussion_r1331501491)

ACKs for top commit:
  0xB10C:
    Code Review re-ACK e6e444c06c
  theStack:
    Code-review ACK e6e444c06c
  pablomartin4btc:
    tested ACK e6e444c06c

Tree-SHA512: c14090d5c64ff15e92d252578de2437bb2ce2e1e431d6698580241a29190f0a3528ae5b013c0ddb76a9ae538507191295c37cab7fd93469941cadbde44587072
2023-10-16 11:21:45 +02:00
furszy
8b6470a906
gui: disable top bar menu actions during shutdown
Opening the top bar menu when the app is being destroyed
freezes the GUI shutdown process for no reason. No menu
action can be executed.

Note:
This behavior is consistent with how the tray icon menu
is cleared too.
2023-10-13 17:40:32 -03:00
furszy
7066e8996d
gui: provide wallet controller context to wallet actions
Addressing potential crashes during shutdown. The most
noticeable one can be triggered by hovering over the
wallet list as the app shuts down.
2023-10-13 17:40:32 -03:00
Pieter Wuille
b22810887b miniscript: make GetWitnessSize accurate for tapscript 2023-10-13 15:28:38 -04:00
Pieter Wuille
8be9851408 test: add tests for miniscript GetWitnessSize 2023-10-13 14:57:03 -04:00
Pieter Wuille
7ed2b2d430 test: remove mutable global contexts in miniscript fuzzer/test 2023-10-13 14:34:02 -04:00
ismaelsadeeq
81dfeddea7 refactor: update MAX_DISCONNECTED_TX_POOL from kb to bytes 2023-10-13 14:25:37 +01:00
brunoerg
ff8e2fc2e2 fuzz: add coverage for bitcoinconsensus_verify_script_with_spent_outputs
Co-authored-by: Antonie Poinsot <darosior@protonmail.com>
2023-10-13 08:55:12 -03:00
Jake Rawsthorne
fb0db07e41 lib: add Taproot support to libconsensus
Co-authored-by: Bruno Garcia <brunoely.gc@gmail.com>
2023-10-13 08:55:07 -03:00
fanquake
448790c00a
Merge bitcoin/bitcoin#28639: refactor: Remove unused nchaintx from SnapshotMetadata constructor, fix test, add test
fafde92f84 test: Check snapshot file with wrong number of coins (MarcoFalke)
faa90f6e7b refactor: Remove unused nchaintx from SnapshotMetadata constructor (MarcoFalke)

Pull request description:

  See commit messages

ACKs for top commit:
  Sjors:
    utACK fafde92f84
  theStack:
    ACK fafde92f84

Tree-SHA512: 9ed2720b50d1c0938f30543ba143e1a4c6af3a0ff166f8b3eb452e1d99ddee6e3443a4c99f77efe94b8c3eb2feff984bf5259807ee8085e1e0e1e0d1de98227e
2023-10-13 11:14:54 +02:00
MarcoFalke
ffffb4af83
scripted-diff: Use ser params operator
-BEGIN VERIFY SCRIPT-
 sed -i 's|WithParams(\([a-zA-Z:._]\+\), |\1(|g' $( git grep -l WithParams )
-END VERIFY SCRIPT-
2023-10-13 10:30:49 +02:00
MarcoFalke
fae9054793
test: Use SER_PARAMS_OPFUNC in serialize_tests.cpp 2023-10-13 10:30:42 +02:00
dergoegge
940a49978c Use type-safe txid types in orphanage 2023-10-12 11:56:37 +01:00
dergoegge
ed70e65016 Introduce types for txids & wtxids 2023-10-12 11:56:37 +01:00
Hennadii Stepanov
79789ccafe
ci: Drop no longer needed NOLINTNEXTLINE 2023-10-12 11:01:47 +01:00
MarcoFalke
fa05a726c2
tidy: modernize-use-emplace 2023-10-12 11:27:19 +02:00
MarcoFalke
faa90f6e7b
refactor: Remove unused nchaintx from SnapshotMetadata constructor
Also, remove wrong nChainTx comment and cast.
2023-10-12 11:14:32 +02:00
fanquake
744157ef1a
Merge bitcoin/bitcoin#28602: descriptors: Disallow hybrid and uncompressed keys when inferring
74c77825e5 test: Unit test for inferring scripts with hybrid and uncompressed keys (Andrew Chow)
f895f97014 test: Scripts with hybrid pubkeys are migrated to watchonly (Andrew Chow)
37b9b73477 descriptors: Move InferScript's pubkey validity checks to InferPubkey (Andrew Chow)
b7485f11ab descriptors: Check result of InferPubkey (Andrew Chow)

Pull request description:

  `InferDescriptor` was not always checking that the pubkey it was placing into the descriptor was an allowed pubkey. For example, given a P2WPKH script that uses an uncompressed pubkey, it would produce a `wpkh()` with the uncompressed key. Additionally, the hybrid key check was only being done for `pk()` scripts, where it should've been done for all scripts.

  This PR moves the key checking into `InferPubkey`. If the key is not valid for the context, then `nullptr` is returned and the inferring will fall through to the defaults of either `raw()` or `addr()`.

  This also resolves an issue with migrating legacy wallets that contain hybrid pubkeys as such watchonly scripts will become `raw()` or `addr()` and go to the watchonly wallet. Note that a legacy wallet cannot sign for hybrid pubkeys. A test has been added for the migration case.

  Also added unit tests for `InferDescriptor` itself as the edge cases with that function are not covered by the descriptor roundtrip test.

ACKs for top commit:
  furszy:
    ACK 74c77825
  Sjors:
    utACK 74c77825e5

Tree-SHA512: ed5f63e42a2e46120245a6b0288b90d2a6912860814c6c08fe393332add1cb364dc5eca72f16980352143570aef0c07bf1a91acd294099463bd028b6ce2fe40c
2023-10-11 12:50:43 +02:00
fanquake
8735e2c136
ci: use LLVM/Clang 17 in tidy job 2023-10-10 11:02:10 +01:00
Andrew Chow
04265ba937
Merge bitcoin/bitcoin#26331: Implement CCoinsViewErrorCatcher::HaveCoin and check disk space periodically
ed52e71176 Periodically check disk space to avoid corruption (Aurèle Oulès)
7fe537f7a4 Implement CCoinsViewErrorCatcher::HaveCoin (Aurèle Oulès)

Pull request description:

  Attempt to fix #26112.

  As suggested by sipa in https://github.com/bitcoin/bitcoin/issues/26112#issuecomment-1249683401:
  > CCoinsViewErrorCatcher, the wrapper class used around CCoinsViewDB that's supposed to detect these problems and forcefully exit the application, has an override for GetCoins. But in CheckTxInputs, HaveInputs is first invoked, which on its turn calls HaveCoin. HaveCoin is implemented in CCoinsViewDB, but not in CCoinsViewErrorCatcher, and thus the disk read exception escapes.
  > A solution may be to just add an override for HaveCoin in CCoinsViewErrorCatcher.

  I implemented `CCoinsViewErrorCatcher::HaveCoin` and also added a periodic disk space check that shutdowns the node if there is not enough space left on disk, the minimum here is 50MB.

  For reviewers, it's possible to saturate disk space to test the PR by creating large files with `fallocate -l 50G test.bin`

ACKs for top commit:
  achow101:
    ACK ed52e71176
  w0xlt:
    Code Review ACK ed52e71176
  sipa:
    utACK ed52e71176

Tree-SHA512: 456aa7b996023df42b4fbb5158ee429d9abf7374b7b1ec129b21aea1188ad19be8da4ae8e0edd90b85b7a3042b8e44e17d3742e33808a4234d5ddbe9bcef1b78
2023-10-09 14:52:00 -04:00
Andrew Chow
74c77825e5 test: Unit test for inferring scripts with hybrid and uncompressed keys 2023-10-09 14:07:37 -04:00
Andrew Chow
37b9b73477 descriptors: Move InferScript's pubkey validity checks to InferPubkey 2023-10-09 14:07:37 -04:00
Andrew Chow
b7485f11ab descriptors: Check result of InferPubkey
InferPubkey can return a nullptr, so check it's result before continuing
with creating the inferred descriptor.
2023-10-09 14:07:37 -04:00
fanquake
3003861e78
Merge bitcoin/bitcoin#28591: kernel: chainparams updates for 26.x
bd71f03df7 doc: update example pulls in release-process.md (fanquake)
b2ede22395 headerssync: update params for 26.x (fanquake)
f12f92b813 kernel: update m_assumed_* chain params for 26.x (fanquake)
a8c2e5e556 kernel: update chainTxData for 26.x (fanquake)
a9d070a6f8 kernel: update nMinimumChainWork & defaultAssumeValid for 26.x (fanquake)

Pull request description:

  Update chainparams pre `26.x` branch off.

  Note: Remember that some variance is expected in the m_assumed_* sizes.

  Closes #28572.

ACKs for top commit:
  Sjors:
    re-ACK bd71f03df7
  ajtowns:
    reACK bd71f03df7
  darosior:
    re-ACK bd71f03df7 for assumevalid and minchainwork params.

Tree-SHA512: c586b82711477bfc1fd9ac4c9c1130ccde29f75d652492c66ef5730f4a49b7da822a3ad2d9090468ea0c9f0e77d00c25f6a800600c81878d8141ce2ffb3724af
2023-10-09 14:54:08 +01:00
fanquake
66f8ee2969
Merge bitcoin/bitcoin#28611: Adjust Gradle properties to fix apk build
5f50406554 Adjust Gradle properties (Hennadii Stepanov)

Pull request description:

  On the master branch @ d2b8c5e123, building the `apk` target fails:
  ```
  $ make -C src/qt apk
  ...
  > Task :compileDebugJavaWithJavac FAILED
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtActivityDelegate.java:690: error: cannot find symbol
                  Display display = (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
                                                                                ^
    symbol:   variable R
    location: class VERSION_CODES
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtActivityDelegate.java:692: error: cannot find symbol
                          : m_activity.getDisplay();
                                      ^
    symbol:   method getDisplay()
    location: variable m_activity of type Activity
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtActivityDelegate.java:833: error: cannot find symbol
          float refreshRate = (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
                                                                          ^
    symbol:   variable R
    location: class VERSION_CODES
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtActivityDelegate.java:835: error: cannot find symbol
                  : m_activity.getDisplay().getRefreshRate();
                              ^
    symbol:   method getDisplay()
    location: variable m_activity of type Activity
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtLayout.java:95: error: cannot find symbol
          Display display = (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
                                                                        ^
    symbol:   variable R
    location: class VERSION_CODES
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/QtLayout.java:97: error: cannot find symbol
                  : ((Activity)getContext()).getDisplay();
                                            ^
    symbol:   method getDisplay()
    location: class Activity
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/ExtractStyle.java:418: error: cannot find symbol
              if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q)
                                                             ^
    symbol:   variable Q
    location: class VERSION_CODES
  /home/hebasto/git/gui/src/qt/android/src/org/qtproject/qt5/android/ExtractStyle.java:421: error: cannot find symbol
                  numStates = stateList.getStateCount();
                                       ^
    symbol:   method getStateCount()
    location: variable stateList of type StateListDrawable
  Note: Some input files use or override a deprecated API.
  Note: Recompile with -Xlint:deprecation for details.
  8 errors

  FAILURE: Build failed with an exception.

  * What went wrong:
  Execution failed for task ':compileDebugJavaWithJavac'.
  > Compilation failed; see the compiler error output for details.

  * Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

  Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
  Use '--warning-mode all' to show the individual deprecation warnings.
  See https://docs.gradle.org/6.6.1/userguide/command_line_interface.html#sec:command_line_warnings

  BUILD FAILED in 827ms
  ...
  ```

  Fixing it by updating the Gradle tool's properties.

ACKs for top commit:
  fanquake:
    ACK 5f50406554 - seems fine.

Tree-SHA512: 52e59fe1c69841370ce2eb670f3618182bf2843582074af4895b8ecb6e5f70dc3fe4eecbffa212efaa534b423ced5b75020f6f09917b52f452121c1e55fbcaac
2023-10-09 14:12:00 +01:00
dergoegge
cdb14d79e8 [net processing] Use HasWitness over comparing (w)txids 2023-10-09 13:22:12 +01:00
Hennadii Stepanov
5c9513ece9
qt: Update translation source file for v26.0 string freeze
The diff is produced by running `make -C src translate`.
2023-10-09 10:08:52 +01:00
Hennadii Stepanov
5f50406554
Adjust Gradle properties
This change fixes the `apk` target build after bumping Qt version from
5.15.5 to 5.15.10.
2023-10-08 14:01:59 +01:00
Antoine Poinsot
ec0fc14a22
miniscript: remove P2WSH-specific part of GetStackSize doc comment 2023-10-08 02:43:27 +02:00
Antoine Poinsot
117927bd5f
miniscript: have a custom Node destructor
To avoid recursive calls in shared_ptr's destructor that could lead to a
stack overflow.
2023-10-08 02:43:26 +02:00
Antoine Poinsot
4f473ea515
script/sign: Miniscript support in Tapscript
We make the Satisfier a base in which to store the common methods
between the Tapscript and P2WSH satisfier, and from which they both
inherit.

A field is added to SignatureData to be able to satisfy pkh() under
Tapscript context (to get the pubkey hash preimage) without wallet data.
For instance in `finalizepsbt` RPC. See also the next commits for a
functional test that exercises this.
2023-10-08 02:43:24 +02:00
Antoine Poinsot
febe2abc0e
MOVEONLY: script/sign: move Satisfier declaration above Tapscript signing
We'll need the Miniscript satisfier for Tapscript too.
2023-10-08 02:43:23 +02:00
Antoine Poinsot
8571b89a7f
descriptor: parse Miniscript expressions within Taproot descriptors 2023-10-08 02:43:22 +02:00
Antoine Poinsot
8ff9489422
descriptor: Tapscript-specific Miniscript key serialization / parsing
64-hex-characters public keys are valid in Miniscript key expressions
within a Tapscript context.

Keys under a Tapscript context always serialize as 32-bytes x-only
public keys (and that's what get hashed by OP_HASH160 on the stack too).
2023-10-08 02:43:22 +02:00
Antoine Poinsot
5e76f3f0dd
fuzz: miniscript: higher sensitivity for max stack size limit under Tapscript
In order to exacerbate a mistake in the stack size tracking logic,
sometimes pad the witness to make the script execute at the brink of the
stack size limit. This way if the stack size is underestimated for a
script it would immediately fail `VerifyScript`.
2023-10-08 02:43:21 +02:00
Antoine Poinsot
6f529cbaaf
qa: test Miniscript max stack size tracking 2023-10-08 02:43:21 +02:00
Antoine Poinsot
770ba5b519
miniscript: check maximum stack size during execution
Under Tapscript, due to the lifting of some standardness and consensus
limits, scripts can now run into the maximum stack size during
execution. Any Miniscript that may hit the limit on any of its spending
paths must be marked as unsafe.

Co-Authored-By: Pieter Wuille <pieter@wuille.net>
2023-10-08 02:43:20 +02:00
Antoine Poinsot
574523dbe0
fuzz: adapt Miniscript targets to Tapscript
We introduce another global that dictates the script context under which
to operate when running the target.

For miniscript_script, just consume another byte to set the context.
This should only affect existing seeds to the extent they contain a
CHECKMULTISIG. However it would not invalidate them entirely as they may
contain a NUMEQUAL or a CHECKSIGADD, and this still exercises a bit of
the parser.

For miniscript_string, reduce the string size by one byte and use the
last byte to determine the context. This is the change that i think
would invalidate the lowest number of existing seeds.

For miniscript_stable, we don't want to invalidate any seed. Instead of
creating a new miniscript_stable_tapscript, simply run the target once
for P2WSH and once for Tapscript (with the same seed).

For miniscript_smart, consume one byte before generating a pseudo-random
node to set the context. We have less regard for seed stability for this
target anyways.
2023-10-08 02:43:20 +02:00
Antoine Poinsot
84623722ef
qa: Tapscript-Miniscript unit tests
Adapt the test data and the parsing context to support x-only keys.
Adapt the Test() helper to test existing cases under both Tapscript and
P2WSH context, asserting what needs to be valid or not in each.
Finally, add more cases that exercise the logic that was added in the
previous commits (multi_a, different resource checks and keys
serialization under Tapscript, different properties for 'd:' fragment,
..).
2023-10-08 02:43:19 +02:00
Antoine Poinsot
fcb6f13f44
pubkey: introduce a GetEvenCorrespondingCPubKey helper
We'll need to get a compressed key out of an x-only one in other places.
Avoid duplicating the code.
2023-10-08 02:43:19 +02:00
Antoine Poinsot
ce8845f5dd
miniscript: account for keys as being 32 bytes under Taproot context 2023-10-08 02:43:18 +02:00
Antoine Poinsot
f4f978d38e
miniscript: adapt resources checks depending on context
Under Tapscript, there is:
- No limit on the number of OPs
- No limit on the script size, it's implicitly limited by the maximum
  (standard) transaction size.
- No standardness limit on the number of stack items, it's limited by
  the consensus MAX_STACK_SIZE. This requires tracking the maximum stack
  size at all times during script execution, which will be tackled in
  its own commit.

In order to avoid any Miniscript that would not be spendable by a
standard transaction because of the size of the witness, we limit the
script size under Tapscript to the maximum standard transaction size
minus the maximum possible witness and Taproot control block sizes. Note
this is a conservative limit but it still allows for scripts more than a
hundred times larger than under P2WSH.
2023-10-08 02:43:17 +02:00
Antoine Poinsot
9cb4c68b89
serialize: make GetSizeOfCompactSize constexpr 2023-10-08 02:43:17 +02:00
Antoine Poinsot
892436c7d5
miniscript: sanity asserts context in ComputeType 2023-10-08 02:43:16 +02:00
Antoine Poinsot
e5aaa3d77a
miniscript: make 'd:' have the 'u' property under Tapscript context
In Tapscript MINIMALIF is a consensus rule, so we can rely on the fact
that the `DUP IF [X] ENDIF` will always put an exact 1 on the stack upon
satisfaction.
2023-10-08 02:43:16 +02:00
Antoine Poinsot
687a0b0fa5
miniscript: introduce a multi_a fragment
It is the equivalent of multi() but for Tapscript, using CHECKSIGADD
instead of CHECKMULTISIG.

It shares the same properties as multi() but for 'n', since a threshold
multi_a() may have an empty vector as the top element of its
satisfaction. It could also have the 'o' property when it only has a
single key, but in this case a 'pk()' is always preferable anyways.
2023-10-08 02:43:15 +02:00
Antoine Poinsot
9164c2eca1
miniscript: restrict multi() usage to P2WSH context
CHECKMULTISIG is disabled for Tapscript. Instead, we'll introduce
a multi_a() fragment with the same semantic as multi().
2023-10-08 02:43:15 +02:00
Antoine Poinsot
91b4db8590
miniscript: store the script context within the Node structure
Some checks will be different depending on the script context (for
instance the maximum script size).
2023-10-08 02:43:14 +02:00
Antoine Poinsot
c3738d0344
miniscript: introduce a MsContext() helper to contexts
We are going to introduce Tapscript support in Miniscript, for which
some of Miniscript rules and properties change (new or modified
fragments, different typing rules, different resources consumption, ..).
2023-10-08 02:43:14 +02:00
Antoine Poinsot
bba9340a94
miniscript: don't anticipate signature presence in CalcStackSize()
It's true that for any public key there'll be a signature check in a
valid Miniscript. The code would previously, when computing the size of
a satisfaction, account for the signature when it sees a public key
push. Instead, account for it when it is required (ie when encountering
the `c:` wrapper). This has two benefits:
- Allows to accurately compute the net effect of a fragment on the stack
  size. This is necessary to track the size of the stack during the
  execution of a Script.
- It also just makes more sense, making the code more accessible to
  future contributors.
2023-10-08 02:43:13 +02:00
Antoine Poinsot
a3793f2d1a
miniscript: add a missing dup key check bypass in Parse()
This was calling the wrong constructor.
2023-10-08 02:43:13 +02:00
Hennadii Stepanov
d2b8c5e123
Merge bitcoin-core/gui#764: Remove legacy wallet creation
b442580ed2 gui: remove legacy wallet creation (furszy)

Pull request description:

  Fixes #763

  Preventing users from creating a legacy wallet prior to its deprecation in the upcoming releases.

  Note:
  This is still available using the `createwallet` RPC command.

  Future Note:
  Would be nice to re-write this modal as a wizard. And improve the design.

  <details><summary> Pre-Changes Screenshot </summary>
  <img width="611" alt="Screenshot 2023-10-06 at 11 30 14" src="https://github.com/bitcoin-core/gui/assets/5377650/ca10c97d-46e8-4aed-82da-068f2afbe25c">
  </details>

  <details><summary> Post-Changes  Screenshot </summary>
  <img width="729" alt="Screenshot 2023-10-06 at 11 32 58" src="https://github.com/bitcoin-core/gui/assets/5377650/f6bdcb57-646a-43d8-86a7-476e3cca683f">
  </details>

ACKs for top commit:
  achow101:
    ACK b442580ed2
  hebasto:
    re-ACK b442580ed2
  pablomartin4btc:
    tACK b442580ed2

Tree-SHA512: f5d26ffbb0962648b9edf273b325e89425a318e136df26a26acb21b88730fd7d6499c68a705680539dc1b40862fbf413a1e0c8572436a0cfc665e2d08a3cf97d
2023-10-07 11:53:16 +01:00
Sebastian Falbesoner
00a52e6394 gui: fix coin control input size accounting for taproot spends 2023-10-07 01:07:21 +02:00
furszy
b442580ed2
gui: remove legacy wallet creation 2023-10-06 17:20:54 -03:00
Fabian Jahr
5d227a6862
rpc: Use Ensure(Any)Chainman in assumeutxo related RPCs 2023-10-06 19:43:32 +02:00
Fabian Jahr
710e5db61b
doc: Drop references to assumevalid in assumeutxo docs 2023-10-06 19:43:32 +02:00
Fabian Jahr
a482f86779
chain: Rename HaveTxsDownloaded to HaveNumChainTxs
Co-authored-by: MarcoFalke <falke.marco@gmail.com>
2023-10-06 19:43:32 +02:00
Fabian Jahr
82e48d20f1
blockstorage: Let FlushChainstateBlockFile return true in case of missing cursor
Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
2023-10-06 19:43:32 +02:00
Fabian Jahr
73700fb554
validation, test: Improve and document nChainTx check for testability
Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
2023-10-06 19:43:31 +02:00
Fabian Jahr
2c9354facb
doc: Add snapshot chainstate removal warning to reindexing documentation 2023-10-06 19:43:29 +02:00
Fabian Jahr
a47fbe7d49
doc: Add and edit some comments around assumeutxo
Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
2023-10-06 18:12:31 +02:00
Fabian Jahr
0a39b8cbd8
validation: remove unused mempool param in DetectSnapshotChainstate 2023-10-06 18:11:24 +02:00
Andrew Chow
54bdb6e074
Merge bitcoin/bitcoin#27609: rpc: allow submitpackage to be called outside of regtest
5b878be742 [doc] add release note for submitpackage (glozow)
7a9bb2a2a5 [rpc] allow submitpackage to be called outside of regtest (glozow)
5b9087a9a7 [rpc] require package to be a tree in submitpackage (glozow)
e32ba1599c [txpackages] IsChildWithParentsTree() (glozow)
b4f28cc345 [doc] parent pay for child in aggregate CheckFeeRate (glozow)

Pull request description:

  Permit (restricted topology) submitpackage RPC outside of regtest. Suggested in https://github.com/bitcoin/bitcoin/pull/26933#issuecomment-1510851570

  This RPC should be safe but still experimental - interface may change, not all features (e.g. package RBF) are implemented, etc. If a miner wants to expose this to people, they can effectively use "package relay" before the p2p changes are implemented. However, please note **this is not package relay**; transactions submitted this way will not relay to other nodes if the feerates are below their mempool min fee. Users should put this behind some kind of rate limit or permissions.

ACKs for top commit:
  instagibbs:
    ACK 5b878be742
  achow101:
    ACK 5b878be742
  dergoegge:
    Code review ACK 5b878be742
  ajtowns:
    ACK 5b878be742
  ariard:
    Code Review ACK  5b878be742. Though didn’t manually test the PR.

Tree-SHA512: 610365c0b2ffcccd55dedd1151879c82de1027e3319712bcb11d54f2467afaae4d05dca5f4b25f03354c80845fef538d3938b958174dda8b14c10670537a6524
2023-10-05 19:08:19 -04:00
Andrew Chow
cf553e3ab7
Merge bitcoin/bitcoin#28597: wallet: No BDB creation, unless -deprecatedrpc=create_bdb
fa071aeb61 wallet: No BDB creation, unless -deprecatedrpc=create_bdb (MarcoFalke)

Pull request description:

  With BDB being removed soon, it seems confusing and harmful to allow users to create fresh BDB wallets going forward, as it would load them with an additional burden of having to migrate them soon after.

  Also, it would be good to allow for one release for test (and external) scripts to adapt.

  Fix all issues by introducing the `-deprecatedrpc=create_bdb` setting.

ACKs for top commit:
  Sjors:
    tACK fa071aeb61
  achow101:
    ACK fa071aeb61
  furszy:
    utACK fa071aeb

Tree-SHA512: 37a4c3e4ba659e0ebe2382e71d9c80e42a895d9ad743f5dda7c110fbbb7d2a36f46769982552a9ac0c3a57203379ef164be97aa8033eb7674d6b4da030ba8f9b
2023-10-05 15:35:54 -04:00
Andrew Chow
0b2c93bc56
Merge bitcoin/bitcoin#28590: assumeutxo: change getchainstates RPC to return a list of chainstates
a9ef702a87 assumeutxo: change getchainstates RPC to return a list of chainstates (Ryan Ofsky)

Pull request description:

  Current `getchainstates` RPC returns "normal" and "snapshot" fields which are not ideal because it requires new "normal" and "snapshot" terms to be defined, and the definitions are not really consistent with internal code. (In the RPC interface, the "snapshot" chainstate becomes the "normal" chainstate after it is validated, while in internal code there is no "normal chainstate" and the "snapshot chainstate" is still called that temporarily after it is validated).

  The current `getchainstates` RPC is also awkward to use if you to want information about the most-work chainstate, because you have to look at the "snapshot" field if it exists, and otherwise fall back to the "normal" field.

  Fix these issues by having `getchainstates` just return a flat list of chainstates ordered by work, and adding a new chainstate "validated" field alongside the existing "snapshot_blockhash" field so it is explicit if a chainstate was originally loaded from a snapshot, and whether the snapshot has been validated.

  This change was motivated by comment thread in https://github.com/bitcoin/bitcoin/pull/28562#discussion_r1344154808

ACKs for top commit:
  Sjors:
    re-ACK a9ef702a87
  jamesob:
    re-ACK a9ef702
  achow101:
    ACK a9ef702a87

Tree-SHA512: b364e2e96675fb7beaaee60c4dff4b69e6bc2d8a30dea1ba094265633d1cddf9dbf1c5ce20c07d6e23222cf1e92a195acf6227e4901f3962e81a1e53a43490aa
2023-10-05 14:19:34 -04:00
Andrew Chow
6e5cf8e953
Merge bitcoin/bitcoin#28587: descriptors: disallow hybrid public keys
c1e6c542af descriptors: disallow hybrid public keys (Pieter Wuille)

Pull request description:

  Fixes #28511

  The descriptor documentation (`doc/descriptors.md`) and [BIP380](https://github.com/bitcoin/bips/blob/master/bip-0380.mediawiki) explicitly require that hex-encoded public keys start with 02 or 03 (compressed) or 04 (uncompressed). However, the current parsing/inference code permit 06 and 07 (hybrid) encoding as well. Fix this.

ACKs for top commit:
  darosior:
    ACK c1e6c542af
  achow101:
    ACK c1e6c542af

Tree-SHA512: 23b674fb420619b2536d12da10008bb87cf7bc0333ec59e618c0d02c3574b468cc71248475ece37f76658d743ef51e68566948e903bca79fda5f7d75416fea4d
2023-10-05 11:58:07 -04:00
MarcoFalke
fa071aeb61
wallet: No BDB creation, unless -deprecatedrpc=create_bdb 2023-10-05 15:47:44 +02:00
Ryan Ofsky
a9ef702a87 assumeutxo: change getchainstates RPC to return a list of chainstates
Current getchainstates RPC returns "normal" and "snapshot" fields which are not
ideal because it requires new "normal" and "snapshot" terms to be defined, and
the definitions are not really consistent with internal code. (In the RPC
interface, the "snapshot" chainstate becomes the "normal" chainstate after it
is validated, while in internal code there is no "normal chainstate" and the
"snapshot chainstate" is still called that temporarily after it is validated).

The current getchainstatees RPC is also awkward to use if you to want
information about the most-work chainstate because you have to look at the
"snapshot" field if it exists, and otherwise fall back to the "normal" field.

Fix these issues by having getchainstates just return a flat list of
chainstates ordered by work, and adding new chainstate "validated" field
alongside the existing "snapshot_blockhash" so it is explicit if a chainstate
was originally loaded from a snapshot, and whether the snapshot has been
validated.
2023-10-05 09:41:43 -04:00
Vasil Dimov
53afa68026
net: move MaybeFlipIPv6toCJDNS() from net to netbase
It need not be in the `net` module and we need to call it from
`LookupSubNet()`, thus move it to `netbase`.
2023-10-05 15:10:34 +02:00
Vasil Dimov
6e308651c4
net: move IsReachable() code to netbase and encapsulate it
`vfLimited`, `IsReachable()`, `SetReachable()` need not be in the `net`
module. Move them to `netbase` because they will be needed in
`LookupSubNet()` to possibly flip the result to CJDNS (if that network
is reachable).

In the process, encapsulate them in a class.

`NET_UNROUTABLE` and `NET_INTERNAL` are no longer ignored when adding
or removing reachable networks. This was unnecessary.
2023-10-05 15:10:34 +02:00
Vasil Dimov
c42ded3d9b
fuzz: ConsumeNetAddr(): avoid IPv6 addresses that look like CJDNS
The fuzz testing framework runs as if `-cjdnsreachable` is set and in
this case addresses like `{net=IPv6, addr=fc...}` are not possible.
2023-10-05 15:10:33 +02:00
Vasil Dimov
64d6f77907
net: put CJDNS prefix byte in a constant 2023-10-05 15:10:32 +02:00
fanquake
52c6904c78
Merge bitcoin/bitcoin#28558: Make PeerManager own a FastRandomContext
4cafe9f176 [test] Make PeerManager's rng deterministic in tests (dergoegge)
fecec3e1c6 [net processing] FeeFilterRounder doesn't own a FastRandomContext (dergoegge)
47520ed209 [net processing] Make fee filter rounder non-global (dergoegge)
77506f4ac6 [net processing] Addr shuffle uses PeerManager's rng (dergoegge)
a648dd79e5 [net processing] PushAddress uses PeerManager's rng (dergoegge)
87c706713e [net processing] PeerManager holds a FastRandomContext (dergoegge)

Pull request description:

  This lets us avoid some non-determinism in tests (also see #28537).

ACKs for top commit:
  MarcoFalke:
    re-ACK 4cafe9f176  🕗
  glozow:
    concept && light code review ACK 4cafe9f176

Tree-SHA512: 3c18700773d0bc547ccb6442c41567e6f26b0b50fab5b79620da417ec91b9c0ae1395d15258da3aa4a91447b8ce560145dd135e39fbbd0610749e528e665b111
2023-10-05 14:06:39 +01:00
Vasil Dimov
5c8e15c451
i2p: destroy the session if we get an unexpected error from the I2P router
From https://geti2p.net/en/docs/api/samv3:

  If SILENT=false was passed, which is the default value, the SAM bridge
  sends the client a ASCII line containing the base64 public destination
  key of the requesting peer

So, `Accept()` is supposed to receive a Base64 encoded destination of
the connecting peer, but if it receives something like this instead:

  STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"

then destroy the session.
2023-10-05 14:11:13 +02:00
Vasil Dimov
762404a68c
i2p: also sleep after errors in Accept()
Background:

`Listen()` does:
* if the session is not created yet
  * create the control socket and on it:
  * `HELLO`
  * `SESSION CREATE ID=sessid`
  * leave the control socked opened
* create a new socket and on it:
* `HELLO`
* `STREAM ACCEPT ID=sessid`
* read reply (`STREAM STATUS`)

Then a wait starts, for a peer to connect. When connected,

`Accept()` does:
* on the socket from `STREAM ACCEPT` from `Listen()`: read the
  Base64 identification of the connecting peer

Problem:

The I2P router may be in such a state that this happens in a quick
succession (many times per second, see https://github.com/bitcoin/bitcoin/issues/22759#issuecomment-1609907115):
`Listen()`-succeeds, `Accept()`-fails.

`Accept()` fails because the I2P router sends something that is
not Base64 on the socket:
STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"

We only sleep after failed `Listen()` because the assumption was that
if `Accept()` fails then the next `Listen()` will also fail.

Solution:

Avoid filling the log with "Error accepting:" messages and sleep also
after a failed `Accept()`.

Extra changes:

* Reset the error waiting time after one successful connection.
  Otherwise the timer will remain high due to problems that have
  vanished long time ago.

* Increment the wait time less aggressively.
2023-10-05 14:10:43 +02:00
fanquake
b2ede22395
headerssync: update params for 26.x 2023-10-05 11:36:03 +01:00
fanquake
f12f92b813
kernel: update m_assumed_* chain params for 26.x 2023-10-05 11:29:42 +01:00
fanquake
a8c2e5e556
kernel: update chainTxData for 26.x 2023-10-05 11:29:41 +01:00
fanquake
a9d070a6f8
kernel: update nMinimumChainWork & defaultAssumeValid for 26.x 2023-10-05 11:29:41 +01:00
fanquake
2eacc61ad7
Merge bitcoin/bitcoin#25970: Add headerssync tuning parameters optimization script to repo
3d420d8f28 Add instructions for headerssync-params.py to release-process.md (Pieter Wuille)
53d7d35b58 Update parameters in headerssync.cpp (Pieter Wuille)
7899402cff Add headerssync-params.py script to the repository (Pieter Wuille)

Pull request description:

  Builds upon #25946, as it incorporates changes based on the selected values there.

  This adds the headerssync tuning parameters optimization script from https://gist.github.com/sipa/016ae445c132cdf65a2791534dfb7ae1 to the repository, updates the parameters based on its output, and adds release process instructions for doing this update in the future.

  A few considerations:
  * It would be a bit cleaner to have these parameters be part of `CChainParams`, but due to the nature of the approach, it really only applies to chains with unforgeable proof-of-work, which we really can only reasonably expect from mainnet, so I think it's fine to keep them local to `headerssync.cpp`. Keeping them as compile-time evaluatable constants also has a (likely negligible) performance impact (avoiding runtime modulo operations).
  * If we want to make sure the chainparams and headerssync params don't go out of date, it could be possible to run the script in CI, and and possibly even have the parameters be generated automatically at build time. I think that's overkill for how unfrequently these need to change, and running the script has non-trivial cost (~minutes in the normal python interpreter).
  * A viable alternative is just leaving this out-of-repo entirely, and just do ad-hoc updating from time to time. Having it in the repo and release notes does make sure it's not forgotten, though adds a cost to contributors/maintainers who follow the process.

ACKs for top commit:
  ajtowns:
    reACK 3d420d8f28

Tree-SHA512: 03188301c20423c72c1cbd008ccce89b93e2898edcbeecc561b2928a0d64e9a829ab0744dc3b017c23de8b02f3c107ae31e694302d3931f4dc3540e184de1963
2023-10-05 11:28:29 +01:00
Hennadii Stepanov
0e3de3b83e
Merge bitcoin-core/gui#754: Add BIP324-specific labels to peer details
d9c4e344d7 qt: Add "Session id" label to peer details (Hennadii Stepanov)
f08adec886 qt: Add "Transport" label to peer details (Hennadii Stepanov)

Pull request description:

  This PR adds BIP324-specific labels to the peer details widget:
  -  a transport version
  - a session id

  See: https://github.com/bitcoin/bitcoin/pull/28331#issuecomment-1693239025.

  ![image](https://github.com/bitcoin-core/gui/assets/32963518/0e0b4c92-dde0-4b2e-b285-a2c69ef09efc)

ACKs for top commit:
  achow101:
    ACK d9c4e344d7
  RandyMcMillan:
    ACK d9c4e34
  theStack:
    Tested re-ACK d9c4e344d7
  MarnixCroes:
    tACK d9c4e344d7

Tree-SHA512: 524e634b1eedcae535d5c2a10dd8dea90d33d65d6790614f86ab6387a0ec9ee4bbc7646b8c20a5b3f1bccbb69bc52a46514e2b28cb4588979834d945b1f89b3a
2023-10-05 08:36:49 +01:00
Andrew Chow
5b4478418b
Merge bitcoin/bitcoin#28577: net: raise V1_PREFIX_LEN from 12 to 16
ba2e5bfc67 net: raise V1_PREFIX_LEN from 12 to 16 (Pieter Wuille)

Pull request description:

  A "version" message in the V1 protocol starts with a fixed 16 bytes:
  * The 4-byte network magic
  * The 12-byte command string: "version" plus 5 0x00 bytes

  The current code detects incoming V1 connections by just looking at the first 12 bytes (matching an [earlier version](https://github.com/bitcoin/bips/pull/1496) of BIP324), but 16 bytes is more precise. This isn't an observable difference right now, as a 12 byte prefix ought to be negligible already, but it may become observable with future extensions to the protocol, so make the code match the specification.

ACKs for top commit:
  achow101:
    ACK ba2e5bfc67
  theStack:
    re-ACK ba2e5bfc67
  mzumsande:
    Code review ACK ba2e5bfc67

Tree-SHA512: 64876b03613bd1c5dda82f4ca1b367014365f9ae4cfa30f45c5758a563c68cbea81a98d02ba616c264674c204517aac8b7de94da10f32e77b56267a43710c651
2023-10-04 16:57:32 -04:00
pablomartin4btc
58c9b50a95 gui: Add wallet name to address book page
Extend addresstablemodel to return the display name from the wallet and
set it to the addressbookpage window title when its  model is set.
2023-10-04 17:01:49 -03:00
Andrew Chow
ab163b0fb5
Merge bitcoin/bitcoin#27823: init: return error when block index is non-contiguous, fix feature_init.py file perturbation
d27b9a2248 test: fix feature_init.py file perturbation (Martin Zumsande)
ad66ca1e47 init: abort loading of blockindex in case of missing height. (Martin Zumsande)

Pull request description:

  When the block index database is non-contiguous due to file corruption (i.e. it contains indexes of height `x-1` and `x+1`, but not `x`), bitcoind can currently crash with an assert in `BuildSkip()` / `GetAncestor()` during `BlockManager::LoadBlockIndex()`:
  ```
  bitcoind: chain.cpp:112: const CBlockIndex* CBlockIndex::GetAncestor(int) const: Assertion `pindexWalk->pprev' failed.
  ```
  This PR changes it such that we instead return an `InitError` to the user.

  I stumbled upon this because I noticed that the file perturbation in `feature_init.py`  wasn't working as intended, which is fixed in the second commit:
  * Opening the file twice in one `with` statement would lead to `tf_read` being empty, so the test wouldn't perturb anything but replace the file with a new one. Fixed by first opening for read, then for write.
  * We need to restore the previous state after perturbations, so that only the current perturbation is active and not a mix of the current and previous ones.
  * I also added `checkblocks=200` to the startup parameters so that corruption in earlier blocks of `blk00000.dat` is detected during init verification and not ignored.

  After fixing `feature_init.py` like that I'd run into the `assert` mentioned above (so running the testfix from the second commit without the first one is a way to reproduce it).

ACKs for top commit:
  achow101:
    ACK d27b9a2248
  furszy:
    Code ACK d27b9a224
  fjahr:
    Code review ACK d27b9a2248

Tree-SHA512: 2e54da6030c5813c86bd58f816401e090bb43c5b834764a5e3c0e55dbfe09e423f88042cab823db3742088204b274d4ad2abf58a3832a4b18328b11a30bf7094
2023-10-04 15:36:57 -04:00
Fabian Jahr
28d7e55dff
test: Add tests for unfiltered GetAddr usage 2023-10-04 18:08:50 +02:00
Fabian Jahr
b8843d37ae
fuzz: Let fuzzers use filter options in GetAddr/GetAddresses 2023-10-04 18:08:50 +02:00
Fabian Jahr
e16f420547
net: Optionally include terrible addresses in GetAddr results 2023-10-04 18:08:49 +02:00
Pieter Wuille
c1e6c542af descriptors: disallow hybrid public keys
The descriptor documentation (doc/descriptors.md) and BIP380 explicitly
require that hex-encoded public keys start with 02 or 03 (compressed) or
04 (uncompressed). However, the current parsing/inference code permit 06
and 07 (hybrid) encoding as well. Fix this.
2023-10-04 11:28:13 -04:00
Pieter Wuille
ba2e5bfc67 net: raise V1_PREFIX_LEN from 12 to 16
A "version" message in the V1 protocol starts with a fixed 16 bytes:
* The 4-byte network magic
* The 12-byte zero-padded command "version" plus 5 0x00 bytes

The current code detects incoming V1 connections by just looking at the
first 12 bytes (matching an earlier version of BIP324), but 16 bytes is
more precise. This isn't an observable difference right now, as a 12 byte
prefix ought to be negligible already, but it may become observable with
future extensions to the protocol, so make the code match the
specification.
2023-10-04 11:04:43 -04:00
fanquake
058488276f
Merge bitcoin/bitcoin#27598: bench: Add SHA256 implementation specific benchmarks
ce6df7df9b bench: Add SHA256 implementation specific benchmarks (Hennadii Stepanov)
5f72417176 Add ability to specify SHA256 implementation for benchmark purposes (Hennadii Stepanov)

Pull request description:

  On the master branch, only the best available `SHA256` implementation is being benchmarked. This PR makes `bench_bitcoin` benchmark all `SHA256` implementations that are available on the system.

  For  example:
  - on Linux:
  ```
  $ ./src/bench/bench_bitcoin -filter=SHA.*
  Using the 'x86_shani(1way,2way)' SHA256 implementation

  |             ns/byte |              byte/s |    err% |     total | benchmark
  |--------------------:|--------------------:|--------:|----------:|:----------
  |                1.00 |    1,002,545,462.93 |    0.4% |      0.01 | `SHA1`
  |                2.91 |      344,117,991.18 |    0.1% |      0.03 | `SHA256 using the 'standard' SHA256 implementation`
  |                2.21 |      453,081,794.40 |    0.1% |      0.02 | `SHA256 using the 'sse4(1way),sse41(4way)' SHA256 implementation`
  |                2.21 |      453,396,506.58 |    0.1% |      0.02 | `SHA256 using the 'sse4(1way),sse41(4way),avx2(8way)' SHA256 implementation`
  |                0.53 |    1,870,520,687.49 |    0.1% |      0.01 | `SHA256 using the 'x86_shani(1way,2way)' SHA256 implementation`
  |                7.90 |      126,627,134.33 |    0.0% |      0.01 | `SHA256D64_1024 using the 'standard' SHA256 implementation`
  |                3.94 |      253,850,206.07 |    0.0% |      0.01 | `SHA256D64_1024 using the 'sse4(1way),sse41(4way)' SHA256 implementation`
  |                1.40 |      716,247,553.38 |    0.4% |      0.01 | `SHA256D64_1024 using the 'sse4(1way),sse41(4way),avx2(8way)' SHA256 implementation`
  |                1.26 |      792,706,270.13 |    0.9% |      0.01 | `SHA256D64_1024 using the 'x86_shani(1way,2way)' SHA256 implementation`
  |                6.75 |      148,172,097.64 |    0.2% |      0.01 | `SHA256_32b using the 'standard' SHA256 implementation`
  |                4.90 |      204,156,289.96 |    0.1% |      0.01 | `SHA256_32b using the 'sse4(1way),sse41(4way)' SHA256 implementation`
  |                4.90 |      204,101,274.22 |    0.1% |      0.01 | `SHA256_32b using the 'sse4(1way),sse41(4way),avx2(8way)' SHA256 implementation`
  |                1.70 |      589,052,595.35 |    0.4% |      0.01 | `SHA256_32b using the 'x86_shani(1way,2way)' SHA256 implementation`
  |                2.21 |      453,441,736.14 |    1.0% |      0.02 | `SHA3_256_1M`
  |                1.92 |      521,807,101.48 |    1.0% |      0.02 | `SHA512`
  ```

  - on macOS (M1):
  ```
  % ./src/bench/bench_bitcoin -filter=SHA.\*
  Using the 'arm_shani(1way,2way)' SHA256 implementation

  |             ns/byte |              byte/s |    err% |     total | benchmark
  |--------------------:|--------------------:|--------:|----------:|:----------
  |                1.36 |      737,644,274.00 |    0.6% |      0.02 | `SHA1`
  |                3.08 |      324,556,777.15 |    0.2% |      0.03 | `SHA256 using the 'standard' SHA256 implementation`
  |                0.45 |    2,198,104,135.18 |    0.3% |      0.01 | `SHA256 using the 'arm_shani(1way,2way)' SHA256 implementation`
  |                8.84 |      113,131,299.18 |    0.0% |      0.01 | `SHA256D64_1024 using the 'standard' SHA256 implementation`
  |                0.94 |    1,059,406,239.36 |    0.0% |      0.01 | `SHA256D64_1024 using the 'arm_shani(1way,2way)' SHA256 implementation`
  |                6.17 |      162,050,659.51 |    0.2% |      0.01 | `SHA256_32b using the 'standard' SHA256 implementation`
  |                1.15 |      866,637,155.98 |    0.0% |      0.01 | `SHA256_32b using the 'arm_shani(1way,2way)' SHA256 implementation`
  |                1.69 |      592,636,491.59 |    0.2% |      0.02 | `SHA3_256_1M`
  |                1.89 |      528,785,775.66 |    0.0% |      0.02 | `SHA512`
  ```

  Found it useful, while working on https://github.com/bitcoin/bitcoin/pull/24773.

ACKs for top commit:
  martinus:
    ACK ce6df7df9b. I would have created a helper function in the test to avoid the code duplication for each test, but that's just me nitpicking. Here are results from my Ryzen 7950X, with `./src/bench/bench_bitcoin -filter="SHA256.*" -min-time=1000`:
  MarcoFalke:
    review ACK ce6df7df9b 🏵
  sipa:
    ACK ce6df7df9b

Tree-SHA512: e3de50e11b9a3a0d1e05583786041d4dc9afa2022e2115d75d6d1f63b11f62f6336f093001e53a631431d558c4dae29c596755c9e2d6aa78c382270116cc1f7f
2023-10-04 16:04:07 +01:00
dergoegge
4cafe9f176 [test] Make PeerManager's rng deterministic in tests 2023-10-04 13:16:53 +01:00
dergoegge
fecec3e1c6 [net processing] FeeFilterRounder doesn't own a FastRandomContext 2023-10-04 13:16:52 +01:00
dergoegge
47520ed209 [net processing] Make fee filter rounder non-global 2023-10-04 13:14:05 +01:00
Hennadii Stepanov
d9c4e344d7
qt: Add "Session id" label to peer details 2023-10-04 12:07:21 +01:00
MarcoFalke
88887531b7
Move compat/assumptions.h include to one place that actually needs it
Also add the <IWYU pragma: keep> to avoid removing it by accident.
2023-10-04 11:25:23 +02:00
MarcoFalke
77774110f4
Remove __cplusplus from compat/assumptions.h
It is unclear what the goal of this check is, given that the value may
need to be set lower for the mimimum supported version of compilers that
forgot to bump the value, see
https://github.com/bitcoin/bitcoin/pull/28349#issuecomment-1745143612 .

The minimum supported compiler versions are already documented in
doc/dependencies.md and using an older compiler will already result in a
compile failure, so this check can be removed as redundant. Especially
given that it is only included in one file, where iwyu suggests to
remove it.
2023-10-04 11:11:37 +02:00
fanquake
db7b5dfcc5
Merge bitcoin/bitcoin#28551: http: bugfix: allow server shutdown in case of remote client disconnection
68f23f57d7 http: bugfix: track closed connection (stickies-v)
084d037231 http: log connection instead of request count (stickies-v)
41f9027813 http: refactor: use encapsulated HTTPRequestTracker (stickies-v)

Pull request description:

  #26742 significantly increased the http server shutdown speed, but also introduced a bug (#27722 - see https://github.com/bitcoin/bitcoin/issues/27722#issuecomment-1559453982 for steps to reproduce on master) that causes http server shutdown to halt in case of a remote client disconnection. This happens because `evhttp_request_set_on_complete_cb` is never called and thus the request is never removed from `g_requests`.

  This PR fixes that bug, and improves robustness of the code by encapsulating the request tracking logic. Earlier approaches (#27909, #27245, #19434) attempted to resolve this but [imo are fundamentally unsafe](https://github.com/bitcoin/bitcoin/pull/27909#discussion_r1265614783) because of differences in lifetime between an `evhttp_request` and `evhttp_connection`.

  We don't need to keep track of open requests or connections, we just [need to ensure](https://github.com/bitcoin/bitcoin/pull/19420#issue-648067169) that there are no active requests on server shutdown. Because a connection can have multiple requests, and a request can be completed in various ways (the request actually being handled, or the client performing a remote disconnect), keeping a counter per connection seems like the approach with the least overhead to me.

  Fixes #27722

ACKs for top commit:
  vasild:
    ACK 68f23f57d7
  theStack:
    ACK 68f23f57d7

Tree-SHA512: dfa711ff55ec75ba44d73e9e6fac16b0be25cf3c20868c2145a844a7878ad9fc6998d9ff62d72f3a210bfa411ef03d3757b73d68a7c22926e874c421e51444d6
2023-10-04 10:09:03 +01:00
MarcoFalke
faa3d4f1d8
Remove duplicate NDEBUG check from compat/assumptions.h
The check is already done in util/check.h, which is more widely
included.
2023-10-04 11:05:27 +02:00
stratospher
e6e444c06c refactor: add and use EnsureAnyAddrman in rpc 2023-10-04 08:53:51 +05:30
stratospher
3931e6abc3 rpc: getaddrmaninfo followups
- make `getaddrmaninfo` RPC public since it's not for development
  purposes only and regular users might find it useful
- add missing `all_networks` key to RPC help
- use clang format spacing
2023-10-04 08:34:30 +05:30
Amiti Uttarwar
df69b22f2e doc: improve documentation around connection limit maximums
Co-authored-by: Martin Zumsande <mzumsande@gmail.com>
2023-10-03 14:36:04 -04:00
Amiti Uttarwar
adc171edf4 scripted-diff: Rename connection limit variables
-BEGIN VERIFY SCRIPT-
sed -i 's/nMaxConnections/m_max_automatic_connections/g' src/net.h src/net.cpp
sed -i 's/\.nMaxConnections/\.m_max_automatic_connections/g' src/init.cpp src/test/denialofservice_tests.cpp
sed -i 's/nMaxFeeler/m_max_feeler/g' src/net.h
sed -i 's/nMaxAddnode/m_max_addnode/g' src/net.h src/net.cpp
sed -i 's/m_max_outbound\([^_]\)/m_max_automatic_outbound\1/g' src/net.h src/net.cpp
-END VERIFY SCRIPT-

Co-authored-by: Martin Zumsande <mzumsande@gmail.com>
2023-10-03 13:55:57 -04:00
Amiti Uttarwar
e9fd9c0225 net: add m_max_inbound to connman
Extract the logic for calculating & maintaining inbound connection limits to be
a member within connman for consistency with other maximum connection limits.

Note that we now limit m_max_inbound to 0 and don't call
AttemptToEvictConnection() when we don't have any inbounds.
Previously, nMaxInbound could become negative if the user ran with a low
-maxconnections, which didn't break any logic but didn't make sense.

Co-authored-by: Martin Zumsande <mzumsande@gmail.com>
2023-10-03 13:52:47 -04:00
Amiti Uttarwar
c25e0e0555 net, refactor: move calculations for connection type limits into connman
Currently the logic is fragmented between init and connman. Encapsulating this
logic within connman allows for less mental overhead and easier reuse in tests.

Co-authored-by: Martin Zumsande <mzumsande@gmail.com>
2023-10-03 13:52:46 -04:00
Andrew Chow
01bd9d7b99
Merge bitcoin/bitcoin#28523: rpc: add hidden getrawaddrman RPC to list addrman table entries
352d5eb2a9 test: getrawaddrman RPC (0xb10c)
da384a286b rpc: getrawaddrman for addrman entries (0xb10c)

Pull request description:

  Inspired by `getaddrmaninfo` (#27511), this adds a hidden/test-only `getrawaddrman` RPC. The RPC returns information on all addresses in the address manager new and tried tables. Addrman table contents can be used in tests and during development.

  The RPC result encodes the `bucket` and `position`, the internal location of addresses in the tables, in the address object's string key. This allows users to choose to consume or to ignore the location information. If the internals of the address manager implementation change, the location encoding might change too.

  ```
  getrawaddrman

  EXPERIMENTAL warning: this call may be changed in future releases.

  Returns information on all address manager entries for the new and tried tables.

  Result:
  {                                  (json object)
    "table" : {                      (json object) buckets with addresses in the address manager table ( new, tried )
      "bucket/position" : {          (json object) the location in the address manager table (<bucket>/<position>)
        "address" : "str",           (string) The address of the node
        "port" : n,                  (numeric) The port number of the node
        "network" : "str",           (string) The network (ipv4, ipv6, onion, i2p, cjdns) of the address
        "services" : n,              (numeric) The services offered by the node
        "time" : xxx,                (numeric) The UNIX epoch time when the node was last seen
        "source" : "str",            (string) The address that relayed the address to us
        "source_network" : "str"     (string) The network (ipv4, ipv6, onion, i2p, cjdns) of the source address
      },
      ...
    },
    ...
  }

  Examples:
  > bitcoin-cli getrawaddrman
  > curl --user myusername --data-binary '{"jsonrpc": "1.0", "id": "curltest", "method": "getrawaddrman", "params": []}' -H 'content-type: text/plain;' http://127.0.0.1:8332/
  ```

ACKs for top commit:
  willcl-ark:
    reACK 352d5eb2a9
  amitiuttarwar:
    reACK 352d5eb2a9
  stratospher:
    reACK 352d5eb.
  achow101:
    ACK 352d5eb2a9

Tree-SHA512: cc462666b5c709617c66b0e3e9a17c4c81e9e295f91bdd9572492d1cb6466fc9b6d48ee805ebe82f9f16010798370effe5c8f4db15065b8c7c0d8637675d615e
2023-10-03 11:38:20 -04:00
Ryan Ofsky
d0b928b29d
Merge bitcoin/bitcoin#26312: Remove Sock::Get() and Sock::Sock()
7df4508369 test: improve sock_tests/move_assignment (Vasil Dimov)
5086a99b84 net: remove Sock default constructor, it's not necessary (Vasil Dimov)
7829272f78 net: remove now unnecessary Sock::Get() (Vasil Dimov)
944b21b70a net: don't check if the socket is valid in ConnectSocketDirectly() (Vasil Dimov)
aeac68d036 net: don't check if the socket is valid in GetBindAddress() (Vasil Dimov)
5ac1a51ee5 i2p: avoid using Sock::Get() for checking for a valid socket (Vasil Dimov)

Pull request description:

  _This is a piece of #21878, chopped off to ease review._

  Peeking at the underlying socket file descriptor of `Sock` and checkig if it is `INVALID_SOCKET` is bad encapsulation and stands in the way of testing/mocking/fuzzing.

  Instead use an empty `unique_ptr` to denote that there is no valid socket where appropriate or outright remove such checks where they are not necessary.

  The default constructor `Sock::Sock()` is unnecessary now after recent changes, thus remove it.

ACKs for top commit:
  ajtowns:
    ACK 7df4508369
  jonatack:
    ACK 7df4508369

Tree-SHA512: 9742aeeeabe8690530bf74caa6ba296787028c52f4a3342afd193b05dbbb1f6645935c33ba0a5230199a09af01c666bd3c7fb16b48692a0d185356ea59a8ddbf
2023-10-03 09:57:46 -04:00
Hennadii Stepanov
88e5a02b8b
Merge bitcoin-core/gui#751: macOS, do not process actions during shutdown
bae209e387 gui: macOS, make appMenuBar part of the main app window (furszy)
e14cc8fc69 gui: macOS, do not process dock icon actions during shutdown (furszy)

Pull request description:

  As the 'QMenuBar' is created without a parent window in MacOS, the app crashes when the user presses the shutdown button and, right after it, triggers any action in the menu bar.

  This happens because the QMenuBar is manually deleted in the BitcoinGUI destructor but the events attached to it children actions are not disconnected, so QActions events such us the 'QMenu::aboutToShow' could try to access null pointers.

  Instead of guarding every single QAction pointer inside the QMenu::aboutToShow slot, or manually disconnecting all registered events in the destructor, we can check if a shutdown was requested and discard the event.

  The 'node' field is a ref whose memory is held by the main application class, so it is safe to use here. Events are disconnected prior destructing the main application object.

  Furthermore, the 'MacDockIconHandler::dockIconClicked' signal can make the app crash during shutdown for the very same reason. The 'show()' call triggers the 'QApplication::focusWindowChanged' event, which is connected to the 'minimize_action' QAction, which is also part of the app menu bar, which could no longer exist.

  Another cause of crashes stems from the shortcuts provided by the `appMenuBar` submenus during shutdown. For instance, executing actions like opening the information dialog (command + I) or the console dialog (command + T) lead to access null pointers. The second commit addresses and resolves these issues.
  Basically, in the present setup, we create a parentless `appMenuBar` whose submenus `QActions` are connected to `qApp` events (the app's global instance). However, at the `BitcoinGUI` destructor, we manually destruct this object without properly disconnecting the events. This leaves `qApp` events, such as `focusWindowChanged`, tied to submenus' `QAction` pointers, which causes the application to crash when it attempts to access them.

  Important Note:
  This happened to me few times. The worst consequence was an inconsistent chain state during IBD. Which triggered a full "replay blocks" process on the next startup. Which was painfully slow.

ACKs for top commit:
  RandyMcMillan:
    utACK bae209e
  hebasto:
    ACK bae209e387.

Tree-SHA512: 432e19c5f7e02c3165b7e7bd7f96f2a902bae5b5e439c2594db1c69d74ab6e0d4509d90f02db8c076f616e567e6a07492ede416ef651b5f749637398291b92fd
2023-10-03 13:56:41 +01:00
stickies-v
68f23f57d7
http: bugfix: track closed connection
It is possible that the client disconnects before the request is
handled. In those cases, evhttp_request_set_on_complete_cb is never
called, which means that on shutdown the server we'll keep waiting
endlessly.

By adding evhttp_connection_set_closecb, libevent automatically
cleans up those dead connections at latest when we shutdown, and
depending on the libevent version already at the moment of remote
client disconnect. In both cases, the bug is fixed.
2023-10-03 13:35:46 +01:00