Commit Graph

46 Commits

Author SHA1 Message Date
Pieter Wuille
7c1c9d0ea6 Merge #8427: net: Ignore notfound P2P messages
5c9e49d net: Ignore `notfound` P2P messages (Wladimir J. van der Laan)
2018-01-08 18:04:55 +01:00
UdjinM6
38e505842a
Vote on IS only if it was accepted to mempool (#1826) 2018-01-06 13:06:43 +03:00
Wladimir J. van der Laan
bc257c1a08 Merge #8305: Improve handling of unconnecting headers
e91cf4b Add test for handling of unconnecting headers (Suhas Daftuar)
96fa953 Improve handling of unconnecting headers (Suhas Daftuar)
2017-12-28 11:44:59 +01:00
Alexander Block
36aa554584 Temporarily fix build error cased by out-of-order backporting
Can be removed when we catch up with backporting. You'll notice it's time
for this when you get conflicts while merging the affected backported PR.
2017-12-28 11:44:59 +01:00
Wladimir J. van der Laan
808936cc30 Merge #8179: Evict orphans which are included or precluded by accepted blocks.
54326a6 Increase maximum orphan size to 100,000 bytes. (Gregory Maxwell)
8c99d1b Treat orphans as implicit inv for parents, discard when parents rejected. (Gregory Maxwell)
11cc143 Adds an expiration time for orphan tx. (Gregory Maxwell)
db0ffe8 This eliminates the primary leak that causes the orphan map to  always grow to its maximum size. (Gregory Maxwell)
1b0bcc5 Track orphan by prev COutPoint rather than prev hash (Pieter Wuille)
2017-12-28 11:44:59 +01:00
Alexander Block
c7937c202e Remove unnecessary call to AddInventoryKnown in INV message handling
This should have been part of Bitcoin #7960 but was missed in merge
conflict resolution.
2017-12-27 14:07:19 +01:00
Wladimir J. van der Laan
e7e3a80712 Merge #8141: Continuing port of java comparison tool
ff2dcf2 Tests: Edit bloated varint test and add option for 'barely expensive' tests (mrbandrews)
12c5a16 Catch exceptions from non-canonical encoding and print only to log (mrbandrews)
291f8aa Continuing port of java comptool (mrbandrews)
8c9e681 Tests: Rework blockstore to avoid re-serialization. (mrbandrews)
2017-12-22 17:20:43 +01:00
Wladimir J. van der Laan
aa6cb48bfa Merge #8154: drop vAddrToSend after sending big addr message
d3d02d5 drop vAddrToSend after sending big addr message (Kaz Wesley)
2017-12-22 17:20:31 +01:00
Pieter Wuille
361d26037b Merge #8173: Use SipHash for node eviction (cont'd)
eebc232 test: Add more test vectors for siphash (Wladimir J. van der Laan)
8884830 Use C++11 thread-safe static initializers (Pieter Wuille)
c31b24f Use 64-bit SipHash of netgroups in eviction (Pieter Wuille)
9bf156b Support SipHash with arbitrary byte writes (Pieter Wuille)
053930f Avoid recalculating vchKeyedNetGroup in eviction logic. (Patrick Strateman)
2017-12-22 16:33:56 +01:00
Wladimir J. van der Laan
ca699cebaa Merge #8126: std::shared_ptr based CTransaction storage in mempool
288d85d Get rid of CTxMempool::lookup() entirely (Pieter Wuille)
c2a4724 Optimization: use usec in expiration and reuse nNow (Pieter Wuille)
e9b4780 Optimization: don't check the mempool at all if no mempool req ever (Pieter Wuille)
dbfb426 Optimize the relay map to use shared_ptr's (Pieter Wuille)
8d39d7a Switch CTransaction storage in mempool to std::shared_ptr (Pieter Wuille)
1b9e6d3 Add support for unique_ptr and shared_ptr to memusage (Pieter Wuille)
2017-12-22 16:33:56 +01:00
Pieter Wuille
51fa05ac33 Merge #8082: Defer inserting into maprelay until just before relaying.
4d8993b Defer inserting into maprelay until just before relaying. (Gregory Maxwell)
2017-12-22 16:33:55 +01:00
Wladimir J. van der Laan
2ee817fb0d Merge #8078: Disable the mempool P2P command when bloom filters disabled
3d3602f Add RPC test for the p2p mempool command in conjunction with disabled bloomfilters (Jonas Schnelli)
beceac9 Disable the mempool P2P command when bloom filters disabled (Peter Todd)
2017-12-22 16:33:55 +01:00
Pieter Wuille
bad08eadf8 Merge #7960: Only use AddInventoryKnown for transactions
383fc10 Only use AddInventoryKnown for transactions (Suhas Daftuar)
2017-12-22 16:33:04 +01:00
Alexander Block
83dc1dc99c Directly push messages instead of using CDataStream first 2017-12-22 16:33:04 +01:00
Wladimir J. van der Laan
dfa0bd2341 Merge #8080: Do not use mempool for GETDATA for tx accepted after the last mempool req.
7e908c7 Do not use mempool for GETDATA for tx accepted after the last mempool req. (Gregory Maxwell)
2017-12-22 16:33:03 +01:00
Alexander Block
b2a27c0624 Only serve normal transactions from mapRelay
Bitcoin #7877 changed mapRelay to be indexed by hash instead of inv. This
means that we may end up with a false-positive match here and send out an
instant transaction as normal transaction.
2017-12-22 16:33:03 +01:00
Wladimir J. van der Laan
bef036125f Merge #7877: Change mapRelay to store CTransactions
38c3102 Change mapRelay to store CTransactions (Pieter Wuille)
2017-12-22 16:33:03 +01:00
Alexander Block
2dc71e8e08 Revert deadlock fix in ProcessGetData
Fix was introdeced in:
https://github.com/dashpay/dash/pull/1169
A fix was later applied to fix a race condition:
https://github.com/dashpay/dash/pull/1178

This has to be reverted to be able to backport multiple changes from Bitcoin.
Later backported PRs from Bitcoin will remove cs_mapRelay and thus also
remove the deadlock that was initially fixed with the above PRs.
2017-12-22 16:33:03 +01:00
Pieter Wuille
43cbeb7fa5 Merge #7891: Always require OS randomness when generating secret keys
628cf14 Don't use assert for catching randomness failures (Pieter Wuille)
fa2637a Always require OS randomness when generating secret keys (Pieter Wuille)
2017-12-21 18:50:14 +01:00
Wladimir J. van der Laan
8b28f5f995 Merge #8020: Use SipHash-2-4 for various non-cryptographic hashes
a68ec21 Use SipHash-2-4 for address relay selection (Pieter Wuille)
8cc9cfe Switch CTxMempool::mapTx to use a hash index for txids (Pieter Wuille)
382c871 Use SipHash-2-4 for CCoinsCache index (Pieter Wuille)
0b1295b Add SipHash-2-4 primitives to hash (Pieter Wuille)
2017-12-21 18:50:13 +01:00
Pieter Wuille
7b25879463 Merge #8059: Remove unneeded feerate param from RelayTransaction/AcceptToMemoryPool.
d87b198 Remove unneeded feerate param from RelayTransaction/AcceptToMemoryPool. (Gregory Maxwell)
2017-12-21 18:50:13 +01:00
Alexander Block
d4b8abf4ff Send non-tx/non-block inventory items
Bitcoin #7840 has split the INVs to send into block and TX and completely
ignores non-tx/non-block items in PushInventory. This is fine for Bitcoin,
as they only use it for blocks and TXs, but we also have a lot of MN related
messages which also need to be relayed.
2017-12-21 17:30:51 +01:00
Wladimir J. van der Laan
5d8e94a26f Merge #7840: Several performance and privacy improvements to inv/mempool handling
b559914 Move bloom and feerate filtering to just prior to tx sending. (Gregory Maxwell)
4578215 Return mempool queries in dependency order (Pieter Wuille)
ed70683 Handle mempool requests in send loop, subject to trickle (Pieter Wuille)
dc13dcd Split up and optimize transaction and block inv queues (Pieter Wuille)
f2d3ba7 Eliminate TX trickle bypass, sort TX invs for privacy and priority. (Gregory Maxwell)
2017-12-21 17:30:51 +01:00
Wladimir J. van der Laan
24f8c248f5 Merge #7856: Only send one GetAddr response per connection.
66b0724 Only send one GetAddr response per connection. (Gregory Maxwell)
2017-12-20 17:25:02 +01:00
Pieter Wuille
d983f1d785 Merge #7828: Trivial: Globals: Explicitly pass const CChainParams& to ProcessMessage()
bf477bc Trivial: Globals: Explicitly pass const CChainParams& to ProcessMessage() (Jorge Timón)
2017-12-20 14:58:27 +01:00
Alexander Block
cd9c6994c2 Implement named devnets (#1791)
* Initial devnet

* Move genesis block adding into its own method

* Introduce -allowprivatenet to lift limitation on RFC1918 addresses

Normally, RFC1918 (192.168.x.x/10.x.x.x/...) addresses are not allowed
to be relayed. Also, masternodes won't start when the address is considered
invalid.

This is needed to test local devnet or regtest based networks.

* Lift the requirement of minimum MN age for regtest/devnet

* Implement named devnets

This allows the creation of multiple independent devnets. Each one is
identified by a name which is hardened into a "devnet genesis" block,
which is automatically positioned at height 1. Validation rules will
ensure that a node from devnet=test1 never be able to accept blocks
from devnet=test2. This is done by checking the expected devnet genesis
block.

The genesis block of the devnet is the same as the one from regtest. This
starts the devnet with a very low difficulty, allowing us to fill up
needed balances for masternodes very fast.

Also, the devnet name is put into the sub-version of the VERSION message.
If a node connects to the wrong network, it will immediately be disconnected.

* Allow to select multiple addresses from the same group in devnet/regtest

The selection code normally only allows to select addresses from the same
group (e.g. 192.168.x.x) once. This results in connecting to only a single
node in devnet/regtest.

* Show the devnet name in the title bar and on the loading screen

* Add AllowMultipleAddressesFromGroup to chainparams and use it in net.cpp

* Remove unused/unneeded scripts from devnet geneses creation

1. OP_RETURN not needed in input script of devnet genesis
2. genesisOutputScript was unused

* Fix copy/paste error in -allowprivatenet description

* Improve -devnet parameter error handling

- Only allow one of -devnet, -regtest or -testnet
- Only allow -devnet=name to be specified once

* Use different datadir for each devnet

* Fix `devnet-devnet` issue

* Fix devnet splashscreen (should use testnet img)

* Avoid passing devNetName around (most of the time)

* Remove nMaxTipAge from CDevNetParams

Not present anymore after rebase on develop
2017-12-20 14:45:01 +03:00
Wladimir J. van der Laan
11ac70af9e Merge #7542: Implement "feefilter" P2P message
0371797 modify release-notes.md and bips.md (Alex Morcos)
b536a6f Add p2p test for feefilter (Alex Morcos)
5fa66e4 Create SingleNodeConnCB class for RPC tests (Alex Morcos)
9e072a6 Implement "feefilter" P2P message. (Alex Morcos)
2017-12-19 13:18:30 +01:00
Wladimir J. van der Laan
f4d30a6452 Merge #7708: De-neuter NODE_BLOOM
c90036f Always disconnect old nodes which request filtered connections. (Patrick Strateman)
2017-12-19 12:55:49 +01:00
Wladimir J. van der Laan
97c7da4b7a Merge #7509: Common argument defaults for NODE_BLOOM stuff and -wallet
1fb91b3 Common argument defaults for NODE_BLOOM stuff and -wallet (Luke Dashjr)
2017-12-11 08:30:26 +01:00
Wladimir J. van der Laan
bf688abcee Merge pull request #7113
086ee67 Switch to a more efficient rolling Bloom filter (Pieter Wuille)
2017-12-10 00:04:01 +01:00
UdjinM6
c166ed39b0
Allow compilation with --disable-wallet (#1733)
* Allow compilation with `--disable-wallet`

* fix remaining references

* Drop wallet references/include in CActiveMasternode and fix other files affected by this change

* Wrap privatesend-client.h include with ifdef/endif and fix other files affected by this change

* Re-enable Travis build with no wallet

reverts 267e57877b
2017-12-01 21:53:34 +03:00
Pieter Wuille
c81394b975 Merge #10195: Switch chainstate db and cache to per-txout model
589827975 scripted-diff: various renames for per-utxo consistency (Pieter Wuille)
a5e02bc7f Increase travis unit test timeout (Pieter Wuille)
73de2c1ff Rename CCoinsCacheEntry::coins to coin (Pieter Wuille)
119e552f7 Merge CCoinsViewCache's GetOutputFor and AccessCoin (Pieter Wuille)
580b02309 [MOVEONLY] Move old CCoins class to txdb.cpp (Pieter Wuille)
8b25d2c0c Upgrade from per-tx database to per-txout (Pieter Wuille)
b2af357f3 Reduce reserved memory space for flushing (Pieter Wuille)
41aa5b79a Pack Coin more tightly (Pieter Wuille)
97072d668 Remove unused CCoins methods (Pieter Wuille)
ce23efaa5 Extend coins_tests (Pieter Wuille)
508307968 Switch CCoinsView and chainstate db from per-txid to per-txout (Pieter Wuille)
4ec0d9e79 Refactor GetUTXOStats in preparation for per-COutPoint iteration (Pieter Wuille)
13870b56f Replace CCoins-based CTxMemPool::pruneSpent with isSpent (Pieter Wuille)
05293f3cb Remove ModifyCoins/ModifyNewCoins (Pieter Wuille)
961e48397 Switch tests from ModifyCoins to AddCoin/SpendCoin (Pieter Wuille)
8b3868c1b Switch CScriptCheck to use Coin instead of CCoins (Pieter Wuille)
c87b957a3 Only pass things committed to by tx's witness hash to CScriptCheck (Matt Corallo)
f68cdfe92 Switch from per-tx to per-txout CCoinsViewCache methods in some places (Pieter Wuille)
000391132 Introduce new per-txout CCoinsViewCache functions (Pieter Wuille)
bd83111a0 Optimization: Coin&& to ApplyTxInUndo (Pieter Wuille)
cb2c7fdac Replace CTxInUndo with Coin (Pieter Wuille)
422634e2f Introduce Coin, a single unspent output (Pieter Wuille)
7d991b55d Store/allow tx metadata in all undo records (Pieter Wuille)
c3aa0c119 Report on-disk size in gettxoutsetinfo (Pieter Wuille)
d34242430 Remove/ignore tx version in utxo and undo (Pieter Wuille)
7e0032290 Add specialization of SipHash for 256 + 32 bit data (Pieter Wuille)
e484652fc Introduce CHashVerifier to hash read data (Pieter Wuille)
f54580e7e error() in disconnect for disk corruption, not inconsistency (Pieter Wuille)
e66dbde6d Add SizeEstimate to CDBBatch (Pieter Wuille)

Tree-SHA512: ce1fb1e40c77d38915cd02189fab7a8b125c7f44d425c85579d872c3bede3a437760997907c99d7b3017ced1c2de54b2ac7223d99d83a6658fe5ef61edef1de3
2017-10-31 21:19:11 +01:00
Wladimir J. van der Laan
753cb1563b Merge #7874: Improve AlreadyHave
c6cb6f7 Avoid unnecessary database access for unknown transactions (Alex Morcos)
2017-10-19 10:51:45 +02:00
Oleg Girko
753b1e486b Eliminate remaining uses of g_connman in Dash-specific code. (#1635)
This monstrous change eliminates all remaining uses of
g_connman global variable in Dash-specific code.

Unlike previous changes eliminating g_connman use
that were isolated to particular modules, this one covers
multiple modules simultaneously because they are so interdependent
that change in one module was quickly spreading to others.

This is mostly invariant change that was done by
* changing all functions using g_connman to use connman argument,
* changing all functions calling these functions to use connman argument,
* repeating previous step until there's nothing to change.

After multiple iterations, this process converged to final result,
producing code that is mostly equivalent to original one, but passing
CConnman instance through arguments instead of global variable.

The only exception to equivalence of resulting code is that I had to
create overload of CMasternodeMan::CheckAndRemove() method without arguments
that does nothing just for use in CFlatDB<CMasternodeMan>::Dump() and
CFlatDB<CMasternodeMan>::Load() methods.
Normal CMasternodeMan::CheckAndRemove() overload now has argument of
CConnman& type and is used everywhere else.

The normal overload has this code in the beginning:

    if(!masternodeSync.IsMasternodeListSynced()) return;

Masternode list is not synced yet when we load "mncache.dat" file,
and we save "mncache.dat" file on shutdown, so I presume that it's OK
to use overload that does nothing in both cases.

Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-09-19 17:51:38 +03:00
Oleg Girko
4956ba7a7f Eliminate g_connman use in instantx module. (#1626)
Pass reference to CConnman instance to methods of CInstantSend
and other instantsend-related classes instead of using g_connman
global variable there.

Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-09-15 21:05:13 +03:00
UdjinM6
05da4557d0 Refactor masternode management (#1611)
* Store masternodes in a map instead of a vector, drop unused functions in CMasternodeMan

* CTxIn vin -> COutPoint outpoint

* do not use CMasternodeMan::Find outside of the class

* update GetMasternodeInfo

* safe version of GetNextMasternodeInQueueForPayment

* fix ProcessMasternodeConnections

* bump CMasternodeMan::SERIALIZATION_VERSION_STRING
2017-09-11 17:13:48 +03:00
Oleg Girko
8da26da713 Eliminate g_connman use in spork module. (#1613)
Pass reference to CConnman instance to methods of CSporkManager and
CSporkMessage instead of using g_connman global variable.

Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-09-07 18:58:38 +03:00
Alexander Block
169afafd50 Fix duplicate headers download in initial sync (#1589)
* Fix duplicate headers download in initial sync

Now that initial block download is delayed until the headers sync is done,
it was noticed that the initial headers sync may happen multiple times in
parallel in the case new blocks are announced. This happens because for
every block in INV that is received, a getheaders message is immediately
sent out resulting in a full download of the headers chain starting from
the point of where the initial headers sync is currently at. This happens
once for each peer that announces the new block. This slows down the
initial headers sync and increases the chance of another block being
announced before it is finished, probably leading to the same behavior
as already described, slowing down the sync even more...and so on.

This commit delays sending of GETHEADERS to later in case the chain is too
far behind while a new block gets announced. Header chains will still be
downloaded multiple times, but the downloading will start much closer
to the tip of the chain, so the damage is not that bad anymore.

This ensures that we get all headers from all peers, even if any of them
is on another chain. This should avoid what happened in
https://github.com/bitcoin/bitcoin/pull/8054
which needed to be reverted later.

This fixes the Bitcoin issue https://github.com/bitcoin/bitcoin/issues/6755

* Introduce DelayGetHeadersTime chain param and fix tests

The delaying of GETHEADERS in combination with very old block times in
test cases resulted in the delaying being triggered when the first newly
mined block arrives. This results in a completely stalled sync.

This is fixed by avoiding delaying in when running tests.

* Disconnect peers which are not catched up

Peers which stop sending us headers too early are very likely peers which
did not catch up before and stalled for some reason. We should disconnect
these peers and chose another one to continue.
2017-09-04 09:10:52 +03:00
Oleg Girko
b82b9787d2 Backport Bitcoin PR#8128: Net: Turn net structures into dumb storage classes (#1604)
* net: Split resolving out of CNetAddr

* net: Split resolving out of CService

* net: Split resolving out of CSubNet

* net: move CNetAddr/CService/CSubNet out of netbase

* net: narrow include scope after moving to netaddress

Net functionality is no longer needed for CAddress/CAddrman/etc. now that
CNetAddr/CService/CSubNet are dumb storage classes.

* net: Add direct tests for new CSubNet constructors

* net: Have LookupNumeric return a CService directly

Also fix up a few small issues:
- Lookup with "badip:port" now sets the port to 0
- Don't allow assert to have side-effects

* net: fixup nits
2017-09-03 16:29:10 +03:00
Oleg Girko
589d22f2ca net: No longer send local address in addrMe (#1600)
After #8594 the addrFrom sent by a node is not used anymore at all,
so don't bother sending it.

Also mitigates the privacy issue in (#8616). It doesn't completely solve
the issue as GetLocalAddress is also called in AdvertiseLocal, but at
least when advertising addresses it stands out less as *our* address.
2017-09-01 06:12:23 +03:00
Oleg Girko
76181f5757 Do not add random inbound peers to addrman. (#1593)
We should learn about new peers via address messages.

An inbound peer connecting to us tells us nothing about
 its ability to accept incoming connections from us, so
 we shouldn't assume that we can connect to it based on
 this.

The vast majority of nodes on the network do not accept
 incoming connections, adding them will only slow down
 the process of making a successful connection in the
 future.

Nodes which have configured themselves to not announce would prefer we
 not violate their privacy by announcing them in GETADDR responses.
2017-08-31 18:34:24 +03:00
Alexander Block
ccee103a0e Backport "assumed valid blocks" feature from Bitcoin 0.13 (#1582)
* IBD check uses minimumchain work instead of checkpoints.

This introduces a 'minimum chain work' chainparam which is intended
 to be the known amount of work in the chain for the network at the
 time of software release.  If you don't have this much work, you're
 not yet caught up.

This is used instead of the count of blocks test from checkpoints.

This criteria is trivial to keep updated as there is no element of
subjectivity, trust, or position dependence to it. It is also a more
reliable metric of sync status than a block count.

* Remove GetTotalBlocksEstimate and checkpoint tests that test nothing.

GetTotalBlocksEstimate is no longer used and it was the only thing
 the checkpoint tests were testing.

Since checkpoints are on their way out it makes more sense to remove
 the test file than to cook up a new pointless test.

# Conflicts:
#	src/Makefile.test.include
#	src/test/Checkpoints_tests.cpp

* IsInitialBlockDownload no longer uses header-only timestamps.

This avoids a corner case (mostly visible on testnet) where bogus
 headers can keep nodes in IsInitialBlockDownload.

* Delay parallel block download until chain has sufficient work

nMinimumChainWork is an anti-DoS threshold; wait until we have a proposed
tip with more work than that before downloading blocks towards that tip.

* Add timeout for headers sync

At startup, we choose one peer to serve us the headers chain, until
our best header is close to caught up.  Disconnect this peer if more
than 15 minutes + 1ms/expected_header passes and our best header
is still more than 1 day away from current time.

* Introduce assumevalid setting to skip presumed valid scripts.

This disentangles the script validation skipping from checkpoints.

A new option is introduced "assumevalid" which specifies a block whos
 ancestors we assume all have valid scriptsigs and so we do not check
 them when they are also burried under the best header by two weeks
 worth of work.

Unlike checkpoints this has no influence on consensus unless you set
 it to a block with an invalid history.  Because of this it can be
 easily be updated without risk of influencing the network consensus.

This results in a massive IBD speedup.

This approach was independently recommended by Peter Todd and Luke-Jr
 since POW based signature skipping (see PR#9180) does not have the
 verifiable properties of a specific hash and may create bad incentives.

The downside is that, like checkpoints, the defaults bitrot and older
 releases will sync slower.  On the plus side users can provide their
 own value here, and if they set it to something crazy all that will
 happen is more time will be spend validating signatures.

Checkblocks and checklevel are also moved to the hidden debug options:
 Especially now that checkblocks has a low default there is little need
 to change these settings, and users frequently misunderstand them as
 influencing security or IBD speed.  By hiding them we offset the
 space added by this new option.

* Add consensusParams to FindNextBlocksToDownload

* Adjust check in headers timeout logic to align with 144 blocks in Dash
2017-08-23 17:21:08 +03:00
Oleg Girko
2472999da0 Backport Bitcoin PR#9441: Net: Massive speedup. Net locks overhaul (#1586)
* net: fix typo causing the wrong receive buffer size

Surprisingly this hasn't been causing me any issues while testing, probably
because it requires lots of large blocks to be flying around.

Send/Recv corks need tests!

* net: make vRecvMsg a list so that we can use splice()

* net: make GetReceiveFloodSize public

This will be needed so that the message processor can cork incoming messages

* net: only disconnect if fDisconnect has been set

These conditions are problematic to check without locking, and we shouldn't be
relying on the refcount to disconnect.

* net: wait until the node is destroyed to delete its recv buffer

when vRecvMsg becomes a private buffer, it won't make sense to allow other
threads to mess with it anymore.

* net: set message deserialization version when it's actually time to deserialize

We'll soon no longer have access to vRecvMsg, and this is more intuitive anyway.

* net: handle message accounting in ReceiveMsgBytes

This allows locking to be pushed down to only where it's needed

Also reuse the current time rather than checking multiple times.

* net: record bytes written before notifying the message processor

* net: Add a simple function for waking the message handler

This may be used publicly in the future

* net: remove useless comments

* net: remove redundant max sendbuffer size check

This is left-over from before there was proper accounting. Hitting 2x the
sendbuffer size should not be possible.

* net: rework the way that the messagehandler sleeps

In order to sleep accurately, the message handler needs to know if _any_ node
has more processing that it should do before the entire thread sleeps.

Rather than returning a value that represents whether ProcessMessages
encountered a message that should trigger a disconnnect, interpret the return
value as whether or not that node has more work to do.

Also, use a global fProcessWake value that can be set by other threads,
which takes precedence (for one cycle) over the messagehandler's decision.

Note that the previous behavior was to only process one message per loop
(except in the case of a bad checksum or invalid header). That was changed in
PR #3180.

The only change here in that regard is that the current node now falls to the
back of the processing queue for the bad checksum/invalid header cases.

* net: add a new message queue for the message processor

This separates the storage of messages from the net and queued messages for
processing, allowing the locks to be split.

* net: add a flag to indicate when a node's process queue is full

Messages are dumped very quickly from the socket handler to the processor, so
it's the depth of the processing queue that's interesting.

The socket handler checks the process queue's size during the brief message
hand-off and pauses if necessary, and the processor possibly unpauses each time
a message is popped off of its queue.

* net: add a flag to indicate when a node's send buffer is full

Similar to the recv flag, but this one indicates whether or not the net's send
buffer is full.

The socket handler checks the send queue when a new message is added and pauses
if necessary, and possibly unpauses after each message is drained from its buffer.

* net: remove cs_vRecvMsg

vRecvMsg is now only touched by the socket handler thread.

The accounting vars (nRecvBytes/nLastRecv/mapRecvBytesPerMsgCmd) are also
only used by the socket handler thread, with the exception of queries from
rpc/gui. These accesses are not threadsafe, but they never were. This needs to
be addressed separately.

Also, update comment describing data flow
2017-08-23 17:20:43 +03:00
Oleg Girko
b9c67258ba Backport Bitcoin PR#9609: net: fix remaining net assertions (#1575) + Dashify
* Dont deserialize nVersion into CNode, should fix #9212

* net: deserialize the entire version message locally

This avoids having some vars set if the version negotiation fails.

Also copy it all into CNode at the same site. nVersion and
fSuccessfullyConnected are set last, as they are the gates for the other vars.
Make them atomic for that reason.

* net: don't run callbacks on nodes that haven't completed the version handshake

Since ForEach* are can be used to send messages to  all nodes, the caller may
end up sending a message before the version handshake is complete. To limit
this, filter out these nodes. While we're at it, may as well filter out
disconnected nodes as well.

Delete unused methods rather than updating them.

* net: Disallow sending messages until the version handshake is complete

This is a change in behavior, though it's much more sane now than before.

* net: log an error rather than asserting if send version is misused

Also cleaned up the comments and moved from the header to the .cpp so that
logging headers aren't needed from net.h

* Implement conditions for ForEachNode() and ForNode() methods of CConnman.

A change making ForEachNode() and ForNode() methods ignore nodes that
have not completed initial handshake have been backported from Bitcoin.
Unfortunately, some Dash-specific code needs to iterate over all nodes.

This change introduces additional condition argument to these methods.
This argument is a functional object that should return true for nodes
that should be taken into account, not ignored.

Two functional objects are provided in CConnman namespace:
* FullyConnectedOnly returns true for nodes that have handshake completed,
* AllNodes returns true for all nodes.

Overloads for ForEachNode() and ForNode() methods without condition argument
are left for compatibility with non-Dash-specific code.
They use FullyConnectedOnly functional object for condition.

Signed-off-by: Oleg Girko <ol@infoserver.lv>

* Iterate over all nodes in Dash-specific code using AllNodes condition.

Use AllNodes functional object as newly introduced condition argument for
ForEachNode() and ForNode() methods of CConnman to iterate over all nodes
where needed in Dash-specific code.

Signed-off-by: Oleg Girko <ol@infoserver.lv>
2017-08-17 21:37:22 +03:00
Oleg Girko
42c784dc7a Backport Bitcoin PR#9289: net: drop boost::thread_group (#1568)
* net: a few small cleanups before replacing boost threads

- Drop the interruption point directly after the pnode allocation. This would
    be leaky if hit.
- Rearrange thread creation so that the socket handler comes first

* net: add CThreadInterrupt and InterruptibleSleep

* net: make net interruptible

Also now that net threads are interruptible, switch them to use std
threads/binds/mutexes/condvars.

* net: make net processing interruptible

* net: remove thread_interrupted catch

This is now a std::thread, so there's no hope of catching a boost interruption
point.

* net: make proxy receives interruptible

* net: misc header cleanups
2017-08-09 19:06:31 +03:00
Oleg Girko
df6d458b85 Backport Bitcoin PR#9260: Mrs Peacock in The Library with The Candlestick (killed main.{h,cpp}) (#1566)
* Remove orphan state wipe from UnloadBlockIndex.

As orphan state is now "network state", like in
d6ea737be1,

UnloadBlockIndex is only used during init if we end up reindexing
to clear our block state so that we can start over. However, at
that time no connections have been brought up as CConnman hasn't
been started yet, so all of the network processing state logic is
empty when its called.

* Move network-msg-processing code out of main to its own file

* Rename the remaining main.{h,cpp} to validation.{h,cpp}
2017-08-09 03:19:06 +03:00