Commit graph

409 commits

Author SHA1 Message Date
Pieter Wuille f2f32a3dee Push down use of cs_main into FindTxForGetData 2020-05-12 13:17:42 -07:00
Pieter Wuille c6131bf407 Abstract logic to determine whether to answer tx GETDATA 2020-05-12 13:16:55 -07:00
MarcoFalke e45fb7e0d2
Merge #18877: Serve cfcheckpt requests
23083856a5 [test] Add test for cfcheckpt (Jim Posen)
f9e00bb25a [net processing] Message handling for getcfcheckpt. (Jim Posen)
9ccaaba11e [init] Add -peerblockfilters option (Jim Posen)

Pull request description:

  Serve cfcheckpt messages if basic block filter index is enabled and `-peercfilters` is set.

  `NODE_COMPACT_FILTERS` is not signaled to peers, but functionality can be used for testing and serving pre-configured clients.

ACKs for top commit:
  jonatack:
    Code review re-ACK 23083856a5 the only change since my review @ 967e2b1 is an update required for #16224 that was merged yesterday.
  fjahr:
    re-ACK 23083856a5
  jkczyz:
    re-ACK 23083856a5
  ariard:
    re-Code Review ACK 2308385
  clarkmoody:
    Tested ACK 23083856a
  MarcoFalke:
    re-ACK 23083856a5 🌳
  theStack:
    ACK 23083856a5

Tree-SHA512: 8c751bbd7d1c31a413096462ae025c3d2f3163c7016cbec472a5f5ec267f8dd19a2dfc4d749876d7409c1db546e6fdd16461c6863effcfa0d3e993edcfa92a08
2020-05-12 09:03:07 -04:00
fanquake 7a5767423f
Merge #18808: [net processing] Drop unknown types in getdata
9847e205bf [docs] Improve commenting in ProcessGetData() (John Newbery)
2f032556e0 [test] test that an invalid GETDATA doesn't prevent processing of future messages (Amiti Uttarwar)
e257cf71c8 [net processing] ignore unknown INV types in GETDATA messages (Amiti Uttarwar)
047ceac142 [net processing] ignore tx GETDATA from blocks-only peers (Amiti Uttarwar)

Pull request description:

  Currently we'll stall peers that send us an unknown INV type in a GETDATA message. Be a bit more friendly and just drop the invalid request.

  Ditto for blocks-relay-only peers that send us a GETDATA for a transaction.

  There's a test for the first part. The second is difficult to test in the functional test framework since we aren't able to make blocks-relay-only connections.

ACKs for top commit:
  sipa:
    utACK 9847e205bf
  brakmic:
    ACK 9847e205bf
  luke-jr:
    utACK 9847e205bf
  naumenkogs:
    utACK 9847e20
  ajtowns:
    utACK 9847e205bf

Tree-SHA512: 6007f2fd839ffe737727f6fb8e8f083b2d9e05a510748f1d40b8f9be8fdf7b5419a36d8f1039923eec1ba2983e8f6f0436ec5fc196d9f6dcb0657f2ff8ff8e4c
2020-05-12 09:13:48 +08:00
Jim Posen f9e00bb25a [net processing] Message handling for getcfcheckpt.
If -peerblockfilters is configured, handle requests for cfcheckpt.
2020-05-08 16:36:19 -04:00
fanquake 551dc7f664
Merge #18806: net: remove is{Empty,Full} flags from CBloomFilter, clarify CVE fix
1ad8ea2b73 net: remove is{Empty,Full} flags from CBloomFilter, clarify CVE fix (Sebastian Falbesoner)

