Commit graph

587 commits

Author SHA1 Message Date
Troy Giorshev 890b1d7c2b Move checksum check from net_processing to net
This removes the m_valid_checksum member from CNetMessage.  Instead,
GetMessage() returns an Optional.

Additionally, GetMessage() has been given an out parameter to be used to
hold error information.  For now it is specifically a uint32_t used to
hold the raw size of the corrupt message.

The checksum check is now done in GetMessage.
2020-09-22 22:01:14 -04:00
Amiti Uttarwar 49c10a9ca4 [log] Add connection type to log statement
In addition to adding more specificity to the log statement about the type of
connection, this change also consolidates two statements into one. Previously,
the second one should have never been hit, since block-relay connections would
match the "!IsInboundConn()" condition and return early.
2020-09-21 19:01:29 -07:00
Wladimir J. van der Laan 77376034d4
Merge #17785: p2p: Unify Send and Receive protocol versions
ddefb5c0b7 p2p: Use the greatest common version in peer logic (Hennadii Stepanov)
e084d45562 p2p: Remove SetCommonVersion() from VERACK handler (Hennadii Stepanov)
8d2026796a refactor: Rename local variable nSendVersion (Hennadii Stepanov)
e9a6d8b13b p2p: Unify Send and Receive protocol versions (Hennadii Stepanov)

Pull request description:

  On master (6fef85bfa3) `CNode` has two members to keep protocol version:
  - `nRecvVersion` for received messages
  - `nSendVersion` for messages to send

  After exchanging with `VERSION` and `VERACK` messages via protocol version `INIT_PROTO_VERSION`, both nodes set `nRecvVersion` _and_ `nSendVersion` to _the same_ value which is the greatest common protocol version.

  This PR:
  - replaces two `CNode` members, `nRecvVersion` `nSendVersion`, with `m_greatest_common_version`
  - removes duplicated getter and setter

  There is no change in behavior on the P2P network.

ACKs for top commit:
  jnewbery:
    ACK ddefb5c0b7
  naumenkogs:
    ACK ddefb5c0b7
  fjahr:
    Code review ACK ddefb5c0b7
  amitiuttarwar:
    code review but untested ACK ddefb5c0b7
  benthecarman:
    utACK `ddefb5c`

Tree-SHA512: 5305538dbaa5426b923b0afd20bdef4f248d310855d1d78427210c00716c67b7cb691515c421716b6157913e453076e293b10ff5fd2cd26a8e5375d42da7809d
2020-09-22 00:14:32 +02:00
Wladimir J. van der Laan c0c409dcd3
Merge #19697: Improvements on ADDR caching
0d04784af1 Refactor the functional test (Gleb Naumenko)
83ad65f31b Address nits in ADDR caching (Gleb Naumenko)
81b00f8780 Add indexing ADDR cache by local socket addr (Gleb Naumenko)
42ec558542 Justify the choice of ADDR cache lifetime (Gleb Naumenko)

Pull request description:

  This is a follow-up on #18991 which does 3 things:
  - improves privacy of a node listening to multiple addresses via adding cache index by local socket addr (suggested [here](https://github.com/bitcoin/bitcoin/pull/18991#issuecomment-668219345))
  - documents on the choice of 24h cache lifetime
  - addresses nits from #18991

ACKs for top commit:
  jnewbery:
    utACK 0d04784af1
  vasild:
    ACK 0d04784
  jonatack:
    Code review ACK 0d04784

Tree-SHA512: bb65a34dd1ce2811186d3e4469bc33e8399cebaaa494ce13041c7cff23275870e4176a719f7a72f8d779c49f8b2344bf4fa1aeb3ea4e2626d5ae76514f00a750
2020-09-21 19:36:57 +02:00
Hennadii Stepanov ab2a44297f
Replace LockAssertion with a proper thread safety annotations 2020-09-19 18:02:02 +03:00
fanquake 1c4f59728c
Merge #19879: [p2p] miscellaneous wtxid followups
a8a64acaf3 [BroadcastTransaction] Remove unsafe move operator (Amiti Uttarwar)
125c038126 [p2p] Remove dead code (Amiti Uttarwar)
fc66d0a65c [p2p] Check for nullptr before dereferencing pointer (Adam Jonas)
cb79b9dbf4 [mempool] Revert unbroadcast set to tracking just txid (Amiti Uttarwar)

Pull request description:

  Addresses some outstanding review comments from #18044

  - reverts unbroadcast txids to a set instead of a map (simpler, communicates intent better, takes less space, no efficiency advantages of map)
  - adds safety around two touchpoints (check for nullptr before dereferencing pointer, remove an inaccurate std::move operator)
  - removes some dead code

  Links to comments on wtxid PR: [1](https://github.com/bitcoin/bitcoin/pull/18044#discussion_r460495254) [2](https://github.com/bitcoin/bitcoin/pull/18044#discussion_r460496023) [3](https://github.com/bitcoin/bitcoin/pull/18044#discussion_r463532611)

  thanks to jnewbery & adamjonas for flagging these ! !

ACKs for top commit:
  sdaftuar:
    utACK a8a64acaf3
  naumenkogs:
    utACK a8a64acaf3
  jnewbery:
    utACK a8a64acaf3

Tree-SHA512: 7be669cb30cc17fb9e06b50e636ef7887c6a27354697987e4e4d38dba4b8f50e175647587430cd9bc3295bec01ce8b1e6639a50a4249d8fff9b1ca1b9ead3277
2020-09-16 06:30:57 +08:00
Antoine Riard d76925478e [doc] Clarify semantic of peer's m_protect w.r.t to outbound eviction logics
The field m_protect is used to protect from eviction both by bad/lagging
chain and extra outbound peers logics. Outbound block-relay peers are
always excluded from this protection.
2020-09-10 09:51:03 -04:00
MarcoFalke fa7e407b50
Do not pass chain params to CheckForStaleTipAndEvictPeers twice 2020-09-08 07:55:11 +02:00
John Newbery 001343f4bc ProcessOrphanTx: Move AddToCompactExtraTransactions call into ProcessOrphanTx 2020-09-07 20:12:02 +01:00
John Newbery 4fce726bd1 ProcessOrphanTx: Remove aliases 2020-09-07 20:10:17 +01:00
John Newbery e07c5d9423 ProcessOrphanTx: Remove outdated commented
Also rename orphan_state to state. Both the comment and the variable
name are leftover from when this logic was part of ProcessMessage().
2020-09-07 20:08:43 +01:00
John Newbery 4763b51bca ProcessOrphanTx: remove useless setMisbehaving set
This starts empty, and is only added to if we're about to
exit the function (so we never read from it).
2020-09-07 20:07:43 +01:00
John Newbery 55c79a9cef ProcessOrphanTx: remove useless done variable
There is a keyword that allows us to break out of loops. Use it.

There's a small change in behaviour here: if we process multiple orphans
that are still orphans, then we'll only call mempool.check() once at the
end, instead of after processing each tx.
2020-09-07 19:57:32 +01:00
John Newbery 6e8dd99ef1 [net processing] Add doxygen comments for orphan data and function 2020-09-07 19:55:53 +01:00
Hennadii Stepanov ddefb5c0b7
p2p: Use the greatest common version in peer logic 2020-09-07 21:03:55 +03:00
Hennadii Stepanov e084d45562
p2p: Remove SetCommonVersion() from VERACK handler
SetCommonVersion() is already called from the VERSION message handler.
There is no change in behavior on the P2P network.
2020-09-07 21:03:54 +03:00
Hennadii Stepanov 8d2026796a
refactor: Rename local variable nSendVersion 2020-09-07 21:03:54 +03:00
Hennadii Stepanov e9a6d8b13b
p2p: Unify Send and Receive protocol versions
There is no change in behavior on the P2P network.
2020-09-07 21:03:44 +03:00
MarcoFalke 147d50d63e
Merge #19791: [net processing] Move Misbehaving() to PeerManager
bb6a32ce99 [net processing] Move Misbehaving() to PeerManager (John Newbery)
aa114b1c9b [net_processing] Move SendBlockTransactions into PeerManager (John Newbery)
3115e00f75 [net processing] Move MaybePunishPeerForTx to PeerManager (John Newbery)
e662e2d42a [net processing] Move ProcessOrphanTx to PeerManager (John Newbery)
b70cd890e3 [net processing] Move MaybePunishNodeForBlock into PeerManager (John Newbery)
d7778351bf [net processing] Move ProcessHeadersMessage to PeerManager (John Newbery)
64f6162651 [whitespace] tidy up indentation after scripted diff (John Newbery)
58bd369b0d scripted-diff: [net processing] Rename PeerLogicValidation to PeerManager (John Newbery)
2297b26b3c [net_processing] Pass chainparams to PeerLogicValidation constructor (John Newbery)
824bbd1ffb [move only] Collect all private members of PeerLogicValidation together (John Newbery)

Pull request description:

  Continues the work of moving net_processing logic into PeerLogicValidation. See https://github.com/bitcoin/bitcoin/pull/19704 and https://github.com/bitcoin/bitcoin/pull/19607#discussion_r462032894 for motivation.

  This PR also renames `PeerLogicValidation` to `PeerManager` as suggested in https://github.com/bitcoin/bitcoin/pull/10756#pullrequestreview-53892618.

ACKs for top commit:
  MarcoFalke:
    re-ACK bb6a32ce99 only change is rebase due to conflict in struct NodeContext and variable rename 🤸
  hebasto:
    re-ACK bb6a32ce99, only rebased, and added renaming `s/peer_logic/peerman/` into scripted-diff since my [previous](https://github.com/bitcoin/bitcoin/pull/19791#pullrequestreview-483118079) review (verified with `git range-diff`).

Tree-SHA512: a2de4a521688fd25125b401e5575402c52b328a0fa27b3010567008d4f596b960aabbd02b2d81f42658f88f4365443fadb1008150a62fbcea123fb42d85a2c21
2020-09-07 18:09:15 +02:00
Antoine Riard ac71fe936d [doc] Clarify scope of eviction protection of outbound block-relay peers
Block-relay-only peers were introduced by #15759. According to its
author, it was intented to make them only immune to outbound peer
rotation-based eviction and not from all eviction as modified comment
leans to think of.

Clearly indicate that outbound block-relay peers aren't protected
from eviction by the bad/lagging chain logic.
2020-09-07 10:48:21 -04:00
John Newbery bb6a32ce99 [net processing] Move Misbehaving() to PeerManager 2020-09-07 11:16:12 +01:00
John Newbery aa114b1c9b [net_processing] Move SendBlockTransactions into PeerManager 2020-09-07 11:16:12 +01:00
John Newbery 3115e00f75 [net processing] Move MaybePunishPeerForTx to PeerManager 2020-09-07 11:16:12 +01:00
John Newbery e662e2d42a [net processing] Move ProcessOrphanTx to PeerManager 2020-09-07 11:16:12 +01:00
John Newbery b70cd890e3 [net processing] Move MaybePunishNodeForBlock into PeerManager 2020-09-07 11:16:12 +01:00
John Newbery d7778351bf [net processing] Move ProcessHeadersMessage to PeerManager 2020-09-07 11:16:12 +01:00
John Newbery 64f6162651 [whitespace] tidy up indentation after scripted diff 2020-09-07 11:16:12 +01:00
John Newbery 58bd369b0d scripted-diff: [net processing] Rename PeerLogicValidation to PeerManager
-BEGIN VERIFY SCRIPT-
sed -i 's/PeerLogicValidation/PeerManager/g' $(git grep -l PeerLogicValidation ./src ./test)
sed -i 's/peer_logic/peerman/g' $(git grep -l peer_logic ./src ./test)
-END VERIFY SCRIPT-

PeerLogicValidation was originally net_processing's implementation to
the validation interface. It has since grown to contain much of
net_processing's logic. Therefore rename it to reflect its
responsibilities.

Suggested in
https://github.com/bitcoin/bitcoin/pull/10756#pullrequestreview-53892618.
2020-09-07 11:15:48 +01:00
John Newbery 2297b26b3c [net_processing] Pass chainparams to PeerLogicValidation constructor
Keep a references to chainparams, rather than calling the global
Params() function every time it's needed. This is fine, since
globalChainParams does not get updated once it's been set, and it's
available at the point of constructing the PeerLogicValidation object.
2020-09-07 11:13:58 +01:00
John Newbery 824bbd1ffb [move only] Collect all private members of PeerLogicValidation together
We don't have a project style for ordering class members, but it always
makes sense to have no more than one of each public/protected/private
specifier.

Also move documentation for MaybeDiscourageAndDisconnect to the header.
2020-09-07 11:13:58 +01:00
MarcoFalke 2583966130
Merge #19478: Remove CTxMempool::mapLinks data structure member
296be8f58e Get rid of unused functions CTxMemPool::GetMemPoolChildren, CTxMemPool::GetMemPoolParents (Jeremy Rubin)
46d955d196 Remove mapLinks in favor of entry inlined structs with iterator type erasure (Jeremy Rubin)

Pull request description:

  Currently we have a peculiar data structure in the mempool called maplinks. Maplinks job is to track the in-pool children and parents of each transaction. This PR can be primarily understood and reviewed as a simple refactoring to remove this extra data structure, although it comes with a nice memory and performance improvement for free.

  Maplinks is particularly peculiar because removing it is not as simple as just moving it's inner structure to the owning CTxMempoolEntry. Because TxLinks (the class storing the setEntries for parents and children) store txiters to each entry in the mempool corresponding to the parent or child, it means that the TxLinks type is "aware" of the boost multiindex (mapTx) it's coming from, which is in turn, aware of the entry type stored in mapTx. Thus we used maplinks to store this entry associated data we in an entirely separate data structure just to avoid a circular type reference caused by storing a txiter inside a CTxMempoolEntry.

  It turns out, we can kill this circular reference by making use of iterator_to multiindex function and std::reference_wrapper. This allows us to get rid of the maplinks data structure and move the ownership of the parents/child sets to the entries themselves.

  The benefit of this good all around, for any of the reasons given below the change would be acceptable, and it doesn't make the code harder to reason about or worse in any respect (as far as I can tell, there's no tradeoff).

  ### Simpler ownership model
  No longer having to consistency check that mapLinks did have records for our CTxMempoolEntry, impossible to have a mapLinks entry outlive or incorrectly die before a CTxMempoolEntry.

  ### Memory Usage
  We get rid of a O(Transactions) sized map in the mempool, which is a long lived data structure.

  ### Performance
  If you have a CTxMemPoolEntry, you immediately know the address of it's children/parents, rather than having to do a O(log(Transactions)) lookup via maplinks (which we do very often). We do it in *so many* places that a true benchmark has to look at a full running node, but it is easy enough to show an improvement in this case.

  The ComplexMemPool shows a good coherence check that we see the expected result of it being 12.5% faster / 1.14x faster.
  ```
  Before:
  # Benchmark, evals, iterations, total, min, max, median
  ComplexMemPool, 5, 1, 1.40462, 0.277222, 0.285339, 0.279793

  After:
  # Benchmark, evals, iterations, total, min, max, median
  ComplexMemPool, 5, 1, 1.22586, 0.243831, 0.247076, 0.244596
  ```
  The ComplexMemPool benchmark only checks doing addUnchecked and TrimToSize for 800 transactions. While this bench does a good job of hammering the relevant types of function, it doesn't test everything.

  Subbing in 5000 transactions shows a that the advantage isn't completely wiped out by other asymptotic factors (this isn't the only bottleneck in growing the mempool), but it's only a bit proportionally slower (10.8%, 1.12x), which adds evidence that this will be a good change for performance minded users.

  ```
  # Benchmark, evals, iterations, total, min, max, median
  ComplexMemPool, 5, 1, 59.1321, 11.5919, 12.235, 11.7068

  # Benchmark, evals, iterations, total, min, max, median
  ComplexMemPool, 5, 1, 52.1307, 10.2641, 10.5206, 10.4306
  ```
  I don't think it's possible to come up with an example of where a maplinks based design would have better performance, but it's something for reviewers to consider.

  # Discussion
  ## Why maplinks in the first place?

  I spoke with the author of mapLinks (sdaftuar) a while back, and my recollection from our conversation was that it was implemented because he did not know how to resolve the circular dependency at the time, and there was no other reason for making it a separate map.

  ## Is iterator_to weird?

  iterator_to is expressly for this purpose, see https://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to

  >  iterator_to provides a way to retrieve an iterator to an element from a pointer to the element, thus making iterators and pointers interchangeable for the purposes of element pointing (not so for traversal) in many situations. This notwithstanding, it is not the aim of iterator_to to promote the usage of pointers as substitutes for real iterators: the latter are specifically designed for handling the elements of a container, and not only benefit from the iterator orientation of container interfaces, but are also capable of exposing many more programming bugs than raw pointers, both at compile and run time. iterator_to is thus meant to be used in scenarios where access via iterators is not suitable or desireable:
  >
  >     - Interoperability with preexisting APIs based on pointers or references.
  >     - Publication of pointer-based interfaces (for instance, when designing a C-compatible library).
  >     - The exposure of pointers in place of iterators can act as a type erasure barrier effectively decoupling the user of the code from the implementation detail of which particular container is being used. Similar techniques, like the famous Pimpl idiom, are used in large projects to reduce dependencies and build times.
  >     - Self-referencing contexts where an element acts upon its owner container and no iterator to itself is available.

  In other words, iterator_to is the perfect tool for the job by the last reason given. Under the hood it should just be a simple pointer cast and have no major runtime overhead (depending on if the function call is inlined).

  Edit by laanwj: removed at sign from the description

ACKs for top commit:
  jonatack:
    re-ACK 296be8f per `git range-diff ab338a19 3ba1665 296be8f`, sanity check gcc 10.2 debug build is clean.
  hebasto:
    re-ACK 296be8f58e, only rebased since my [previous](https://github.com/bitcoin/bitcoin/pull/19478#pullrequestreview-482400727) review (verified with `git range-diff`).

Tree-SHA512: f5c30a4936fcde6ae32a02823c303b3568a747c2681d11f87df88a149f984a6d3b4c81f391859afbeb68864ef7f6a3d8779f74a58e3de701b3d51f78e498682e
2020-09-07 12:06:55 +02:00
MarcoFalke fa0359c5b3
Remove mempool global from p2p 2020-09-05 16:24:52 +02:00
Wladimir J. van der Laan 416efcb7ab
Merge #19728: Increase the ip address relay branching factor for unreachable networks
86d4cf42d9 Increase the ip address relay branching factor for unreachable networks (Pieter Wuille)

Pull request description:

  Onion addresses propagate very badly among the IPv4/IPv6 network, resulting
  in difficulty for those to find each other.

  The branching factor 1 is probably so low that propagations die out before
  they reach another onion peer. Increase it to 1.5 on average.

ACKs for top commit:
  practicalswift:
    ACK 86d4cf42d9 -- patch looks correct
  naumenkogs:
    ACK 86d4cf4
  jonatack:
    ACK 86d4cf42d9. Code review, built and running with some sanity check logging. `RelayAddress()` is called by `ProcessMessage() ADDR` msg handling, from within the loop while processing each new address to relay it to a limited number of other nodes. According to git blame, the line setting `nRelayNodes` hasn't been touched since 2016 in e736772c56 *Move network-msg-processing code out of main to its own file*, which moved the line but otherwise did not change it. Running a mixed clearnet/onion node with this patch and the logging below, I'm only seeing values of `fReachable 1, nRelayNodes 2`. IIUC, I need to use the settings in `init.cpp` that call `SetReachable(*, false)`. *Edit:* with `onlynet=onion` am now seeing entries of `fReachable 0` with `nRelayNodes` values of 1 and 2.
  vasild:
    ACK 86d4cf42d

Tree-SHA512: 22391e16d60bcfdec9a9336728da39d68a24a183b3d1b0e8fbc038d265ca6ddf71d16db018f3678745fd9f3e9281049e42197fa0a29124833c50a9170ed6f793
2020-09-05 14:08:16 +02:00
Amiti Uttarwar 125c038126 [p2p] Remove dead code
The else clause is dead code because the only way to not enter the if branch is
if TX_WITNESS_STRIPPED is true. In that case, it would not have a witness to
match the `tx.HasWitness()` else condition.

Co-authored-by: Adam Jonas <jonas@chaincode.com>
Co-authored-by: John Newbery <john@johnnewbery.com>
2020-09-04 14:42:30 -07:00
Adam Jonas fc66d0a65c [p2p] Check for nullptr before dereferencing pointer 2020-09-04 14:37:44 -07:00
Amiti Uttarwar cb79b9dbf4 [mempool] Revert unbroadcast set to tracking just txid
When I originally implemented the unbroadcast set in 18038, it just tracked
txids. After 18038 was merged, I offered a patch to 18044 to make the
unbroadcast changes compatible with wtxid relay. In this patch, I updated
`unbroadcast_txids` to a map of txid -> wtxid. Post merge review comments shed
light on the fact that this update was unnecessary, and distracting. So, this
commit updates the unbroadcast ids back to a set.
2020-09-04 14:29:29 -07:00
Jeremy Rubin 46d955d196 Remove mapLinks in favor of entry inlined structs with iterator type erasure 2020-09-04 09:46:44 -07:00
Amiti Uttarwar 1e563aed78 [refactor] Simplify check for block-relay-only connection.
Previously we deduced it was a block-relay-only based on presence of the
m_tx_relay structure. Now we have the ability to identify it directly via a
connection type accessor function.
2020-09-02 17:18:22 -07:00
Amiti Uttarwar 1d74fc7df6 [trivial] Small style updates 2020-09-02 17:18:21 -07:00
Amiti Uttarwar ff6b9081ad [doc] Explain address handling logic in process messages
Co-authored-by: Suhas Daftuar <sdaftuar@gmail.com>
2020-09-02 17:18:21 -07:00
Amiti Uttarwar dff16b184b [refactor] Restructure logic to check for addr relay.
We previously identified if we relay addresses to the connection by checking
for the existence of the m_addr_known data structure. With this commit, we
answer this question based on the connection type.

IsAddrRelayPeer() checked for the existence of the m_addr_known
2020-09-02 17:18:21 -07:00
Wladimir J. van der Laan 505b39e72b
Merge #19610: p2p: refactor AlreadyHave(), CInv::type, INV/TX processing
fb56d37612 p2p: ensure inv is GenMsgTx before ToGenTxid in inv processing (John Newbery)
aa3621385e test: use CInv::MSG_WITNESS_TX flag in p2p_segwit (Jon Atack)
24ee4f01ea p2p: make gtxid(.hash) and fAlreadyHave localvars const (Jon Atack)
b1c855453b p2p: use CInv block message helpers in net_processing.cpp (Jon Atack)
acd6642167 [net processing] Change AlreadyHaveTx() to take a GenTxid (John Newbery)
5fdfb80b86 [net processing] Change AlreadyHaveBlock() to take block_hash argument (John Newbery)
430e183b89 [net processing] Remove mempool argument from AlreadyHaveBlock() (John Newbery)
42ca5618ca [net processing] Split AlreadyHave() into separate block and tx functions (John Newbery)
39f1dc9445 p2p: remove nFetchFlags from NetMsgType TX and INV processing (Jon Atack)
471714e1f0 p2p: add CInv block message helper methods (Jon Atack)

Pull request description:

  Building on #19590 and the recent `wtxid` and `GenTxid` changes, this is a refactoring and cleanup PR to simplify and improve some of the net processing code.

  Some of the diffs are best reviewed with `-w` to ignore spacing.

  Co-authored by John Newbery.

ACKs for top commit:
  laanwj:
    Code review ACK fb56d37612
  jnewbery:
    utACK fb56d37612
  vasild:
    ACK fb56d3761

Tree-SHA512: ba39b58e6aaf850880a842fe5f6295e9f1870906ef690206acfc17140aae2ac854981e1066dbcd4238062478762fbd040ef772fdc2c50eea6869997c583e6a6d
2020-09-02 13:45:40 +02:00
MarcoFalke bab4cce1b0
Merge #19668: Do not hide compile-time thread safety warnings
ea74e10acf doc: Add best practice for annotating/asserting locks (Hennadii Stepanov)
2ee7743fe7 sync.h: Make runtime lock checks require compile-time lock checks (Anthony Towns)
23d71d171e Do not hide compile-time thread safety warnings (Hennadii Stepanov)
3ddc150857 Add missed thread safety annotations (Hennadii Stepanov)
af9ea55a72 Use LockAssertion utility class instead of AssertLockHeld() (Hennadii Stepanov)

Pull request description:

  On the way of transit from `RecursiveMutex` to `Mutex` (see #19303) it is crucial to have run-time `AssertLockHeld()` assertion that does _not_ hide compile-time Clang Thread Safety Analysis warnings.

  On master (65e4ecabd5) using `AssertLockHeld()` could hide Clang Thread Safety Analysis warnings, e.g., with the following patch applied:
  ```diff
  --- a/src/txmempool.h
  +++ b/src/txmempool.h
  @@ -607,7 +607,7 @@ public:
       void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);

       void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
  -    void removeForReorg(const CCoinsViewCache* pcoins, unsigned int nMemPoolHeight, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
  +    void removeForReorg(const CCoinsViewCache* pcoins, unsigned int nMemPoolHeight, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
       void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
       void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);

  ```
  Clang compiles the code without any thread safety warnings.

  See "Add missed thread safety annotations" commit for the actual thread safety warnings that are fixed in this PR.

ACKs for top commit:
  MarcoFalke:
    ACK ea74e10acf 🎙
  jnewbery:
    ACK ea74e10acf
  ajtowns:
    ACK ea74e10acf

Tree-SHA512: 8cba996e526751a1cb0e613c0cc1b10f027a3e9945fbfb4bd30f6355fd36b9f9c2e1e95ed3183fc254b42df7c30223278e18e5bdb5e1ef85db7fef067595d447
2020-09-01 08:18:26 +02:00
Hennadii Stepanov af9ea55a72
Use LockAssertion utility class instead of AssertLockHeld()
This change prepares for upcoming commit "Do not hide compile-time
thread safety warnings" by replacing AssertLockHeld() with
LockAssertion() where needed.
2020-08-29 20:43:23 +03:00
Suhas Daftuar 675e55e013 Ignore unknown messages before VERACK 2020-08-28 17:17:07 -04:00
Wladimir J. van der Laan 1cf73fb8eb
Merge #19607: [p2p] Add Peer struct for per-peer data in net processing
8e35bf5906 scripted-diff: rename misbehavior members (John Newbery)
1f96d2e673 [net processing] Move misbehavior tracking state to Peer (John Newbery)
7cd4159ac8 [net processing] Add Peer (John Newbery)
aba03359a6 [net processing] Remove CNodeState.name (John Newbery)

Pull request description:

  We currently have two structures for per-peer data:

  - `CNode` in net, which should just contain connection layer data (eg socket, send/recv buffers, etc), but currently also contains some application layer data (eg tx/block inventory).
  - `CNodeState` in net processing, which contains p2p application layer data, but requires cs_main to be locked for access.

  This PR adds a third struct `Peer`, which is for p2p application layer data, and doesn't require cs_main. Eventually all application layer data from `CNode` should be moved to `Peer`, and any data that doesn't strictly require cs_main should be moved from `CNodeState` to `Peer` (probably all of `CNodeState` eventually).

  `Peer` objects are stored as shared pointers in a net processing global map `g_peer_map`, which is protected by `g_peer_mutex`. To use a `Peer` object, `g_peer_mutex` is locked, a copy of the shared pointer is taken, and the lock is released. Individual members of `Peer` are protected by different mutexes that guard related data. The lifetime of the `Peer` object is managed by the shared_ptr refcount.

  This PR adds the `Peer` object and moves the misbehaving data from `CNodeState` to `Peer`. This allows us to immediately remove 15 `LOCK(cs_main)` instances.

  For more motivation see #19398

ACKs for top commit:
  laanwj:
    Code review ACK 8e35bf5906
  troygiorshev:
    reACK 8e35bf5906 via `git range-diff master 9510938 8e35bf5`
  theuni:
    ACK 8e35bf5906.
  jonatack:
    ACK 8e35bf5906 keeping in mind Cory's comment (https://github.com/bitcoin/bitcoin/pull/19607#discussion_r470173964) for the follow-up

Tree-SHA512: ad84a92b78fb34c9f43813ca3dfbc7282c887d55300ea2ce0994d134da3e0c7dbc44d54380e00b13bb75a57c28857ac3236bea9135467075d78026767a19e4b1
2020-08-28 20:29:16 +02:00
Gleb Naumenko 81b00f8780 Add indexing ADDR cache by local socket addr 2020-08-27 10:51:56 +03:00
John Newbery fb56d37612
p2p: ensure inv is GenMsgTx before ToGenTxid in inv processing
and otherwise log that an unknown INV type was received.

In INV processing, when handling transaction type inv messages,
ToGenTxid() expects that we constructed the CInv ourselves or
that we verified that it is for a transaction type CInv.

Therefore, change this `else` branch into an `else if (inv.GenMsgTx())`
to make this safer and log any INVs that fall through.
2020-08-26 11:57:30 +02:00
Jon Atack 24ee4f01ea
p2p: make gtxid(.hash) and fAlreadyHave localvars const 2020-08-26 11:57:23 +02:00
Jon Atack b1c855453b
p2p: use CInv block message helpers in net_processing.cpp 2020-08-26 11:57:19 +02:00
John Newbery acd6642167
[net processing] Change AlreadyHaveTx() to take a GenTxid 2020-08-26 11:57:15 +02:00
John Newbery 5fdfb80b86
[net processing] Change AlreadyHaveBlock() to take block_hash argument 2020-08-26 11:57:11 +02:00
John Newbery 430e183b89
[net processing] Remove mempool argument from AlreadyHaveBlock() 2020-08-26 11:57:07 +02:00
John Newbery 42ca5618ca
[net processing] Split AlreadyHave() into separate block and tx functions 2020-08-26 11:57:03 +02:00
Jon Atack 39f1dc9445
p2p: remove nFetchFlags from NetMsgType TX and INV processing
The nFetchFlags code can be removed here because GetFetchFlags() can only add
the MSG_WITNESS_FLAG, which is added to the CInv::type field. That CInv is only
passed to AlreadyHave() or ToGenTxid(), and neither of those functions do
anything different depending on whether the CInv type is MSG_TX or
MSG_WITNESS_TX.

Co-authored by: John Newbery <john@johnnewbery.com>
2020-08-26 11:56:59 +02:00
fanquake 4fefd80f08
Merge #19704: Net processing: move ProcessMessage() to PeerLogicValidation
daed542a12 [net_processing] Move ProcessMessage to PeerLogicValidation (John Newbery)
c556770b5e [net_processing] Change PeerLogicValidation to hold a connman reference (John Newbery)

Pull request description:

  Rather than ProcessMessage() being a static function in net_processing.cpp, make it a private member function of PeerLogicValidation. This is the start of moving static functions and global variables into PeerLogicValidation to make it better encapsulated.

ACKs for top commit:
  jonatack:
    ACK daed542a12 code review and debug tested
  promag:
    Code review ACK daed542a12.
  MarcoFalke:
    re-ACK daed542a12, only change is removing second commit 🎴
  theStack:
    Code Review ACK daed542a12

Tree-SHA512: ddebf410d114d9ad5a9e536950018ff333a347c035d74fcc101fb4a3f20a281782c7eac2b7d1bd1c8f6bc7e59f5b5630fb52c2e1b4c32df454fa584673bd021e
2020-08-24 21:50:37 +08:00
John Newbery daed542a12 [net_processing] Move ProcessMessage to PeerLogicValidation 2020-08-21 13:10:41 +01:00
Pieter Wuille 86d4cf42d9 Increase the ip address relay branching factor for unreachable networks
Onion addresses propagate very badly among the IPv4/IPv6 network, resulting
in difficulty for those to find each other.

The branching factor 1 is probably so low that propagations die out before
they reach another onion peer. Increase it to 1.5 on average.
2020-08-14 23:02:42 -07:00
Wladimir J. van der Laan b4d0366b47
Merge #19070: p2p: Signal support for compact block filters with NODE_COMPACT_FILTERS
f5c003d3ea [test] Add test for NODE_COMPACT_FILTER. (Jim Posen)
132b30d9c8 [net] Signal NODE_COMPACT_FILTERS if we're serving compact filters. (Jim Posen)
b3fbc94d4f Apply cfilters review fixups (John Newbery)

Pull request description:

  If -peerblockfilters is configured, signal the `NODE_COMPACT_FILTERS` service bit to indicate that we are able to serve compact block filters, headers and checkpoints.

ACKs for top commit:
  MarcoFalke:
    re-review and Concept ACK f5c003d3ea
  fjahr:
    Code review ACK f5c003d3ea
  clarkmoody:
    Concept ACK f5c003d3ea
  ariard:
    Concept and Code Review ACK f5c003d
  jonatack:
    ACK f5c003d3e

Tree-SHA512: 34d1c153530a0e55d09046fe548c9dc37344b5d6d50e00af1b4e1de1e7b49de770fca8471346a17c151de9fe164776296bb3dd5af331977f0c3ef1e6fc906f85
2020-08-13 15:44:48 +02:00
John Newbery c556770b5e [net_processing] Change PeerLogicValidation to hold a connman reference
Hold a reference to connman rather than a pointer because:

- PeerLogicValidation can't run without a connman
- The pointer never gets reseated

The alternative is to always assert that the pointer is non-null before
dereferencing.

Change the name from connman to m_connman at the same time to conform
with current style guidelines.
2020-08-12 14:25:28 +01:00
Wladimir J. van der Laan bd00d3b1f2
Merge #19658: [rpc] Allow RPC to fetch all addrman records and add records to addrman
37a480e0cd [net] Add addpeeraddress RPC method (John Newbery)
ae8051bbd8 [test] Test that getnodeaddresses() can return all known addresses (John Newbery)
f26502e9fc [addrman] Specify max addresses and pct when calling GetAddresses() (John Newbery)

Pull request description:

  Currently addrman only allows a maximum of 1000 records or 23% of all records to be returned in a call to `GetAddr()`. Relax this limit and have the client specify the max records they want. For p2p, behaviour is unchanged (but the rate limiting is set inside net_processing, where it belongs). For RPC, `getnodeaddresses` can now return the complete addrman, which is helpful for testing and monitoring.

  Also add a test-only RPC `addpeeraddress`, which adds an IP address:port to addrman. This is helpful for testing (eg #18991).

ACKs for top commit:
  naumenkogs:
    utACK 37a480e0cd
  laanwj:
    Code review and lightly manually tested ACK 37a480e0cd

Tree-SHA512: f86dcd410aaebaf6e9ca18ce6f23556e5e4649c1325577213d873aa09967298e65ab2dc19a72670641ae92211a923afda1fe124a82e9d2c1cad73d478ef27fdc
2020-08-12 15:23:06 +02:00
John Newbery 8e35bf5906 scripted-diff: rename misbehavior members
-BEGIN VERIFY SCRIPT-
sed -i 's/nMisbehavior/m_misbehavior_score/g' src/net_processing.cpp src/net_processing.h src/rpc/net.cpp src/qt/rpcconsole.cpp
-END VERIFY SCRIPT-
2020-08-12 11:23:22 +01:00
John Newbery 1f96d2e673 [net processing] Move misbehavior tracking state to Peer
Misbehavior tracking state is now contained in Peer instead of
CNode. It is no longer guarded by cs_main, but instead by a
dedicated m_misbehavior_mutex lock.

This allows us to remove 14 cs_main locks from net_processing.
2020-08-12 11:23:21 +01:00
John Newbery 7cd4159ac8 [net processing] Add Peer
Peer is a struct for holding per-peer data. This structure is not
protected by cs_main since it does not contain validation-critical data.
2020-08-12 11:22:44 +01:00
John Newbery aba03359a6 [net processing] Remove CNodeState.name
This has been unused since logging peer IPs was removed from
Misbehaving() in a8865f8b.
2020-08-12 10:10:22 +01:00
John Newbery f26502e9fc [addrman] Specify max addresses and pct when calling GetAddresses()
CAddrMan.GetAddr() would previously limit the number and percentage of
addresses returned (to ADDRMAN_GETADDR_MAX (1000) and
ADDRMAN_GETADDR_MAX_PCT (23) respectively). Instead, make it the callers
responsibility to specify the maximum addresses and percentage they want
returned.

For net_processing, the maximums are MAX_ADDR_TO_SEND (1000) and
MAX_PCT_ADDR_TO_SEND (23). For rpc/net, the maximum is specified by the
client.
2020-08-12 09:22:07 +01:00
fanquake ce3bdd0ed1
Merge #19316: [net] Cleanup logic around connection types
01e283068b [net] Remove unnecessary default args on CNode constructor (Amiti Uttarwar)
bc5d65b3ca [refactor] Remove IsOutboundDisconnectionCandidate (Amiti Uttarwar)
2f2e13b6c2 [net/refactor] Simplify multiple-connection checks (Amiti Uttarwar)
7f7b83deb2 [net/refactor] Rework ThreadOpenConnections logic (Amiti Uttarwar)
35839e963b [net] Fix bug where AddrFetch connections would be counted as outbound full relay (Amiti Uttarwar)
4972c21b67 [net/refactor] Clarify logic for selecting connections in ThreadOpenConnections (Amiti Uttarwar)
60156f5fc4 [net/refactor] Remove fInbound flag from CNode (Amiti Uttarwar)
7b322df629 [net/refactor] Remove m_addr_fetch member var from CNode (Amiti Uttarwar)
14923422b0 [net/refactor] Remove fFeeler flag from CNode (Amiti Uttarwar)
49efac5cae [net/refactor] Remove m_manual_connection flag from CNode (Amiti Uttarwar)
d3698b5ee3 [net/refactor] Add connection type as a member var to CNode (Amiti Uttarwar)
46578c03e9 [doc] Describe different connection types (Amiti Uttarwar)
442abae2ba [net/refactor] Add AddrFetch connections to ConnectionType enum (Amiti Uttarwar)
af59feb052 [net/refactor] Extract m_addr_known logic from initializer list (Amiti Uttarwar)
e1bc29812d [net/refactor] Add block relay only connections to ConnectionType enum (Amiti Uttarwar)
0e52a659a2 [net/refactor] Add feeler connections to ConnectionType enum (Amiti Uttarwar)
1521c47438 [net/refactor] Add manual connections to ConnectionType enum (Amiti Uttarwar)
26304b4100 [net/refactor] Introduce an enum to distinguish type of connection (Amiti Uttarwar)
3f1b7140e9 scripted-diff: Rename OneShot to AddrFetch (Amiti Uttarwar)

Pull request description:

  **This is part 1 of #19315, which enables the ability to test `outbound` and `block-relay-only` connections from the functional tests.** Please see that PR for more information of overall functionality.

  **This PR simplifies how we manage different connection types.** It introduces an enum with the various types of connections so we can explicitly define the connection type. The existing system relies on a series of independent flags, then has asserts scattered around to ensure that conflicting flags are not enabled at the same time. I find this approach to be both brittle and confusing. While making these changes, I found a small bug due to the silent assumptions.

  This PR also proposes a rename from `OneShot` to `AddrFetch`. I find the name `OneShot` to be very confusing, especially when we also have `onetry` manual connections. Everyone I've talked to offline has agreed that the name is confusing, so I propose a potential alternative. I think this is a good opportunity for a rename since I'm creating an enum to explicitly define the connection types.
  (some context for the unfamiliar: `oneshot` or `addrfetch` connections are short-lived connections created on startup. They connect to the seed peers, send a `getaddr` to solicit addresses, then close the connection.)

  Overview of this PR:
  * rename `oneshot` to `addrfetch`
  * introduce `ConnectionType` enum
  * one by one, add different connection types to the enum
  * expose the `conn_type` on CNode, and use this to reduce reliance on flags (& asserts)
  * fix the bug in counting different type of connections
  * some additional cleanup to simplify logic and make expectations explicit/inclusive rather than implicit/exclusive.

ACKs for top commit:
  jnewbery:
    utACK 01e283068b
  laanwj:
    Code review ACK 01e283068b, the commits are pretty straightforward to follow, and I think this is a move in the right direction overall
  vasild:
    ACK 01e283068
  sdaftuar:
    ACK 01e283068b.
  fanquake:
    ACK 01e283068b - I don't have as much experience with the networking code but these changes look fairly straight forward, the new code seems more robust/understandable and the additional documentation is great. I'm glad that a followup branch is already underway. There might be some more review comments here later today, so keep an eye on the discussion, however I'm going to merge this now.
  jb55:
    wow this code was messy before... ACK 01e283068b

Tree-SHA512: 7bb644a6ed5849913d777ebc2ff89133ca0fbef680355a9a344e07496a979e6f9ff21a958e8eea93dcd7d5c343682b0c7174b1a3de380a4247eaae73da436e15
2020-08-12 10:01:44 +08:00
Wladimir J. van der Laan 85fa648c85
Merge #19596: Deduplicate parent txid loop of requested transactions and missing parents of orphan transactions
4c0731f9c5 Deduplicate missing parents of orphan transactions (Suhas Daftuar)
8196176243 Rewrite parent txid loop of requested transactions (Suhas Daftuar)

Pull request description:

  I noticed a couple of places recently where we loop over all inputs of a transaction in order to do some processing on the txids we find in those inputs.  There may be thousands of inputs in a transaction, and the same txid may appear many times.  In a couple of places in particular, we loop over those txids and add them to a rolling bloom filter; doing that multiple times for the same txid wastes entries in that filter.

  This PR fixes that in two places relating to transaction relay: one on the server side, where we look for parent transactions of a tx that we are delivering to a peer to ensure that getdata requests for those parents will succeed; and the other on the client side, where when we process an orphan tx we want to loop over the parent txids and ensure that all are eventually requested from the peer who provided the orphan.

  This addresses a couple of [related](https://github.com/bitcoin/bitcoin/pull/19109#discussion_r455197217) [comments](https://github.com/bitcoin/bitcoin/pull/19109#discussion_r456820373) left in #19109.

ACKs for top commit:
  laanwj:
    Code review ACK 4c0731f9c5
  jonatack:
    ACK 4c0731f9c5
  ajtowns:
    ACK 4c0731f9c5

Tree-SHA512: 8af9df7f56c6e54b5915519d7d5465e081473ceb1bcc89bbebf83e78722cf51ff58145e588cf57126bce17071a8053273f4bcef0ad8166bec83ba14352e40f5d
2020-08-10 20:38:19 +02:00
Amiti Uttarwar bc5d65b3ca [refactor] Remove IsOutboundDisconnectionCandidate 2020-08-07 17:18:17 -07:00
Amiti Uttarwar 2f2e13b6c2 [net/refactor] Simplify multiple-connection checks
Extract logic that check multiple connection types into interface functions &
structure as switch statements. This makes it very clear what touch points are
for accessing `m_conn_type` & using the switch statements enables the compiler
to warn if a new connection type is introduced but not handled for these cases.
2020-08-07 17:18:16 -07:00
Amiti Uttarwar 60156f5fc4 [net/refactor] Remove fInbound flag from CNode 2020-08-07 17:18:16 -07:00
Amiti Uttarwar 7b322df629 [net/refactor] Remove m_addr_fetch member var from CNode 2020-08-07 17:18:16 -07:00
Amiti Uttarwar 14923422b0 [net/refactor] Remove fFeeler flag from CNode 2020-08-07 17:18:16 -07:00
Amiti Uttarwar 49efac5cae [net/refactor] Remove m_manual_connection flag from CNode 2020-08-07 17:18:16 -07:00
Amiti Uttarwar 3f1b7140e9 scripted-diff: Rename OneShot to AddrFetch
-BEGIN VERIFY SCRIPT-
sed -i 's/a oneshot/an addrfetch/g' src/chainparams.cpp #comment
sed -i 's/oneshot/addrfetch/g' src/net.cpp #comment
sed -i 's/AddOneShot/AddAddrFetch/g' src/net.h src/net.cpp
sed -i 's/cs_vOneShots/m_addr_fetches_mutex/g' src/net.h src/net.cpp
sed -i 's/vOneShots/m_addr_fetches/g' src/net.h src/net.cpp
sed -i 's/fOneShot/m_addr_fetch/g' src/net.h src/net.cpp src/net_processing.cpp
sed -i 's/ProcessOneShot/ProcessAddrFetch/g' src/net.h src/net.cpp
-END VERIFY SCRIPT-
2020-08-07 17:18:12 -07:00
fanquake 6d8543504d
Merge #19620: Add txids with non-standard inputs to reject filter
9f88ded82b test addition of unknown segwit spends to txid reject filter (Gregory Sanders)
7989901c7e Add txids with non-standard inputs to reject filter (Suhas Daftuar)

Pull request description:

  Our policy checks for non-standard inputs depend only on the non-witness
  portion of a transaction: we look up the scriptPubKey of the input being
  spent from our UTXO set (which is covered by the input txid), and the p2sh
  checks only rely on the scriptSig portion of the input.

  Consequently it's safe to add txids of transactions that fail these checks to
  the reject filter, as the witness is irrelevant to the failure. This is helpful
  for any situation where we might request the transaction again via txid (either
  from txid-relay peers, or if we might fetch the transaction via txid due to
  parent-fetching of orphans).

  Further, in preparation for future witness versions being deployed on the
  network, ensure that WITNESS_UNKNOWN transactions are rejected in
  AreInputsStandard(), so that transactions spending v1 (or greater) witness
  outputs will fall into this category of having their txid added to the reject
  filter.

ACKs for top commit:
  ajtowns:
    ACK 9f88ded82b - code review
  jnewbery:
    Code review ACK 9f88ded82b
  ariard:
    Code Review/Tested ACK 9f88ded
  naumenkogs:
    utACK 9f88ded82b
  jonatack:
    ACK 9f88ded82b

Tree-SHA512: 1e93c0a5b68cb432524780ffc0093db893911fdfed9e2ed17f888e59114cc75d2a07062aefad4e5ce2e87c9270886117a8abb3c78fb889c9b9f31967f1777148
2020-08-07 07:34:27 +08:00
Suhas Daftuar 4c0731f9c5 Deduplicate missing parents of orphan transactions
In the logic for requesting missing parents of orphan transactions, parent
transactions with multiple outputs being spent by the given orphan were being
processed multiple times. Fix this by deduplicating the set of missing parent
txids first.

Co-authored-by: Anthony Towns <aj@erisian.com.au>
2020-08-04 13:59:16 -04:00
Suhas Daftuar 8196176243 Rewrite parent txid loop of requested transactions
Previously, we would potentially add the same txid many times to the rolling
bloom filter of recently announced transactions to a peer, if many outputs of
the same txid appeared as inputs in a transaction. Eliminate this problem and
avoid redundant lookups by asking the mempool for the unique parents of a
requested transaction.
2020-08-04 13:59:11 -04:00
Suhas Daftuar 7989901c7e Add txids with non-standard inputs to reject filter
Our policy checks for non-standard inputs depend only on the non-witness
portion of a transaction: we look up the scriptPubKey of the input being
spent from our UTXO set (which is covered by the input txid), and the p2sh
checks only rely on the scriptSig portion of the input.

Consequently it's safe to add txids of transactions that fail these checks to
the reject filter, as the witness is irrelevant to the failure. This is helpful
for any situation where we might request the transaction again via txid (either
from txid-relay peers, or if we might fetch the transaction via txid due to
parent-fetching of orphans).

Further, in preparation for future witness versions being deployed on the
network, ensure that WITNESS_UNKNOWN transactions are rejected in
AreInputsStandard(), so that transactions spending v1 (or greater) witness
outputs will fall into this category of having their txid added to the reject
filter.
2020-08-04 13:29:40 -04:00
Wladimir J. van der Laan 14ceddd290
Merge #18991: Cache responses to GETADDR to prevent topology leaks
3bd67ba5a4 Test addr response caching (Gleb Naumenko)
cf1569e074 Add addr permission flag enabling non-cached addr sharing (Gleb Naumenko)
acd6135b43 Cache responses to addr requests (Gleb Naumenko)
7cc0e8101f Remove useless 2500 limit on AddrMan queries (Gleb Naumenko)
ded742bc5b Move filtering banned addrs inside GetAddresses() (Gleb Naumenko)

Pull request description:

  This is a very simple code change with a big p2p privacy benefit.

  It’s currently trivial to scrape any reachable node’s AddrMan (a database of all nodes known to them along with the timestamps).
  We do have a limit of one GETADDR per connection, but a spy can disconnect and reconnect even from the same IP, and send GETADDR again and again.

  Since we respond with 1,000 random records at most, depending on the AddrMan size it takes probably up to 100 requests for an spy to make sure they scraped (almost) everything.
  I even have a script for that. It is totally doable within couple minutes.

  Then, with some extra protocol knowledge a spy can infer the direct peers of the victim, and other topological stuff.

  I suggest to cache responses to GETADDR on a daily basis, so that an attacker gets at most 1,000 records per day, and can’t track the changes in real time. I will be following up with more improvements to addr relay privacy, but this one alone is a very effective. And simple!

  I doubt any of the real software does *reconnect to get new addrs from a given peer*, so we shouldn’t be cutting anyone.
  I also believe it doesn’t have any negative implications on the overall topology quality. And the records being “outdated” for at most a day doesn’t break any honest assumptions either.

ACKs for top commit:
  jnewbery:
    reACK 3bd67ba5a4
  promag:
    Code review ACK 3bd67ba5a4.
  ariard:
    Code Review ACK 3bd67ba

Tree-SHA512: dfa5d03205c2424e40a3f8a41af9306227e1ca18beead3b3dda44aa2a082175bb1c6d929dbc7ea8e48e01aed0d50f0d54491caa1147471a2b72a46c3ca06b66f
2020-08-03 14:48:52 +02:00
Pieter Wuille 10b7a6d532 refactor: make txmempool interface use GenTxid 2020-07-30 13:45:03 -07:00
Pieter Wuille 5c124e1740 refactor: make FindTxForGetData use GenTxid 2020-07-30 13:45:02 -07:00
Pieter Wuille a2bfac8935 refactor: use GenTxid in tx request functions 2020-07-30 13:45:02 -07:00
Pieter Wuille 900d7f6c07 p2p: enable fetching of orphans from wtxid peers
Based on a commit by Anthony Towns.
2020-07-30 13:45:02 -07:00
Pieter Wuille 9efd86a908 refactor: add GenTxid (=txid or wtxid) type and use it for tx request logic 2020-07-30 13:44:54 -07:00
Wladimir J. van der Laan 17de75b028
Merge #19590: p2p, refactor: add CInv transaction message helpers; use in net processing
c251d710a4 p2p, refactoring: use CInv helpers in net_processing.cpp (Jon Atack)
4254cd9f8f p2p: add CInv transaction message helper methods (Jon Atack)

Pull request description:

  Following the merge of wtxid relay in #18044, this is the first of three refactoring PRs (this one, #19610, and #19611) with no change in behavior, tightly scoped to ease review, to simplify the net processing code and improve encapsulation:

  - add `CInv` transaction message helper methods, defined in the class

  - use the new helpers in `net_processing.cpp` to simplify the code and improve encapsulation

  Test coverage is provided by the functional p2p tests, notably (from seeing which tests failed when breaking things to test coverage) `p2p_segwit`, `p2p_tx_download`, `p2p_feefilter`, and `p2p_permissions`.

ACKs for top commit:
  fjahr:
    Code review ACK c251d710a4
  laanwj:
    Code review ACK c251d710a4
  vasild:
    ACK c251d71
  theStack:
    Code-Review ACK c251d710a4
  hebasto:
    ACK c251d710a4, I have reviewed the code and it looks OK, I agree it can be merged.

Tree-SHA512: ead034b3c9e438909b4c5010c570d7930e69063c114290b051b7cebfd9bd5b19f573218bebe8a521256d32e830797f997adad3d85b4539c64ac5762b698e656d
2020-07-30 16:18:06 +02:00
Gleb Naumenko cf1569e074 Add addr permission flag enabling non-cached addr sharing 2020-07-30 14:38:50 +03:00
Gleb Naumenko acd6135b43 Cache responses to addr requests
Prevents a spy from scraping victim's AddrMan by
reconnecting and re-requesting addrs.
2020-07-30 14:38:48 +03:00
Jon Atack c251d710a4
p2p, refactoring: use CInv helpers in net_processing.cpp
to simplify the code and reach less from it into the CInv class internals
2020-07-27 11:06:48 +02:00
John Newbery a8865f8b72 [net processing] Tidy up Misbehaving()
- Make const things const.
- Replace conditional return with assert.
- Don't log the peer's IP address.
- Log the name Misbehaving directly instead of relying on __func__.
2020-07-25 15:52:23 +01:00
John Newbery d15b3afb4c [net processing] Always supply debug message to Misbehaving()
Misbehaving() could optionally take a debug string for printing to the
log file. Make this mandatory and always provide the string.

A couple of additional minor changes:

- remove the unnecessary forward declaration of Misbehaving()
- don't include the nodeid or newline in the passed debug message.
Misbehaving() adds these itself.
2020-07-25 15:50:34 +01:00
John Newbery 634144a1c2 [net processing] Fixup MaybeDiscourageAndDisconnect() style
Based on review comments from Marco Falke and Jon Atack.
2020-07-25 15:49:24 +01:00
Wladimir J. van der Laan 40a04814d1
Merge #19472: [net processing] Reduce cs_main scope in MaybeDiscourageAndDisconnect()
655b195747 [net processing] Continue SendMessages processing if not disconnecting peer (John Newbery)
a49781e56d [net processing] Only call MaybeDiscourageAndDisconnect from SendMessages (John Newbery)
a1d5a428a2 [net processing] Fix bad indentation in SendMessages() (John Newbery)
1a1c23f8d4 [net processing] Change cs_main TRY_LOCK to LOCK in SendMessages() (John Newbery)

Pull request description:

  The motivation for this PR is to reduce the scope of cs_main locking in misbehavior logic. It is the first set of commits from a larger branch to move the misbehavior data out of CNodeState and into a new struct that doesn't take cs_main.

  There are some very minor behavior changes in this branch, such as:

  - Not checking for discouragement/disconnect in `ProcessMessages()` (and instead relying on the following check in `SendMessages()`)
  - Checking for discouragement/disconnect as the first action in `SendMessages()` (and not doing ping message sending first)
  - Continuing through `SendMessages()` if `MaybeDiscourageAndDisconnect()` doesn't disconnect the peer (rather than dropping out of `SendMessages()`

ACKs for top commit:
  jonatack:
    re-ACK 655b195 per `git range-diff 505b4ed f54af5e 655b195`, code/commit messages review, a bit of code history, and debug build.
  MarcoFalke:
    ACK 655b195747 only some style-nits 🚁
  promag:
    Code review ACK 655b195747.
  ariard:
    Code Review ACK 655b195

Tree-SHA512: fd6d7bc6bb789f5fb7771fb6a45f61a8faba32af93b766554f562144f9631d15c9cc849a383e71743ef73e610b4ee14853666f6fbf08a3ae35176d48c76c65d3
2020-07-24 17:20:58 +02:00
Gleb Naumenko 7cc0e8101f Remove useless 2500 limit on AddrMan queries 2020-07-24 18:02:20 +03:00
Gleb Naumenko ded742bc5b Move filtering banned addrs inside GetAddresses() 2020-07-24 18:02:20 +03:00
Suhas Daftuar 0a4f1422cd Further improve comments around recentRejects 2020-07-19 02:10:42 -04:00
Suhas Daftuar 0e20cfedb7 Disconnect peers sending wtxidrelay message after VERACK 2020-07-19 02:10:42 -04:00
Suhas Daftuar dd78d1d641 Rename AddInventoryKnown() to AddKnownTx() 2020-07-19 02:10:42 -04:00
Suhas Daftuar 4eb515574e Make TX_WITNESS_STRIPPED its own rejection reason
Previously, TX_WITNESS_MUTATED could be returned during transaction validation
for either transactions that had a witness that was non-standard, or for
transactions that had no witness but were invalid due to segwit validation
rules.

However, for txid/wtxid-relay considerations, net_processing distinguishes the
witness stripped case separately, because it affects whether a wtxid should be
able to be added to the reject filter. It is safe to add the wtxid of a
witness-mutated transaction to the filter (as that wtxid shouldn't collide with
the txid, and hence it wouldn't interfere with transaction relay from
txid-relay peers), but it is not safe to add the wtxid (== txid) of a
witness-stripped transaction to the filter, because that would interfere with
relay of another transaction with the same txid (but different wtxid) when
relaying from txid-relay peers.

Also updates the comment explaining this logic, and explaining that we can get
rid of this complexity once there's a sufficient deployment of wtxid-relaying
peers on the network.
2020-07-19 02:10:42 -04:00
Suhas Daftuar 97141ca442 Delay getdata requests from peers using txid-based relay
Using both txid and wtxid-based relay with peers means that we could sometimes
download the same transaction twice, if announced via two different hashes from
different peers.

Use a heuristic of delaying txid-peer-getdata requests by 2 seconds, if we have
at least one wtxid-based peer.
2020-07-19 02:10:42 -04:00