Pull request description:

  The BIP37 bloom filter class `CBloomFilter` contains two flags `isEmpty`/`isFull` together with an update method with the purpose to, according to the comments, "avoid wasting cpu", i.e. the mechanism should serve as an optimization for the trivial cases of empty (all bits zero) or full (all bits one) filters.
  However, the real reason of adding those flags (introduced with commit 37c6389c5a by gmaxwell) was a _covert fix_ of [CVE-2013-5700](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-5700), a vulnerability that allowed a divide-by-zero remote node crash.
  According to gmaxwell himself (https://github.com/bitcoin/bitcoin/pull/9060#issuecomment-257749165):
  > the IsEmpty/IsFull optimizations were largely a pretextual optimization intended to make unexploitable a remote crash vulnerability (integer division by zero) that existed in the original bloom filtering code without disclosing it. I'm doubtful that they are all that useful. :)

  For more information on how to trigger this crash, see PR https://github.com/bitcoin/bitcoin/pull/18515 which contains a detailled description and a regression test. It has also been discussed on a [recent PR club meeting on fuzzing](https://bitcoincore.reviews/18521.html).

  The covert fix code already led to issues and PR based on the wrong assumption that the flags are there for optimization reasons (see #16886 and #16922). This PR gets rid of the flags and the update method and just focuses on the CVE fix itself, i.e. it can be seen as a revert of the covert fix commit modulo the actual fix.

ACKs for top commit:
  meshcollider:
    utACK 1ad8ea2b73
  laanwj:
    Concept and code review ACK 1ad8ea2b73
  jkczyz:
    ACK 1ad8ea2b73
  MarcoFalke:
    ACK 1ad8ea2b73
  fjahr:
    Code review ACK 1ad8ea2b73

Tree-SHA512: 29f7ff9faece0285e11e16c024851f5bcb772dec64118ccc3f9067ec256267ec8e1b1e3105c7de2a72fd122c3b085e8fc840ab8f4e49813f1cc7a444df1867f7
2020-05-06 15:40:06 +08:00
John Newbery 9847e205bf [docs] Improve commenting in ProcessGetData() 2020-04-29 19:34:01 -04:00
Amiti Uttarwar e257cf71c8 [net processing] ignore unknown INV types in GETDATA messages
Co-Authored-By: John Newbery <john@johnnewbery.com>
2020-04-29 10:54:55 -04:00
Amiti Uttarwar 047ceac142 [net processing] ignore tx GETDATA from blocks-only peers
Co-Authored-By: John Newbery <john@johnnewbery.com>
2020-04-29 10:54:48 -04:00
fanquake 0ef0d33f75
Merge #18038: P2P: Mempool tracks locally submitted transactions to improve wallet privacy
50fc4df6c4 [mempool] Persist unbroadcast set to mempool.dat (Amiti Uttarwar)
297a178536 [test] Integration tests for unbroadcast functionality (Amiti Uttarwar)
6851502472 [refactor/test] Extract P2PTxInvStore into test framework (Amiti Uttarwar)
dc1da48dc5 [wallet] Update the rebroadcast frequency to be ~1/day. (Amiti Uttarwar)
e25e42f20a [p2p] Reattempt initial send of unbroadcast transactions (Amiti Uttarwar)
7e93eecce3 [util] Add method that returns random time in milliseconds (Amiti Uttarwar)
89eeb4a333 [mempool] Track "unbroadcast" transactions (Amiti Uttarwar)

Pull request description:

  This PR introduces mempool tracking of unbroadcast transactions and periodic reattempts at initial broadcast. This is a part of the rebroadcast project, and a standalone privacy win.

  The current rebroadcast logic is terrible for privacy because 1. only the source wallet rebroadcasts transactions and 2. it does so quite frequently. In the current system, if a user submits a transaction that does not immediately get broadcast to the network (eg. they are offline), this "rebroadcast" behavior is the safety net that can actually serve as the initial broadcast. So, keeping the attempts frequent is important for initial delivery within a reasonable timespan.

  This PR aims to improve # 2 by reducing the wallet rebroadcast frequency to ~1/day from ~1/15 min. It achieves this by separating the notion of initial broadcast from rebroadcasts. With these changes, the mempool tracks locally submitted transactions & periodically reattempts initial broadcast. Transactions submitted via the wallet or RPC are added to an "unbroadcast" set & are removed when a peer sends a `getdata` request, or the transaction is removed from the mempool. Every 10-15 minutes, the node reattempts an initial broadcast. This enables reducing the wallet rebroadcast frequency while ensuring the transactions will be propagated to the network.

  For privacy improvements around # 1, please see #16698.
  Thank you to gmaxwell for the idea of how to break out this subset of functionality (https://github.com/bitcoin/bitcoin/pull/16698#issuecomment-571399346)

ACKs for top commit:
  fjahr:
    Code review ACK 50fc4df6c4
  MarcoFalke:
    ACK 50fc4df6c4, I think this is ready for merge now 👻
  amitiuttarwar:
    The current tip `50fc4df` currently has 6 ACKs on it, so I've opened #18807 to address the last bits.
  jnewbery:
    utACK 50fc4df6c4.
  ariard:
    Code Review ACK 50fc4df (minor points no need to invalid other ACKs)
  robot-visions:
    ACK 50fc4df6c4
  sipa:
    utACK 50fc4df6c4
  naumenkogs:
    utACK 50fc4df

Tree-SHA512: 2dd935d645d5e209f8abf87bfaa3ef0e4492705ce7e89ea64279cb27ffd37f4727fa94ad62d41be331177332f8edbebf3c7f4972f8cda10dd951b80a28ab3c0f
2020-04-29 16:32:37 +08:00
Sebastian Falbesoner 1ad8ea2b73 net: remove is{Empty,Full} flags from CBloomFilter, clarify CVE fix 2020-04-28 19:27:22 +02:00
Amiti Uttarwar e25e42f20a [p2p] Reattempt initial send of unbroadcast transactions
Every 10-15 minutes, the scheduler kicks off a job that queues unbroadcast
transactions onto each node.
2020-04-23 14:42:25 -07:00
Amiti Uttarwar 89eeb4a333 [mempool] Track "unbroadcast" transactions
- Mempool tracks locally submitted transactions (wallet or rpc)
- Transactions are removed from set when the node receives a GETDATA request
  from a peer, or if the transaction is removed from the mempool.
2020-04-23 14:42:25 -07:00
John Newbery e9ea95a30d [net processing] Move all const declarations to top of net_processing.cpp 2020-04-23 12:54:06 -04:00
John Newbery b8580cacc7 [net processing] Move net processing consts to net_processing.cpp 2020-04-23 12:54:03 -04:00
MarcoFalke da4cbb7927
Merge #18544: net: limit BIP37 filter lifespan (active between 'filterload'..'filterclear')
a9ecbdfcaa test: add more inactive filter tests to p2p_filter.py (Sebastian Falbesoner)
5eae034996 net: limit BIP37 filter lifespan (active between 'filterload' and 'filterclear') (Sebastian Falbesoner)

Pull request description:

  This PR fixes https://github.com/bitcoin/bitcoin/issues/18483. On the master branch, there is currently _always_ a BIP37 filter set for every peer: if not a specific filter is set through a `filterload` message, a default match-everything filter is instanciated and pointed to via the `CBloomFilter` default constructor; that happens both initially, when the containing structure `TxRelay` is constructed:

  c0b389b335/src/net.h (L812)

  and after a loaded filter is removed again through a `filterclear` message:

  c0b389b335/src/net_processing.cpp (L3201)

  The behaviour was introduced by commit 37c6389c5a (an intentional covert fix for [CVE-2013-5700](https://github.com/bitcoin/bitcoin/pull/18515), according to gmaxwell).

  This default match-everything filter leads to some unintended side-effects:
  1. `getdata` request for filtered blocks (i.e. type `MSG_FILTERED_BLOCK`) are always responded to with `merkleblock`s, even if no filter was set by the peer, see issue #18483 (strictly speaking, this is a violation of BIP37) c0b389b335/src/net_processing.cpp (L1504-L1507)
  2. if a peer sends a `filteradd` message without having loaded a filter via `filterload` before, the intended increasing of the banscore never happens (triggered if `bad` is set to true, a few lines below) c0b389b335/src/net_processing.cpp (L3182-L3186)

  This PR basically activates the `else`-branch code paths for all checks of `pfilter` again (on the master branch, they are dead code) by limiting the pointer's lifespan: instead of always having a filter set, the `pfilter` is only pointing to a `CBloomFilter`-instance after receiving a `filterload` message and the instance is destroyed again (and the pointer nullified) after receiving a `filterclear` message.

  Here is a before/after comparison in behaviour:
  | code part / scenario                          |    master branch                   |   PR branch                                          |
  | --------------------------------------------- | ---------------------------------- | ---------------------------------------------------- |
  | `getdata` processing for `MSG_FILTERED_BLOCK` | always responds with `merkleblock` | only responds if filter was set via `filterload`     |
  | `filteradd` processing, no filter was loaded  | nothing                            | peer's banscore increases by 100 (i.e. disconnect)   |

  On the other code parts where `pfilter` is checked there is no change in the logic behaviour (except that `CBloomFilter::IsRelevantAndUpdate()` is unnecessarily called and immediately returned in the master branch).
  Note that the default constructor of `CBloomFilter` is only used for deserializing the received `filterload` message and nowhere else. The PR also contains a functional test checking that sending `getdata` for filtered blocks is ignored by the node if no bloom filter is set.

ACKs for top commit:
  MarcoFalke:
    re-ACK a9ecbdfcaa, only change is in test code 🕙

Tree-SHA512: 1a656a6d74ccaf628e7fdca063ba63fbab2089e0b6d0a11be9bbd387c2ee6d3230706ff8ffc1a55711481df3d4547137dd7c9d9184d89eaa43ade4927792d0b6
2020-04-20 06:59:53 -04:00
MarcoFalke 29893ec875
Merge #18454: net: Make addr relay mockable, add test
fa1da3d4bf test: Add basic addr relay test (MarcoFalke)
fa1793c1c4 net: Pass connman const when relaying address (MarcoFalke)
fa47a0b003 net: Make addr relay mockable (MarcoFalke)

Pull request description:

  As usual:

  * Switch to std::chrono time to be type-safe and mockable
  * Add basic test that relies on mocktime to add code coverage

ACKs for top commit:
  naumenkogs:
    utACK  fa1da3d
  promag:
    ACK fa1da3d4bf (fabe56e44b6f683e24e37246a7a8851190947cb3 before https://github.com/bitcoin/bitcoin/pull/18454#issuecomment-607866453), fa5bf23d527a450e72c2bf13d013e5393b664ca3 was dropped since last review.

Tree-SHA512: 0552bf8fcbe375baa3cab62acd8c23b2994efa47daff818ad1116d0ffaa0b9e520dc1bca2bbc68369b25584e85e54861fe6fd0968de4f503b95439c099df9bd7
2020-04-10 10:12:46 -04:00
Sebastian Falbesoner 5eae034996 net: limit BIP37 filter lifespan (active between 'filterload' and 'filterclear')
Previously, a default match-everything bloom filter was set for every peer,
i.e. even before receiving a 'filterload' message and after receiving a
'filterclear' message code branches checking for the existence of the filter
by testing the pointer "pfilter" were _always_ executed.
2020-04-09 11:26:24 +02:00
MarcoFalke 7777e3624f
scripted-diff: Replace strCommand with msg_type
-BEGIN VERIFY SCRIPT-
sed -i 's/\<strCommand\>/msg_type/g' ./src/net_processing.cpp ./src/test/fuzz/process_message.cpp
-END VERIFY SCRIPT-
2020-04-06 08:00:34 +08:00
MarcoFalke fa1793c1c4
net: Pass connman const when relaying address 2020-04-02 21:56:20 +08:00
MarcoFalke fa47a0b003
net: Make addr relay mockable 2020-03-27 17:58:51 -04:00
Wladimir J. van der Laan 312d27b11c
Merge #17477: Remove the mempool's NotifyEntryAdded and NotifyEntryRemoved signals
e57980b473 [mempool] Remove NotifyEntryAdded and NotifyEntryRemoved callbacks (John Newbery)
2dd561f361 [validation] Remove pool member from ConnectTrace (John Newbery)
969b65f3f5 [validation] Remove NotifyEntryRemoved callback from ConnectTrace (John Newbery)
5613f9842b [validation] Remove conflictedTxs from PerBlockConnectTrace (John Newbery)
cdb893443c [validation interface] Remove vtxConflicted from BlockConnected (John Newbery)
1168394d75 [wallet] Notify conflicted transactions in TransactionRemovedFromMempool (John Newbery)

Pull request description:

  These boost signals were added in #9371, before we had a `TransactionRemovedFromMempool` method in the validation interface. The `NotifyEntryAdded` callback was used by validation to build a vector of conflicted transactions when connecting a block, which the wallet was notified of in the `BlockConnected` CValidationInterface callback.

  Now that we have a `TransactionRemovedFromMempool` callback, we can fire that signal directly from the mempool for conflicted transactions.

  Note that #9371 was implemented to ensure `-walletnotify` events were fired for these conflicted transaction. We inadvertently stopped sending these notifications in #16624 (Sep 2019 commit 7e89994). We should probably fix that, but in a different PR.

ACKs for top commit:
  jonatack:
    Re-ACK e57980b
  ryanofsky:
    Code review ACK e57980b473, no code changes since previous review, but helpful new code comments have been added and the PR description is now more clear about where the old code came from

Tree-SHA512: 3bdbaf1ef2731e788462d4756e69c42a1efdcf168691ce1bbfdaa4b7b55ac3c5b1fd4ab7b90bcdec653703600501b4224d252cfc086aef28f9ce0da3b0563a69
2020-03-19 17:26:51 +01:00
Vasil Dimov 7d8e1dec3b
net: fix use-after-free in tests
In PeerLogicValidation::PeerLogicValidation() we would schedule a lambda
function to execute later, capturing the local variable
`consensusParams` by reference.

Presumably this was considered safe because `consensusParams` is a
reference itself to a global variable which is not supposed to change,
but it can in tests.

Fixes https://github.com/bitcoin/bitcoin/issues/18372
2020-03-18 13:03:26 +01:00
MarcoFalke ce87d5613a
Merge #18289: refactor: Make scheduler methods type safe
fa36f3a295 refactor: move DUMP_BANS_INTERVAL to banman.h (MarcoFalke)
fadafb83cf scheduler: Make schedule* methods type safe (MarcoFalke)
fa70ccc6c4 scheduler: Use C++11 member initialization, add shutdown assert (MarcoFalke)

Pull request description:

  Main benefit is that stuff like `15 * 60 * 1000` is replaced by `minutes{15}`

ACKs for top commit:
  vasild:
    ACK fa36f3a (code review, not tested)
  ajtowns:
    ACK fa36f3a295
  jonatack:
    ACK fa36f3a

Tree-SHA512: f35f1a1d643dfa676bd47474659f6492ed05cca04cdb556064b126f654a6a44a4b93fcaddcdcd41faf81b8f11439c11e5c7ab88685ba2eef12f7188843d17ad8
2020-03-17 16:34:53 -04:00
MarcoFalke fa7fea3654
refactor: Remove mempool global from net
This refactor does two things:
* Pass mempool in to PeerLogicValidation
* Pass m_mempool around where needed
2020-03-12 09:23:56 -04:00
John Newbery cdb893443c [validation interface] Remove vtxConflicted from BlockConnected
The wallet now uses TransactionRemovedFromMempool to be notified about
conflicted wallet, and no other clients use vtxConflicted.
2020-03-11 18:38:33 -04:00
practicalswift fd1dae10b4 tests: Add fuzzing harness for ProcessMessage(...) 2020-03-11 06:57:55 +00:00
MarcoFalke fadafb83cf
scheduler: Make schedule* methods type safe 2020-03-10 09:47:32 -04:00
Jeffrey Czyz 0aed17ef28 Refactor FormatStateMessage into ValidationState 2020-02-27 17:59:07 -08:00
MarcoFalke facb71576c
net: Remove forcerelay of rejected txs 2020-02-11 07:44:12 -08:00
Jon Atack 9a299a59cc
net: reference instead of copy in BlockConnected range loop
to fix -Wrange-loop-analysis warning introduced in a029e18
2020-02-02 10:27:47 +01:00
Jonas Schnelli d104aa0ace
Merge #17951: Use rolling bloom filter of recent block txs for AlreadyHave() check
a029e18c2b Use rolling bloom filter of recent block tx's for AlreadyHave() check (Suhas Daftuar)

Pull request description:

  In order to determine whether to download or process a relayed transaction, we first try to check whether we already have the transaction -- either in the mempool, in our filter of recently rejected transactions, in our orphan pool, or already confirmed in a block.

  Prior to this commit, the heuristic for checking whether a transaction was confirmed in a block is based on whether there's a coin cache entry corresponding to the 0- or 1-index vout of the tx. While that is a quick check, it is very imprecise (eg if those outputs were already spent in another block, we wouldn't detect that the transaction has already been confirmed) -- we can do better by just keeping a rolling bloom filter of the transactions in recent blocks, which will better capture the case of a transaction which has been confirmed and then fully spent.

  This should reduce the bandwidth that we waste by requesting transactions which will not be accepted to the mempool.

  To avoid relay problems for transactions which have been included in a recent block but then reorged out of the chain, we clear the bloom filter whenever a block is disconnected.

ACKs for top commit:
  MarcoFalke:
    re-ACK a029e18c2b only stylistic and comment fixups 🍴
  sipa:
    utACK a029e18c2b
  jonatack:
    Code review ACK a029e18c2b also built/ran tests and am running bitcoind with mempool debug logging and custom logging. Looked a bit into CRollingBloomFilter and also the mempool median time past checks mentioned above; I don't have a deep understanding of those areas yet but the concept here and changes LGTM. Tests and other optimisations could be added as a follow-up. In favor of seeing this move forward if no major immediate concerns.

Tree-SHA512: 784c9a35bcd3af5db469063ac7d26b4bac430e451e5637a34d8a538c3ffd1433abdd3f06e5584e7a84bfa9e791449e61819397b5a6c7890fa59d78ec3ba507b2
2020-01-31 14:42:59 +01:00
Suhas Daftuar a029e18c2b Use rolling bloom filter of recent block tx's for AlreadyHave() check
In order to determine whether to download or process a relayed transaction, we
try to determine if we already have the transaction, either in the mempool, in
our recently rejected filter, in our orphan pool, or already confirmed in the
chain itself.

Prior to this commit, the heuristic for checking the chain is based on whether
there's an output corresponding to the 0- or 1-index vout in our coin cache.
While that is a quick check, it is very imprecise (say if those outputs were
already spent in a block) -- we can do better by just keeping a rolling bloom
filter of the transactions in recent blocks, which will capture the case of a
transaction which has been confirmed and then fully spent already.

To avoid relay problems for transactions which have been included in a recent
block but then reorged out of the chain, we clear the bloom filter whenever a
block is disconnected.
2020-01-29 09:37:21 -05:00
Ben Woosley 297e098557
Fix doxygen errors
Identified via -Wdocumentation, e.g.:

  ./rpc/rawtransaction_util.h:31:13: error: parameter 'prevTxs' not found in the function declaration [-Werror,-Wdocumentation]
    * @param  prevTxs       Array of previous txns outputs that tx depends on but may not yet be in the block chain
              ^~~~~~~
  ./rpc/rawtransaction_util.h:31:13: note: did you mean 'prevTxsUnival'?
    * @param  prevTxs       Array of previous txns outputs that tx depends on but may not yet be in the block chain
              ^~~~~~~
              prevTxsUnival

  netbase.cpp:766:11: error: parameter 'outProxyConnectionFailed[out]' not found in the function declaration [-Werror,-Wdocumentation]
   * @param outProxyConnectionFailed[out] Whether or not the connection to the
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  netbase.cpp:766:11: note: did you mean 'outProxyConnectionFailed'?
   * @param outProxyConnectionFailed[out] Whether or not the connection to the
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            outProxyConnectionFailed
2020-01-16 18:25:11 -08:00
MarcoFalke e09c701e01 scripted-diff: Bump copyright of files changed in 2020
-BEGIN VERIFY SCRIPT-
./contrib/devtools/copyright_header.py update ./
-END VERIFY SCRIPT-
2020-01-15 02:18:00 +07:00
MarcoFalke 6cbe620964 scripted-diff: Replace CCriticalSection with RecursiveMutex
-BEGIN VERIFY SCRIPT-
 # Delete outdated alias for RecursiveMutex
 sed -i -e '/CCriticalSection/d'                 ./src/sync.h
 # Replace use of outdated alias with RecursiveMutex
 sed -i -e 's/CCriticalSection/RecursiveMutex/g' $(git grep -l CCriticalSection)
-END VERIFY SCRIPT-
2020-01-15 01:43:46 +07:00
Wladimir J. van der Laan 190a4051fd
Merge #17762: net: Log to net category for exceptions in ProcessMessages
4bdd68f301 Add missing typeinfo includes (Wladimir J. van der Laan)
4d88c3dcb6 net: Log to net category for exceptions in ProcessMessages (Wladimir J. van der Laan)

Pull request description:

  Remove the forest of special exceptions based on string matching, and simply log a short message to the NET logging category when an exception happens during packet processing. It is not good to panick end users with verbose errors (let alone writing to stderr) when any peer can generate them.

ACKs for top commit:
  MarcoFalke:
    re-ACK 4bdd68f301 (only change is adding includes) 🕕
  promag:
    ACK 4bdd68f301, could squash.

Tree-SHA512: a005591a3202b005c75e01dfa54249db3992e2f9eefa8b3d9d435acf66130417716ed926ce4e045179cf43788f1abc7362d999750681a9c80b318373d611c366
2020-01-02 21:39:00 +01:00
Wladimir J. van der Laan 4bdd68f301 Add missing typeinfo includes
The use of `typeid()` for logging exception types requires this include
according to https://en.cppreference.com/w/cpp/language/typeid.
2020-01-02 20:54:15 +01:00
MarcoFalke aaaaad6ac9
scripted-diff: Bump copyright of files changed in 2019
-BEGIN VERIFY SCRIPT-
./contrib/devtools/copyright_header.py update ./
-END VERIFY SCRIPT-
2019-12-30 10:42:20 +13:00
Wladimir J. van der Laan 4d88c3dcb6 net: Log to net category for exceptions in ProcessMessages
Remove the forest of special exceptions, and simply log a short
message to the NET logging category when an exception happens during
packet processing. It is not good to panick end users with errors
that any peer can generate (let alone writing to stderr).
2019-12-17 15:56:49 +01:00
MarcoFalke c7e6b3b343
Merge #17243: p2p: add PoissonNextSend method that returns mockable time
1a8f0d5a74 [tools] update nNextInvSend to use mockable time (Amiti Uttarwar)
4de630354f [tools] add PoissonNextSend method that returns mockable time (Amiti Uttarwar)

Pull request description:

  Introduce a Poisson helper method that wraps the existing method to return `std::chrono::duration` type, which is mockable.

  Needed for https://github.com/bitcoin/bitcoin/pull/16698.

ACKs for top commit:
  ajtowns:
    ACK 1a8f0d5a74
  MarcoFalke:
    re-ACK 1a8f0d5a74
  naumenkogs:
    ACK 1a8f0d5, and let's merge it and come back to it later.

Tree-SHA512: 7e2325d7c55fc0b4357cb86b83e0c218ba269f678c1786342d8bc380bfd9696373bc24ff124b9ff17a6e761c62b2b44ff5247c3911e2afdc7cc5c20417e8290b
2019-11-05 12:38:28 -05:00
Amiti Uttarwar 1a8f0d5a74 [tools] update nNextInvSend to use mockable time 2019-11-05 11:12:10 +01:00
MarcoFalke 8f9df2ed88
Merge #17164: p2p: Avoid allocating memory for addrKnown where we don't need it
b6d2183858 Minor refactoring to remove implied m_addr_relay_peer. (User)
a552e8477c added asserts to check m_addr_known when it's used (User)
090b75c14b p2p: Avoid allocating memory for addrKnown where we don't need it (User)

Pull request description:

  We should allocate memory for addrKnown filter only for those peers which are expected to participate in address relay.

  Currently, we do it for all peers (including SPV and block-relay-only),  which results in extra RAM where it's not needed.

  Upd:
  In future, we would still allow SPVs to ask for addrs, so allocation still will be done by default.
  However, they will be able to opt-out via [this proposal](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-October/017428.html) and then we could save some more memory.
  This PR still saves memory for block-relay-only peers immediately after merging.

Top commit has no ACKs.

Tree-SHA512: e84d93b2615556d466f5ca0e543580fde763911a3bfea3127c493ddfaba8f05c8605cb94ff795d165af542b594400995a2c51338185c298581408687e7812463
2019-11-04 11:17:20 -05:00
Wladimir J. van der Laan 3c40bc6726
Merge #15921: validation: Tidy up ValidationState interface
3004d5a12d [validation] Remove fMissingInputs from AcceptToMemoryPool() (John Newbery)
c428622a5b [validation] Remove unused first_invalid parameter from ProcessNewBlockHeaders() (John Newbery)
7204c6434b [validation] Remove useless ret parameter from Invalid() (John Newbery)
1a37de4b31 [validation] Remove error() calls from Invalid() calls (John Newbery)
067981e492 [validation] Tidy Up ValidationResult class (John Newbery)
a27a2957ed [validation] Add CValidationState subclasses (John Newbery)

Pull request description:

  Carries out some remaining tidy-ups remaining after PR 15141:

  - split ValidationState into TxValidationState and BlockValidationState (commit from ajtowns)
  - various minor code style tidy-ups to the ValidationState class
  - remove the useless `ret` parameter from `ValidationState::Invalid()`
  - remove the now unused `first_invalid` parameter from `ProcessNewBlockHeaders()`
  - remove the `fMissingInputs` parameter from `AcceptToMemoryPool()`, and deal with missing inputs the same way as other errors by using the `TxValidationState` object.

  Tip for reviewers (thanks ryanofsky!): The first commit ("[validation] Add CValidationState subclasses" ) is huge and can be easier to start reviewing if you revert the rote, mechanical changes:

  Substitute the commit hash of commit "[validation] Add CValidationState subclasses" for <CommitHash> in the commands below.

  ```sh
  git checkout <CommitHash>
  git grep -l ValidationState | xargs sed -i 's/BlockValidationState\|TxValidationState/CValidationState/g'
  git grep -l ValidationResult | xargs sed -i 's/BlockValidationResult\|TxValidationResult/ValidationInvalidReason/g'
  git grep -l MaybePunish | xargs sed -i 's/MaybePunishNode\(ForBlock\|ForTx\)/MaybePunishNode/g'
  git diff HEAD^
  ```

  After that it's possible to easily see the mechanical changes with:

  ```sh
  git log -p -n1 -U0 --word-diff-regex=. <CommitHash>
  ```

ACKs for top commit:
  laanwj:
    ACK 3004d5a12d
  amitiuttarwar:
    code review ACK 3004d5a12d. Also built & ran tests locally.
  fjahr:
    Code review ACK 3004d5a12d . Only nit style change and pure virtual destructor added since my last review.
  ryanofsky:
    Code review ACK 3004d5a12d. Just whitespace change and pure virtual destructor added since last review.

Tree-SHA512: 511de1fb380a18bec1944ea82b513b6192df632ee08bb16344a2df3c40811a88f3872f04df24bc93a41643c96c48f376a04551840fd804a961490d6c702c3d36
2019-10-30 15:37:34 +01:00
John Newbery 3004d5a12d [validation] Remove fMissingInputs from AcceptToMemoryPool()
Handle this failure in the same way as all other failures: call Invalid()
with the reasons for the failure.
2019-10-29 15:46:45 -04:00
John Newbery c428622a5b [validation] Remove unused first_invalid parameter from ProcessNewBlockHeaders()
No callers use the returned value in first_invalid. Remove it from the
function signature and don't set it in the function.
2019-10-29 15:46:45 -04:00
John Newbery a27a2957ed [validation] Add CValidationState subclasses
Split CValidationState into TxValidationState and BlockValidationState
to store validation results for transactions and blocks respectively.
2019-10-29 15:46:45 -04:00
Russell Yanofsky e6f4f895d5 Pass NodeContext, ConnMan, BanMan references more places
So g_connman and g_banman globals can be removed next commit.
2019-10-28 10:30:51 -04:00
fanquake badca85e2c
Merge #16202: p2p: Refactor network message deserialization
ed2dc5e48a Add override/final modifiers to V1TransportDeserializer (Pieter Wuille)
f342a5e61a Make resetting implicit in TransportDeserializer::Read() (Pieter Wuille)
6a91499496 Remove oversized message detection from log and interface (Pieter Wuille)
b0e10ff4df Force CNetMessage::m_recv to use std::move (Jonas Schnelli)
efecb74677 Use adapter pattern for the network deserializer (Jonas Schnelli)
1a5c656c31 Remove transport protocol knowhow from CNetMessage / net processing (Jonas Schnelli)
6294ecdb8b Refactor: split network transport deserializing from message container (Jonas Schnelli)

Pull request description:

  **This refactors the network message deserialization.**

  * It transforms the `CNetMessage` into a transport protocol agnostic message container.
  * A new class `TransportDeserializer` (unique pointer of `CNode`)  is introduced, handling the network buffer reading and the decomposing to a `CNetMessage`
  * **No behavioral changes** (in terms of disconnecting, punishing)
  * Moves the checksum finalizing into the `SocketHandler` thread (finalizing was in `ProcessMessages` before)

  The **optional last commit** makes the `TransportDeserializer` following an adapter pattern (polymorphic interface) to make it easier to later add a V2 transport protocol deserializer.

  Intentionally not touching the sending part.

  Pre-Requirement for BIP324 (v2 message transport protocol).
  Replacement for #14046 and inspired by a [comment](https://github.com/bitcoin/bitcoin/pull/14046#issuecomment-431528330) from sipa

ACKs for top commit:
  promag:
    Code review ACK ed2dc5e48a.
  marcinja:
    Code review ACK ed2dc5e48a
  ryanofsky:
    Code review ACK ed2dc5e48a. 4 cleanup commits added since last review. Unaddressed comments:
  ariard:
    Code review and tested ACK ed2dc5e.

Tree-SHA512: bab8d87464e2e8742529e488ddcdc8650f0c2025c9130913df00a0b17ecdb9a525061cbbbd0de0251b76bf75a8edb72e3ad0dbf5b79e26f2ad05d61b4e4ded6d
2019-10-28 09:15:59 -04:00
User a552e8477c added asserts to check m_addr_known when it's used 2019-10-25 16:28:14 -04:00
MarcoFalke fce7c75422
Merge #16851: Continue relaying transactions after they expire from mapRelay
168b781fe7 Continue relaying transactions after they expire from mapRelay (Anthony Towns)

Pull request description:

  This change allows peers to request transactions even after they've expired from mapRelay and even if they're not doing mempool requests. This is intended to allow for CPFP of old transactions -- if parent tx P wasn't relayed due to low fees, then a higher fee rate child C is relayed, peers will currently request the parent P, but we prior to this patch, we will not relay it due to it not being in mapRelay.

ACKs for top commit:
  MarcoFalke:
    re-ACK 168b781fe7 (only change is comment fixup)
  sdaftuar:
    re-ACK 168b781fe7
  sipa:
    ACK 168b781fe7

Tree-SHA512: b206666dd1450cd0a161ae55fd1a7eda2c3d226842ba27d91fe463b551fd924b65b92551b14d6786692e15cf9a9a989666550dfc980b48ab0f8d4ca305bc7762
2019-10-24 17:50:42 -04:00
Wladimir J. van der Laan b688b859db
Merge #17004: validation: Remove REJECT code from CValidationState
9075d13153 [docs] Add release notes for removal of REJECT reasons (John Newbery)
04a2f326ec [validation] Fix REJECT message comments (John Newbery)
e9d5a59e34 [validation] Remove REJECT code from CValidationState (John Newbery)
0053e16714 [logging] Don't log REJECT code when transaction is rejected (John Newbery)
a1a07cfe99 [validation] Fix peer punishment for bad blocks (John Newbery)

Pull request description:

  We no longer send BIP 61 REJECT messages, so there's no need to set
  a REJECT code in the CValidationState object.

  Note that there is a minor bug fix in p2p behaviour here. Because the
  call to `MaybePunishNode()` in `PeerLogicValidation::BlockChecked()` only
  previously happened if the REJECT code was > 0 and < `REJECT_INTERNAL`,
  then there are cases were `MaybePunishNode()` can get called where it
  wasn't previously:

  - when `AcceptBlockHeader()` fails with `CACHED_INVALID`.
  - when `AcceptBlockHeader()` fails with `BLOCK_MISSING_PREV`.

  Note that `BlockChecked()` cannot fail with an 'internal' reject code. The
  only internal reject code was `REJECT_HIGHFEE`, which was only set in
  ATMP.

  This reverts a minor bug introduced in 5d08c9c579.

ACKs for top commit:
  ariard:
    ACK 9075d13, changes since last reviewed are splitting them in separate commits to ease understanding and fix nits
  fjahr:
    ACK 9075d13153, confirmed diff to last review was fixing nits in docs/comments.
  ryanofsky:
    Code review ACK 9075d13153. Only changes since last review are splitting the main commit and updating comments

Tree-SHA512: 58e8a1a4d4e6f156da5d29fb6ad6a62fc9c594bbfc6432b3252e962d0e9e10149bf3035185dc5320c46c09f3e49662bc2973ec759679c0f3412232087cb8a3a7
2019-10-24 10:49:45 +02:00
Anthony Towns 168b781fe7 Continue relaying transactions after they expire from mapRelay 2019-10-23 11:36:24 +10:00
Jonas Schnelli 1a5c656c31
Remove transport protocol knowhow from CNetMessage / net processing 2019-10-18 08:56:08 +02:00
Jonas Schnelli 6294ecdb8b
Refactor: split network transport deserializing from message container 2019-10-18 08:56:06 +02:00
User 090b75c14b p2p: Avoid allocating memory for addrKnown where we don't need it 2019-10-16 17:06:20 -04:00
practicalswift 084e17cebd Remove unused includes 2019-10-15 22:56:43 +00:00
John Newbery 04a2f326ec [validation] Fix REJECT message comments 2019-10-10 13:31:57 -04:00
John Newbery a1a07cfe99 [validation] Fix peer punishment for bad blocks
Because the call to MaybePunishNode() in
PeerLogicValidation::BlockChecked() only previously happened if the
REJECT code was > 0 and < REJECT_INTERNAL, then there are cases were
MaybePunishNode() can get called where it wasn't previously:

- when AcceptBlockHeader() fails with CACHED_INVALID.
- when AcceptBlockHeader() fails with BLOCK_MISSING_PREV.

Note that BlockChecked() cannot fail with an 'internal' reject code. The
only internal reject code was REJECT_HIGHFEE, which was only set in
ATMP.

This change restores the behaviour pre-commit
5d08c9c579 which did punish nodes that
sent us CACHED_INVALID and BLOCK_MISSING_PREV blocks.
2019-10-10 11:17:01 -04:00
Wladimir J. van der Laan c08bf2b574
Merge #15437: p2p: Remove BIP61 reject messages
fa25f43ac5 p2p: Remove BIP61 reject messages (MarcoFalke)

Pull request description:

  Reject messages (BIP 61) appear in the following settings:

  * Parsing of reject messages (in case `-debug=net` is set, off by default). This has only been used for a single `LogPrint` call for several releases now. Such logging is completely meaningless to us and should thus be removed.

  * The sending of reject messages (in case `-enablebip61` is set, off by default). This can be used to debug a node that is under our control. Instead of hacking this debugging into the p2p protocol, it could be more easily achieved by parsing the debug log. (Use `-printtoconsole` to have it as stream, or read from the `debug.log` file like our python function `assert_debug_log` in the test framework does)

  Having to maintain all of this logic and code to accommodate debugging, which can be achieved by other means a lot easier, is a burden. It makes review on net processing changes a lot harder, since the reject message logic has to be carried around without introducing any errors or DOS vectors.

ACKs for top commit:
  jnewbery:
    utACK fa25f43ac5
  laanwj:
    I'm still not 100% convinced that I like getting rid of BIP61 conceptually, but apparently everyone wants it, code review ACK fa25f43ac5.
  ryanofsky:
    Code review ACK fa25f43ac5

Tree-SHA512: daf55254202925e56be3d6cfb3c1c804e7a82cecb1dd1e5bd7b472bae989fd68ac4f21ec53fc46751353056fd645f7f877bebcb0b40920257991423a3d99e0be
2019-10-09 11:51:58 +02:00
Gregory Sanders 8e59af55aa feefilter: Compute the absolute fee rather than stored rate to match mempool acceptance logic 2019-10-03 14:03:27 -04:00
MarcoFalke fa25f43ac5
p2p: Remove BIP61 reject messages 2019-10-02 10:39:14 -04:00
MarcoFalke faec689bed
txmempool: Make entry time type-safe (std::chrono) 2019-09-23 08:00:14 -04:00
Wladimir J. van der Laan feb162d500
Merge #14696: qa: Add explicit references to related CVE's in p2p_invalid_block test.
0c62e3aa73 New regression testing for CVE-2018-17144, CVE-2012-2459, and CVE-2010-5137. (lucash-dev)
38bfca6bb2 Added comments referencing multiple CVEs in tests and production code. (lucash-dev)

Pull request description:

  This functional test includes two scenarios that test for regressions of vulnerabilities, but they are only briefly described. There are freely available documents explaining in detail the issues, but without explicit mentions, the developer trying to maintain the code needs an additional step of digging in commit history and PR conversations to figure it out.
  Added comments to explicitly mention  CVE-2018-17144 and CVE-2012-2459, for more complete documentation.
  This improves developer experience by making understanding the tests easier.

ACKs for top commit:
  laanwj:
    ACK 0c62e3aa73, checked the CVE numbers, thanks for adding documentation

Tree-SHA512: 3ee05351745193b8b959e4a25d50f25a693b2d24b0732ed53cf7d5882df40b5dd0f1877bd5c69cffb921d4a7acf9deb3cc1160b96dc730d9b5984151ad06b7c9
2019-09-18 16:00:54 +02:00
James O'Beirne 82e53f37e1 doc: add comments clarifying how local services are advertised
Recent questions have come up regarding dynamic service registration
(see https://github.com/bitcoin/bitcoin/pull/16442#discussion_r308702676
and the assumeutxo project, which needs to dynamically flip NODE_NETWORK).

While investigating how dynamic service registration might work, I was
confused about how we convey local services to peers. This adds some
documentation that hopefully clarifies this process.
2019-09-11 10:24:44 -04:00
fanquake 189c19e012
Merge #15759: p2p: Add 2 outbound block-relay-only connections
0ba08020c9 Disconnect peers violating blocks-only mode (Suhas Daftuar)
937eba91e1 doc: improve comments relating to block-relay-only peers (Suhas Daftuar)
430f489027 Don't relay addr messages to block-relay-only peers (Suhas Daftuar)
3a5e885306 Add 2 outbound block-relay-only connections (Suhas Daftuar)
b83f51a4bb Add comment explaining intended use of m_tx_relay (Suhas Daftuar)
e75c39cd42 Check that tx_relay is initialized before access (Suhas Daftuar)
c4aa2ba822 [refactor] Change tx_relay structure to be unique_ptr (Suhas Daftuar)
4de0dbac9b [refactor] Move tx relay state to separate structure (Suhas Daftuar)
26a93bce29 Remove unused variable (Suhas Daftuar)

Pull request description:

  Transaction relay is optimized for a combination of redundancy/robustness as well as bandwidth minimization -- as a result transaction relay leaks information that adversaries can use to infer the network topology.

  Network topology is better kept private for (at least) two reasons:

  (a) Knowledge of the network graph can make it easier to find the source IP of a given transaction.

  (b) Knowledge of the network graph could be used to split a target node or nodes from the honest network (eg by knowing which peers to attack in order to achieve a network split).

  We can eliminate the risks of (b) by separating block relay from transaction relay; inferring network connectivity from the relay of blocks/block headers is much more expensive for an adversary.

  After this commit, bitcoind will make 2 additional outbound connections that are only used for block relay. (In the future, we might consider rotating our transaction-relay peers to help limit the effects of (a).)

ACKs for top commit:
  sipa:
    ACK 0ba08020c9
  ajtowns:
    ACK 0ba08020c9 -- code review, ran tests. ran it on mainnet for a couple of days with MAX_BLOCKS_ONLY_CONNECTIONS upped from 2 to 16 and didn't observe any unexpected behaviour: it disconnected a couple of peers that tried sending inv's, and it successfully did compact block relay with some block relay peers.
  TheBlueMatt:
    re-utACK 0ba08020c9. Pointed out that stats.fRelayTxes was sometimes uninitialized for blocksonly peers (though its not a big deal and only effects RPC), which has since been fixed here. Otherwise changes are pretty trivial so looks good.
  jnewbery:
    utACK 0ba08020c9
  jamesob:
    ACK 0ba08020c9

Tree-SHA512: 4c3629434472c7dd4125253417b1be41967a508c3cfec8af5a34cad685464fbebbb6558f0f8f5c0d4463e3ffa4fa3aabd58247692cb9ab8395f4993078b9bcdf
2019-09-07 17:45:03 +08:00
Suhas Daftuar 0ba08020c9 Disconnect peers violating blocks-only mode
If we set fRelay=false in our VERSION message, and a peer sends an INV or TX
message anyway, disconnect. Since we use fRelay=false to minimize bandwidth,
we should not tolerate remaining connected to a peer violating the protocol.
2019-09-04 14:58:36 -04:00
Suhas Daftuar 937eba91e1 doc: improve comments relating to block-relay-only peers 2019-09-04 14:58:36 -04:00
Suhas Daftuar 430f489027 Don't relay addr messages to block-relay-only peers
We don't want relay of addr messages to leak information about
these network links.
2019-09-04 14:58:36 -04:00
Suhas Daftuar 3a5e885306 Add 2 outbound block-relay-only connections
Transaction relay is primarily optimized for balancing redundancy/robustness
with bandwidth minimization -- as a result transaction relay leaks information
that adversaries can use to infer the network topology.

Network topology is better kept private for (at least) two reasons:

(a) Knowledge of the network graph can make it easier to find the source IP of
a given transaction.

(b) Knowledge of the network graph could be used to split a target node or
nodes from the honest network (eg by knowing which peers to attack in order to
achieve a network split).

We can eliminate the risks of (b) by separating block relay from transaction
relay; inferring network connectivity from the relay of blocks/block headers is
much more expensive for an adversary.

After this commit, bitcoind will make 2 additional outbound connections that
are only used for block relay. (In the future, we might consider rotating our
transaction-relay peers to help limit the effects of (a).)
2019-09-04 14:58:36 -04:00
Suhas Daftuar e75c39cd42 Check that tx_relay is initialized before access 2019-09-04 14:58:34 -04:00
Suhas Daftuar c4aa2ba822 [refactor] Change tx_relay structure to be unique_ptr 2019-08-28 13:41:58 -04:00
Suhas Daftuar 4de0dbac9b [refactor] Move tx relay state to separate structure 2019-08-28 13:41:58 -04:00
MarcoFalke 85883a9f8e
Merge #16443: refactor: have CCoins* data managed under CChainState
582d2cd747 Cover UTXO set access with lock annotations (James O'Beirne)
5693530685 refactor: have CCoins* data managed under CChainState (James O'Beirne)
fae6ab6aed refactor: pcoinsTip -> CChainState::CoinsTip() (James O'Beirne)

Pull request description:

  This is part of the [assumeutxo project](https://github.com/bitcoin/bitcoin/projects/11):

  Parent PR: #15606
  Issue: #15605
  Specification: https://github.com/jamesob/assumeutxo-docs/tree/2019-04-proposal/proposal

  ---

  This change encapsulates UTXO set data within CChainState instances, removing global data `pcoinsTip` and `pcoinsviewdb`. This is necessary if we want to maintain multiple chainstates with their own rendering of the UTXO set.

  We introduce a class CoinsViews which consolidates the construction of a CCoins* hierarchy.

  This commit could be broken into smaller pieces, but it would require more ephemeral diffs to, e.g., temporarily change CCoinsViewDB's constructor invocations.

ACKs for top commit:
  Sjors:
    reACK 582d2cd747
  MarcoFalke:
    ACK 582d2cd747

Tree-SHA512: ec9d904fe5dca8cd2dc4b7916daa5d8bab30856dd4645987300f905e0a19f9919fce4f9d1ff03eda982943ca73e6e9a746be6cf53b46510de36e8c81a1eafba1
2019-08-15 12:47:15 -04:00
nicolas.dorier d541fa3918
Replace the use of fWhitelisted by permission checks 2019-08-11 11:33:28 +09:00
nicolas.dorier ecd5cf7ea4
Do not disconnect peer for asking mempool if it has NO_BAN permission 2019-08-11 11:33:27 +09:00
James O'Beirne fae6ab6aed refactor: pcoinsTip -> CChainState::CoinsTip()
This aliasing makes subsequent commits easier to review; eventually CoinsTip()
will return the CCoinsViewCache managed by CChainState.
2019-08-06 13:13:06 -04:00
MarcoFalke c77f7cdbd1
Merge #16197: net: Use mockable time for tx download
fab3658356 [qa] Test that getdata requests work as expected (Suhas Daftuar)
fa883ab35a net: Use mockable time for tx download (MarcoFalke)

Pull request description:

  Two commits:

  * First commit changes to mockable time for tx download (refactoring, should only have an effect on regtest)
  * Second commit adds a test that uses mocktime to test tx download

ACKs for top commit:
  laanwj:
    code review ACK 16197/commits/fab365835639a3da03f8ad9a58a0db6c6c4c2314
  jamesob:
    ACK fab3658356

Tree-SHA512: 3a64a3e283ec4bab1f6e506404b11f0a564a5b61d2a7508ae738a61f035e57220484c66e0ae47d847fe9f7e3ff5cc834909d7b34a9bbcea6abe01f8742806908
2019-08-05 08:01:28 -04:00
Antoine Riard 9bc8b28c1d refactor : use RelayTransaction in BroadcastTransaction utility
To do so, we also refactor RelayTransaction to take a txid
instead of passing a tx
2019-07-24 19:47:56 -04:00
fanquake 21bd6eb782
Merge #16188: net: Document what happens to getdata of unknown type
dddd9270f8 net: Document what happens to getdata of unknonw type (MarcoFalke)

Pull request description:

  Any getdata of unknown type will never be processed and blocks all future messages from a peer. This isn't obviously clear from reading the code, so document it.

Top commit has no ACKs.

Tree-SHA512: 4f8e43bbe6534242facfcfffae28b7a6aa2d228841fa2146a87d494e69f614b0da23cf7a5f3d4367358a7c1981fe2ec196a21c437ae1653f1c7e0351be22598a
2019-06-25 11:12:37 +08:00
MarcoFalke dddd9270f8
net: Document what happens to getdata of unknonw type 2019-06-20 10:49:26 -04:00
MarcoFalke 0b68fca700
Merge #16092: Don't use global (external) symbols for symbols that are used in only one translation unit
0959d37e3e Don't use global (external) symbols for symbols that are used in only one translation unit (practicalswift)

Pull request description:

  Don't use global (external) symbols for symbols that are used in only one translation unit.

  Before:

  ```
  $ for SYMBOL in $(nm src/bitcoind | grep -E ' [BD] ' | c++filt | cut -f3- -d' ' | grep -v @ | grep -v : | sort | grep '[a-z]' | sort -u | grep -vE '(^_|typeinfo|vtable)'); do
        REFERENCES=$(git grep -lE "([^a-zA-Z]|^)${SYMBOL}([^a-zA-Z]|\$)" -- "*.cpp" "*.h")
        N_REFERENCES=$(wc -l <<< "${REFERENCES}")
        if [[ ${N_REFERENCES} > 1 ]]; then
            continue
        fi
        echo "Global symbol ${SYMBOL} is used in only one translation unit: ${REFERENCES}"
    done
  Global symbol g_chainstate is used in only one translation unit: src/validation.cpp
  Global symbol g_ui_signals is used in only one translation unit: src/ui_interface.cpp
  Global symbol instance_of_cmaincleanup is used in only one translation unit: src/validation.cpp
  Global symbol instance_of_cnetcleanup is used in only one translation unit: src/net.cpp
  Global symbol instance_of_cnetprocessingcleanup is used in only one translation unit: src/net_processing.cpp
  Global symbol pindexBestForkBase is used in only one translation unit: src/validation.cpp
  Global symbol pindexBestForkTip is used in only one translation unit: src/validation.cpp
  $
  ```

  After:

  ```
  $ for SYMBOL in $(nm src/bitcoind | grep -E ' [BD] ' | c++filt | cut -f3- -d' ' | grep -v @ | grep -v : | sort | grep '[a-z]' | sort -u | grep -vE '(^_|typeinfo|vtable)'); do
        REFERENCES=$(git grep -lE "([^a-zA-Z]|^)${SYMBOL}([^a-zA-Z]|\$)" -- "*.cpp" "*.h")
        N_REFERENCES=$(wc -l <<< "${REFERENCES}")
        if [[ ${N_REFERENCES} > 1 ]]; then
            continue
        fi
        echo "Global symbol ${SYMBOL} is used in only one translation unit: ${REFERENCES}"
    done
  $
  ```

  ♻️ Think about future generations: save the global namespace from unnecessary pollution!  ♻️

ACKs for commit 0959d3:
  Empact:
    ACK 0959d37e3e
  MarcoFalke:
    ACK 0959d37e3e
  hebasto:
    ACK 0959d37e3e
  promag:
    ACK 0959d37.

Tree-SHA512: 722f66bb50450f19b57e8a8fbe949f30cd651eb8564e5787cbb772a539bf3a288c048dc49e655fd73ece6a46f6dafade515ec4004729bf2b3ab83117b7c5d153
2019-06-18 15:59:53 -04:00
MarcoFalke fa883ab35a
net: Use mockable time for tx download 2019-06-17 14:12:32 -04:00
MarcoFalke f792395d13
Merge #15834: Fix transaction relay bugs introduced in #14897 and expire transactions from peer in-flight map
308b76732f Fix bug around transaction requests (Suhas Daftuar)
f635a3ba11 Expire old entries from the in-flight tx map (Suhas Daftuar)
e32e08407e Remove NOTFOUND transactions from in-flight data structures (Suhas Daftuar)
23163b7593 Add an explicit memory bound to m_tx_process_time (Suhas Daftuar)
218697b645 Improve NOTFOUND comment (Suhas Daftuar)

Pull request description:

  #14897 introduced several bugs that could lead to a node no longer requesting transactions from one or more of its peers.  Credit to ajtowns for originally reporting many of these bugs along with an originally proposed fix in #15776.

  This PR does a few things:

  - Fix a bug in NOTFOUND processing, where the in-flight map for a peer was keeping transactions it shouldn't

  - Eliminate the possibility of a memory attack on the CNodeState `m_tx_process_time` data structure by explicitly bounding its size

  - Remove entries from a peer's in-flight map after 10 minutes, so that we should always eventually resume transaction requests even if there are other bugs like the NOTFOUND one

  - Fix a bug relating to the coordination of request times when multiple peers announce the same transaction

  The expiry mechanism added here is something we'll likely want to remove in the future, but is belt-and-suspenders for now to try to ensure we don't have other bugs that could lead to transaction relay failing due to some unforeseen conditions.

ACKs for commit 308b76:
  ajtowns:
    utACK 308b76732f
  morcos:
    light ACK 308b767
  laanwj:
    Code review ACK 308b76732f
  jonatack:
    Light ACK 308b76732f.
  jamesob:
    ACK 308b76732f
  MarcoFalke:
    ACK 308b76732f (Tested two of the three bugs this pull fixes, see comment above)
  jamesob:
    Concept ACK 308b76732f
  MarcoFalke:
    ACK 308b76732f

Tree-SHA512: 8865dca5294447859d95655e8699085643db60c22f0719e76e961651a1398251bc932494b68932e33f68d4f6084579ab3bed7d0e7dd4ac6c362590eaf9414eda
2019-06-12 12:33:01 -04:00
MarcoFalke d0f81a96d9
Merge #16129: refactor: Remove unused includes
67f4e9c522 Include core_io.h from core_read.cpp (practicalswift)
eca9767673 Make reasoning about dependencies easier by not including unused dependencies (practicalswift)

Pull request description:

  Make reasoning about dependencies easier by not including unused dependencies.

  Please note that the removed headers are _not_ "transitively included" by other still included headers. Thus the removals are real.

  As an added bonus this change means less work for the preprocessor/compiler. At least 51 393 lines of code no longer needs to be processed:

  ```
  $ git diff -u HEAD~1 | grep -E '^\-#include ' | cut -f2 -d"<" | cut -f1 -d">" | \
        sed 's%^%src/%g' | xargs cat | wc -l
  51393
  ```

  Note that 51 393 is the lower bound: the real number is likely much higher when taking into account transitively included headers :-)

ACKs for commit 67f4e9:

Tree-SHA512: 0c8868aac59813f099ce53d5307eed7962dd6f2ff3546768ef9e5c4508b87f8210f1a22c7e826c3c06bebbf28bdbfcf1628ed354c2d0fdb9a31a42cefb8fdf13
2019-06-06 16:41:40 +02:00
practicalswift 0959d37e3e Don't use global (external) symbols for symbols that are used in only one translation unit 2019-06-06 07:45:56 +02:00
Wladimir J. van der Laan 5d37c1bde0
Merge #15976: refactor: move methods under CChainState (pt. 1)
403e677c9 refactoring: IsInitialBlockDownload -> CChainState (James O'Beirne)
3ccbc376d refactoring: FlushStateToDisk -> CChainState (James O'Beirne)
4d6688603 refactoring: introduce ChainstateActive() (James O'Beirne)
d7c97edee move-only: make the CChainState interface public (James O'Beirne)

Pull request description:

  This is part of the [assumeutxo project](https://github.com/bitcoin/bitcoin/projects/11):

  Parent PR: #15606
  Issue: #15605
  Specification: https://github.com/jamesob/assumeutxo-docs/tree/2019-04-proposal/proposal

  ---

  This changeset starts moving functionality intimately related to CChainState into methods. Parameterizing these functions by a particular CChainState is necessary for the use of multiple chainstates simultaneously (e.g. for asynchronous background validation).

  In this change, we
  - make the CChainState interface public - since other units will start to invoke its methods directly,
  - introduce `::ChainstateActive()`, the CChainState equivalent for `::ChainActive()`,
  - and move `IsInitialBlockDownload()` and `FlushStateToDisk()` into methods on CChainState.

  Independent of assumeutxo, these changes better encapsulate chainstate behavior and allow easier use from a testing context.

  There are more methods that we'll move in the future, but they require other substantial changes (i.e. moving ownership of the `CCoinsView*` hierarchy into CChainState) so we'll save them for future PRs.

  ---

  The first move-only commit is most easily reviewed with `git diff ... --color-moved=dimmed_zebra`.

ACKs for commit 403e67:
  Empact:
    utACK 403e677c9e no need to address my nits herein
  Sjors:
    utACK 403e677
  ryanofsky:
    utACK 403e677c9e. Only change since previous review is removing global state comment as suggested.
  MarcoFalke:
    utACK 403e677c9e, though the diff still seems a bit bloated with some unnecessary changes in the second commit.
  promag:
    utACK 403e677 and rebased with current [master](c7cfd20a7).

Tree-SHA512: 6fcf260bb2dc201361170c0b4547405366f5f331fcc3a2bac29b24442814b7b244ca1b58aac5af716885f9a130c343b544590dff780da0bf835c7c5b3ccb2257
2019-06-05 11:56:23 +02:00
lucash-dev 38bfca6bb2 Added comments referencing multiple CVEs in tests and production code.
This commit adds comments referencing multiple CVEs both in production and test code.
CVEs covered in this commit:

CVE-2010-5137
CVE-2010-5139
CVE-2010-5141
CVE-2012-1909
CVE-2012-2459
CVE-2012-3789
CVE-2018-17144
2019-06-02 10:25:03 -07:00
practicalswift eca9767673 Make reasoning about dependencies easier by not including unused dependencies 2019-06-02 17:15:23 +02:00
Suhas Daftuar 308b76732f Fix bug around transaction requests
If a transaction is already in-flight when a peer announces a new tx to us, we
schedule a time in the future to reconsider whether to download. At that future
time, there was a bug that would prevent transactions from being rescheduled
for potential download again (ie if the transaction was still in-flight at the
time of reconsideration, such as from some other peer). Fix this.
2019-05-28 16:22:10 -04:00
Suhas Daftuar f635a3ba11 Expire old entries from the in-flight tx map
If a peer hasn't responded to a getdata request, eventually time out the request
and remove it from the in-flight data structures.  This is to prevent any bugs in
our handling of those in-flight data structures from filling up the in-flight
map and preventing us from requesting more transactions (such as the NOTFOUND
bug, fixed in a previous commit).

Co-authored-by: Anthony Towns <aj@erisian.com.au>
2019-05-28 16:22:10 -04:00
Wladimir J. van der Laan bb291b50f2
Merge #16021: p2p: Avoid logging transaction decode errors to stderr
fa2b52af32 Disallow extended encoding for non-witness transactions (take 3) (MarcoFalke)

Pull request description:

  (previous title "p2p: Disallow extended encoding for non-witness transactions (take 3)")

  Remote peers can send us illegally encoded txs and thus have us write to stderr. Fix that by not writing to stderr.

  This is a follow up to the previous (incomplete) attempts at this:

  *  Disallow extended encoding for non-witness transactions #14039
  *  Add test for superfluous witness record in deserialization #15893

ACKs for commit fa2b52:
  laanwj:
    utACK fa2b52af32
  ryanofsky:
    utACK fa2b52af32. Would change title to something like "Avoid logging transaction decode errors to stderr" instead of "Disallow extended encoding for non-witness transactions." The current title is confusing because this PR isn't really allowing or disallowing anything, just logging the condition differently. "Disallow" also seems to contradict the "Allow exceptions from..." comments in the actual code.

Tree-SHA512: c66990e69b432d00dc1c5510bf976a1188664d0890a32d1e5c6459094e7e27da82a5d227627afcbc203676f5540eec74b7d9b1d71d2c62d3b2069e1781824b4d
2019-05-20 17:29:21 +02:00
James O'Beirne 403e677c9e refactoring: IsInitialBlockDownload -> CChainState
We introduce CChainState.m_cached_finished_ibd because the static state it
replaces would've been shared across all CChainState instances.
2019-05-16 09:06:54 -04:00
MarcoFalke fa2b52af32
Disallow extended encoding for non-witness transactions (take 3) 2019-05-14 08:33:55 -04:00
MarcoFalke fa1dce7329
net: Rename ::fRelayTxes to ::g_relay_txes
This helps to distinguish it from CNode::fRelayTxes and avoid bugs like
425278d17b
2019-05-09 09:10:53 -04:00
MarcoFalke b2a6b02161
Merge #15948: refactor: rename chainActive
486c1eea86 refactoring: remove unused chainActive (James O'Beirne)
631940aab2 scripted-diff: replace chainActive -> ::ChainActive() (James O'Beirne)
a3a609079c refactoring: introduce unused ChainActive() (James O'Beirne)
1b6e6fcfd2 rename: CChainState.chainActive -> m_chain (James O'Beirne)

Pull request description:

  This is part of the assumeutxo project:

  Parent PR: #15606
  Issue: #15605
  Specification: https://github.com/jamesob/assumeutxo-docs/tree/2019-04-proposal/proposal

  ---

  This change refactors the `chainActive` reference into a `::ChainActive()` call. It also distinguishes `CChainState`'s `CChain` data member as `m_chain` instead of the current `chainActive`, which makes it easily confused with the global data.

  The active chain must be obtained via function because its reference will be swapped at some point during runtime after loading a UTXO snapshot.

  This change, though lengthy, should be pretty easy to review since most of it is contained within a scripted-diff. Once merged, the parent PR should be easier to review.

ACKs for commit 486c1e:
  Sjors:
    utACK 486c1ee
  promag:
    utACK 486c1ee.
  practicalswift:
    utACK 486c1eea86

Tree-SHA512: 06ed8f9e77f2d25fc9bea0ba86436d80dbbce90a1e8be23e37ec4eeb26060483e60b4a5c4fba679cb1867f61e3921c24abeb9cabdfb4d0a9b1c4ddd77b17456a
2019-05-07 11:51:30 -04:00
James O'Beirne 631940aab2 scripted-diff: replace chainActive -> ::ChainActive()
Though at the moment ChainActive() simply references `g_chainstate.m_chain`,
doing this change now clears the way for multiple chainstate usage and allows
us to script the diff.

-BEGIN VERIFY SCRIPT-
git grep -l "chainActive" | grep -E '(h|cpp)$' | xargs sed -i '/chainActive =/b; /extern CChain& chainActive/b; s/\(::\)\{0,1\}chainActive/::ChainActive()/g'
-END VERIFY SCRIPT-
2019-05-03 15:02:54 -04:00
Suhas Daftuar 0ff1c2a838 Separate reason for premature spends (coinbase/locktime) 2019-05-02 15:30:58 -04:00
Suhas Daftuar 54470e767b Assert validation reasons are contextually correct 2019-05-02 15:29:09 -04:00
Suhas Daftuar 6b34bc6b6f Fix handling of invalid headers
We only disconnect outbound peers (excluding HB compact block peers and manual
connections) when receiving a CACHED_INVALID header.
2019-05-02 15:17:24 -04:00