Commit Graph

323 Commits

Author SHA1 Message Date
Aaron Campbell
8be96a8729 multi: Correct typos.
Correct typos found by reading code, ispell, and creative grepping.
2019-08-22 10:20:03 -05:00
Dave Collins
665ab37c68
gcs: Standardize serialization on a single format.
Currently, the filters provide two different serialization formats per
version.  The first is the raw filter bytes without the number of items
in its data set and is implemented by the Bytes and FromBytesV1
functions.  The second includes that information and is implemented by
the NBytes and FromNBytesV1 functions.

In practice, the ability to serialize the filter independently from the
number of items in its data set is not very useful since that
information is required to be able to query the filter and, unlike the
other parameters which are fixed (e.g. false positive rate and key), the
number of items varies per filter.  For this reason, all usage in
practice calls NBytes and FromNBytesV1.

Consequently, this simplifies the API for working with filters by
standardizing on a single serialization format per filter version which
includes the number of items in its data set.

In order to accomplish this, the current Bytes and FromBytesV1 functions
are removed and the NBytes and FromNBytesV1 functions are renamed to
take their place.

This also updates all tests and callers in the repo accordingly.
2019-08-22 09:50:29 -05:00
Dave Collins
90d2deb420
gcs: Add filter version support.
This refactors the primary gcs filter logic into an internal struct with
a version parameter in in order to pave the way for supporting v2
filters which will have a different serialization that makes them
incompatible with v1 filters while still retaining the ability to work
with v1 filters in the interim.

The exported type is renamed to FilterV1 and the new internal struct is
embedded so its methods are externally available.

The tests and all callers in the repo have been updated accordingly.
2019-08-20 23:43:23 -05:00
Dave Collins
feb4ff55e0
gcs: Start v2 module dev cycle.
This removes the unused and undesired FromPBytes and FromNPBytes
functions and associated tests from the gcs module in preparation for
upcoming changes aimed to support new version filters for use
in header commitments.

Since these changes, and several planned upcoming ones, constitute
breaking pubic API changes, this bumps the major version of the gcs
module, adds a replacement for gcs/v2 to the main module and updates all
other modules to make use of it.

It also bumps the rpcclient module to v5 since it makes use of the
gcs.Filter type in its API, adds a replacement for rpcclient/v5 to the
main module and updates all other modules to make use of it.

Note that this also marks the start of a new approach towards handling
module versioning between release cycles to reduce the maintenance
burden.

The new approach is as follows.

Whenever a new breaking change to a module's API is introduced, the
following will happen:

- Bump the major version in the go.mod of the affected module if not
  already done since the last release tag
- Add a replacement to the go.mod in the main module if not already
  done since the last release tag
- Update all imports in the repo to use the new major version as
  necessary
  - Make necessary modifications to allow all other modules to use the
    new version in the same commit
- Repeat the process for any other modules the require a new major as a
  result of consuming the new major(s)

Finally, once the repo is frozen for software release, all modules will
be tagged in dependency order to stabilize them and all module
replacements will be removed in order to ensure releases are only using
fully tagged and released code.
2019-08-20 09:07:07 -05:00
Aaron Campbell
03678bb754 multi: Correct typos.
Correct typos found by reading code and creative grepping.
2019-08-16 17:37:58 -05:00
Donald Adu-Poku
77a14a9ead multi: add automatic network address discovery.
This discovers the network address(es) of the daemon
through connected outbound peers. The address(es)
discovered are advertised to subsequent connecting peers.
2019-08-14 06:53:10 -05:00
Dave Collins
25c14e046a
main: Update to use all new major module versions.
This updates all code in the main module to use the latest major modules
versions to pull in the latest updates.

A more general high level overview of the changes is provided below,
however, there is one semantic change worth calling out independently.

The verifymessage RPC will now return an error when provided with
an address that is not for the current active network and the RPC server
version has been bumped accordingly.

Previously, it would return false which indicated the signature is
invalid, even when the provided signature was actually valid for the
other network.  Said behavior was not really incorrect since the
address, signature, and message combination is in fact invalid for the
current active network, however, that result could be somewhat
misleading since a false result could easily be interpreted to mean the
signature is actually invalid altogether which is distinct from the case
of the address being for a different network.  Therefore, it is
preferable to explicitly return an error in the case of an address on
the wrong network to cleanly separate these cases.

The following is a high level overview of the changes:

- Replace all calls to removed blockchain merkle root, pow, subsidy, and
  coinbase funcs with their standalone module equivalents
  - Introduce a new local func named calcTxTreeMerkleRoot that accepts
    dcrutil.Tx as before and defers to the new standalone func
- Update block locator handling to match the new signature required by
  the peer/v2 module
  - Introduce a new local func named chainBlockLocatorToHashes which
    performs the necessary conversion
- Update all references to old v1 chaincfg params global instances to
  use the new v2 functions
- Modify all cases that parse addresses to provide the now required
  current network params
  - Include address params with the wsClientFilter
- Replace removed v1 chaincfg constants with local constants
- Create subsidy cache during server init and pass it to the relevant
  subsystems
  - blockManagerConfig
  - BlkTmplGenerator
  - rpcServer
  - VotingWallet
- Update mining code that creates the block one coinbase transaction to
  create the output scripts as defined in the v2 params
- Replace old v2 dcrjson constant references with new types module
- Fix various comment typos
- Update fees module to use the latest major module versions and bump it v2
2019-08-13 11:22:37 -05:00
Donald Adu-Poku
6968dcfdbd multi: decouple BlockManager from server.
This adds a blockManager config and removes direct references
to the server from the blockManager.
2019-06-25 19:05:47 +00:00
Dave Collins
826d66bb56
mining: Overhaul background template generator.
Currently, block templates that provide work to PoW miners are generated
in response to them calling the getwork RPC.  However, unlike in a pure
PoW system, in Decred, when a new block is connected, a new block
template extending that block can't be generated until the minimum
number of required votes for it has been received.  This poses a
challenge for PoW miners because they are typically unaware of when
votes are received.  Consequently, miners poll getwork waiting until
they see a new template generated when a new block is connected.

Since only a minimum of 3 votes is required to build a template and new
templates are only generated in response to the miners calling getwork,
as just described, miners often, unfortunately, end up receiving a
template that only has 3 votes and begin working on it.  Worse, since
many new miners are not well versed in the intricacies of Decred voting,
they often aren't aware they really need to continue polling for new
votes and immediately switch over to the new template with more votes in
it in order to avoid receiving a reduced subsidy.  This often results in
new miners producing blocks with 3 votes.

Moreover, blocks with less than all 5 votes are not only undesirable for
the PoW miners because they receive reduced subsidy, they're also
undesirable for PoS stakers since it means the votes that were not
included don't receive the reward despite having voted simply due to a
propagation delay.

Another issue with the existing approach is that since it takes a bit of
time to generate and validate templates, particularly as the number of
transactions they include rises, miners periodically requesting updated
work to include the latest transactions have to wait for the template to
be built when they call getwork once the existing cached template is
expired.  This can result in undesirable delays for them.

In order to address the need to wait for templates to be built in that
case, there was recently some preliminary work that implemented a
background template generator which asynchronously generates templates
in response to events with the intention of allowing access to the
latest one without said random delays in the future.

However, that preliminary work did not address the issues around vote
propagation such as the tendency for miners to end up with the first
block template only containing the 3 fastest-propagating votes, nor did
it have robust handling for all potential corner cases and error
conditions.

Consequently, this overhauls the background block template generator to
add support for intelligent vote propagation handling, handle chain
reorganization to alternative blocks in the case the current tip is
unable to obtain enough votes, provide a subscription for a stream of
template updates, handle template generation errors, consider the
synchronization state as a part of determining if the chain is current,
track the reason for template updates, block current template retrieval
during operations that are in the process of making it stale, and
correct several corner cases.

It should be noted that this only implements the infrastructure and does
not switch getwork or the CPU miner over to use the background templates
yet.  This will be done in future commits.

The following is a high-level overview of the semantics this implements:

- Generate new templates immediately when prior to stake validation
  height since no votes are required
- Do not generate templates for intermediate blocks during a chain
  reorganization
- Do not generate templates before the chain is considered synchronized
- Prefer to create templates with maximum votes through the use of a
  timeout once the minimum votes have been received to provide the votes
  an opportunity to propagate with a fallback for immediate generation
  as soon as all votes are received
  - In the case the timeout expires and a template is created with less
    than the maximum number of votes, generate a new template
    immediately upon receiving more votes for the block it extends
- In the event there are competing blocks at the current tip, prefer to
  build a template on the first seen block so long as it receives the
  minimum number of required votes within a few seconds
- Generate new templates immediately when a block is disconnected to
  support future planned chain invalidation capabilities
- Generate new templates periodically when there are new regular transactions
  to include
- Schedule retries in the rare event template generation fails
- Allow clients to subscribe for updates every time a new template is
  successfully generated along with a reason why it was generated
- Provide direct access to the most-recently generated template
  - Block while generating new templates that will make the current template
    stale (e.g. new parent or new votes)

The following is a high-level overview of the changes:

- Initialize PRNG once instead of at every invocation
- Implement an asynchronous queue for all events to ensure normal chain
  and vote processing is not blocked
- Provide ability to subscribe for all template updates over a single
  channel to ensure none can indadvertently be missed as is possible with
  the current design
  - Always deliver existing template upon registration
  - Drop templates if the receiver falls too far behind in the same way
    tickers work
- Introduce tracking the reason for template updates so that it can
  ultimately be presented to miners to allow them to make better
  decisions about when to force their workers to switch
- Consider the current network sync state when checking if the chain is
  current
- Introduce a regen handler state such as timeouts, blocks to monitor
  for votes, and the block the next template should extend
- Add logic for selectively reacting to votes on the block the current
  template is extending, the current tip, and alternate competing blocks
  at the current tip using the aforementioned semantics
- Perform all template generation in separate goroutines with a
  cancellable context
  - Cancel any in progress templates that are being generated whenever
    generating a new one
- Introduce blocking current template retrieval when a new template that
  would cause the existing one to become stale is being generated
- Modify periodic regen handling to use a resettable timer for better
  efficiency and more fine grained control
- Remove template pool as that is something that should be handled by
  the code that is actually handing the templates out
- Rename and export the event notification funcs to make it clear
  they're not internal functions and also make it easier to eventually
  move the code into the mining package
- Expand and improve comments
- Store and return template generation errors
  - Schedule retry in the case of failure
- Correct several cases that were not being handled correctly and some
  undesirable behaviors such as block disconnects (as opposed to
  reorgs), reorganization to side chains, and notifying with stale
  templates
2019-06-23 00:45:51 -05:00
Dave Collins
1dd1dd7359
miner: Improve background generator lifecycle.
This modifies the lifecycle of the background generator to use the
expected pattern for running subsystems based on contexts in the future.

In particular, this renames the Start function to Run and arranges for
it to block until the provided context is cancelled.  This is more
flexible for the caller since it can easily turn blocking code into
async code while the reverse is not true.

Next, the server is modified to ensure it waits for the background
template generator to shutdown before shutting down itself to help
ensure an orderly shutdown.

While here, it also makes the various lifecycle debug messages more
consistent with the rest of the code base.
2019-04-02 11:51:12 -05:00
Dave Collins
b39c637145
server: Remove unused dynamicTickDuration func. 2019-04-01 12:49:38 -05:00
Dave Collins
20caedc344
server: Remove unused ScheduleShutdown func. 2019-04-01 12:49:34 -05:00
Donald Adu-Poku
8f5019e083 multi: add BgBlkTmplGenerator.
BgBlkTmplGenerator represents the background process that
generates block templates and notifies all subscribed clients
on template regeneration. It generates new templates based
on mempool activity for vote and non-vote transactions and
the time elapsed since last template regeneration.

This also adds a template pool to the background block
generator for recreating submitted blocks.
2019-03-30 16:08:43 -05:00
David Hill
99cc7266b6 server: limit getminingstate requests 2019-03-29 01:11:27 -05:00
David Hill
b72b6ca714 server: return on outbound peer creation error 2019-03-28 21:10:43 -05:00
David Hill
06e03bed9f blockmanager: use local var for the request queue
Instead of waiting for a second inv to process what the first inv
may have requested, just send it all at once.  This allows dropping
of a request queue for each server peer.
2019-03-28 21:10:12 -05:00
Dave Collins
0173adf9a4
server: Use lru cache module for addresses.
This updates the server known address cache to make use of the new
generic LRU cache provided by the lru module.
2019-03-18 10:08:51 -05:00
David Hill
a9c87c67cb fees: drop unused chaincfg 2019-03-17 15:16:14 -05:00
Dave Collins
f1c519a8e5
server: Update for deprecated peer chaincfg.
This updates peer.Config in the server to set the new Net parameter
instead of the now deprecated ChainParams parameter.
2019-03-16 21:11:02 -05:00
Matheus Degiovani
6628e8d02d server: Remove instead of disconnect node
This changes the behavior of peer disconnection logic, such that
permanent peers are actually removed from the connection manager when
requested, instead of just being disconnected and therefore triggering a
future retry.

Previously, this prevented the addnode [addr] remove from correctly
removing permanent peers. A connection retry attempt would always be
performed.
2019-03-07 19:34:35 -06:00
Dave Collins
fc4d68a327
main: Update for mempool/v2.
This updates the main module to use version 2 of the mempool module.

The following is a summary of changes:

- Update all imports to use mempool/v2
- Update module requirements to include new module and remove no longer
  needed old versions
- Add an override for the v2 module so CI is always builds with the
  latest code
- Update rpcserver getrawmempool to make use of new mempool
  VerboseTxDescs instead of the removed RawMempoolVerbose
- Update rpcserver getrawmempool to properly return the parameter
  provided for the transaction type instead of the type of variable in
  the case an invalid type is provided
- Update rpcserver getrawmempool to return the supported transaction
  types in the error when an invalid type is provided
2019-02-14 19:59:22 -06:00
Dave Collins
4e8dc457e1
multi: Enable vote for DCP0004.
This implements the agenda for voting on the sequence lock fixes as
defined in DCP0004 along with consensus tests and mempool acceptance
tests to ensure its correctness.

It also modifies the mempool to conditionally treat all transactions
with enabled sequence locks as non standard until the vote passes at
which point the will become standard with the modified semantics
enforced.

The following is an overview of the changes:

- Generate new version blocks and reject old version blocks after a
  super majority has been reached
  - New block version on mainnet is version 6
  - New block version on testnet is version 7
- Introduce a convenience function for determining if the vote passed
  and is now active
- Enforce modified sequence lock semantics in accordance with the state
  of the vote
- Modify the more strict standardness checks (acceptance to the mempool
  and relay) to enforce DCP0004 in accordance with the state of the vote
  - Make all transactions with enabled sequence locks non standard until
    the agenda vote passes
  - Add tests to ensure acceptance and relay behave according to the
    aforementioned description
- Add tests for determining if the agenda is active for both mainnet and
  testnet
- Add tests to ensure the corrected sequence locks are handled properly
  depending on the result of the vote
2019-01-28 09:29:25 -06:00
David Hill
f27ac9ff4d multi: switch to golangci-lint.
multi: Switch to golangci-lint.
2019-01-24 00:12:31 -06:00
Matheus Degiovani
300b6848c9
multi: Integrate fee estimation
This commit performs the necessary modifications to hook the fee
estimation facility added by the previous commit into the node software.

The block manager is modified to notify the estimator of all new blocks,
such that their transactions can be accounted for, and the mempool is
modified to relay transactions entering and leaving it, so that those
transactions can be tracked.

The results of the estimator can be queried by issuing estimatesmartfee
rpc commands to the node.
2018-12-06 19:41:52 -02:00
David Hill
653b7c5e6b [config]: add --maxsameip to limit # of conns to same IP 2018-11-15 12:34:31 -05:00
Dave Collins
df1898cead
blockchain: Reverse utxo set semantics.
This modifies the way the unspent transaction output set is handled to
reverse its current semantics so that it is optimized for the typical
case, provides simpler handling, and resolves various issues with the
previous approach.  In addition, it updates the transaction, address,
and existsaddress indexes to no longer remove entries from blocks that
have been disapproved as, in all cases, the data still exists in the
blockchain and thus should be queryable via the indexes even though
there is special handling applied which treats them as if they did not
exist in certain regards.

Prior to this change, transactions in the regular tree were not applied
to the utxo set until the next block was processed and did not vote
against them.  However, that approach has several undesirable
consequences such as temporarily "invisible" utxos that are actually
spendable, disapproved transactions missing from indexes even though
they are still in the blockchain, and poor performance characteristics.

In a certain sense, the previous approach could be viewed as the
transactions not being valid until they were approved, however, that is
not really true because it was (and still is) perfectly acceptable to
spend utxos created by transactions in the regular tree of the same
block so long as they come before the transactions that spend them.
Further, utxos from a transaction in the regular tree of a block can be
spent in the next block so long as that block does not disapprove them,
which further illustrates that the utxos are actually valid unless they
are disapproved.

Consequently, this modifies that behavior to instead make the utxo set
always track the most recent block and remove the regular transactions
in the parent when a block votes against them.  This approach is
significantly more efficient for the normal case where the previous
block is not disapproved by its successor.

Also, the terminology is changed in several places to refer to
disapproved blocks and transaction trees as opposed to invalid, because
invalid implies the tree/block is malformed or does not follow the
consensus rules.  On the contrary, when a block votes against its
parent, it is only voting against regular transaction tree of the
parent.  Both the block and transaction tree are still valid in that
case, only the regular transaction tree is treated as if it never
existed in terms of effects on the utxo set and duplicate transaction
semantics.

High level overview of changes:
- Modify the utxo viewpoint to reverse semantics as previously described
  - Remove all code related to stake viewpoints
  - Change all block connection code in the viewpoint to first undo all
    transactions in the regular tree of the parent block if the current
    one disapproves it then connect all of the stake txns followed by
    the regular transactions in the block
    - NOTE: The order here is important since stake transactions are not
      allowed to spend outputs from the regular transactions in the same
      block as the next block might disapprove them
  - Change all block disconnection code in the viewpoint to first undo
    all the transactions in the regular and stake trees of the block
    being disconnected, and then resurrect the regular transactions in
    the parent block if the block being disconnected disapproved of it
  - Introduce a new type named viewFilteredSet for handling sets
    filtered by transactions that already exist in a view
  - Introduce a function on the viewpoint for specifically fetching the
    inputs to the regular transactions
  - Update mempool block connection and disconnection code to match the
    new semantics
  - Update all tests to handle the new semantics
- Modify the best state number of transactions to include all
  transactions in all blocks regardless of disapproval because they
  still had to be processed and still exist in the blockchain
- Remove include recent block parameter from mempool.FetchTransaction
  since the utxoset now always includes the latest block
  - This also has the side effect of correcting some unexpected results
    such as coinbases in the most recent block being incorrectly
    reported as having zero confirmations
- Modify mempool utxo fetch logic to use a cached disapproved view, when
  needed, rather than recreating the view for every new transaction
  added to it
- Update spend journal to include all transactions in the block instead
  of only stake transactions from the current block and regular
  transactions from the parent block
- Modify tx and address indexes to store the block index of each tx
  along with its location within the files and update the query
  functions to return the information as well
- Change the tx, address, and existsaddress indexes to index all
  transactions regardless of their disapproval
  - This also corrects several issues such as the inability to query and
    retrieve transactions that exist in a disapproved block
- Update all RPC commands that return verbose transaction information
  to set that newly available block index information properly
- Rename IsRegTxTreeKnownDisapproved in the mining.TxSource interface to
  IsRegTxTreeKnownDisapproved
  - NOTE: This will require a major bump to the mining module before
    the next release
- Rename several utxoView instances to view for consistency
- Rename several variables that dealt with disapproved trees from
  names that contained Invalid to ones that contain Disapproved

NOTE: This does not yet have database migration code and thus will
require a full chain download.  It will exit with error in the case you
attempt to run it against an existing v4 database.  The new database it
creates will be v5, so attempting to run an older version will reject
the new database to prevent corruption.

The database migration will be added in a separate commit.
2018-11-09 17:23:46 -06:00
Dave Collins
f34dde5328
server: Always allow whitelisted inbound peers.
This modifies the code which enforces a maximum number of peers to
always allow whitelisted inbound peers even when they would exceed the
maximum number of peers to ensure that operators can always allow their
own clients.
2018-11-06 15:17:45 -06:00
Donald Adu-Poku
88ca6f5525 multi: add cpuminerConfig.
Port of upstream commit 6719014.
2018-09-13 12:24:42 -05:00
Donald Adu-Poku
e8e9f90c26 multi: add BlkTmplGenerator.
Port of upstream commit 74fe2a4. In preparation of moving all
mining related code into the mining package.
2018-09-12 17:18:44 +00:00
Donald Adu-Poku
c0b0b6c2bb multi: remove chainState deps in server & cpuminer.
Port of upstream commit 2274d36 (subset). In preparation of the
removal of chainState.
2018-09-12 15:28:45 +00:00
Dave Collins
a3b09ccda2
server: Add infrastruct for immediate inv relay.
This modifies the infrastructure for the server inventory relay to allow
the caller to specify the inventory should be announced immediately
versus using the typical trickle mechanism.

It also updates all callers in the repository and changes the relay of
accepted blocks use the new ability.
2018-09-10 09:57:52 -05:00
Dave Collins
999ee7d863
multi: Make use of new internal version package.
This introduces a new internal package named version to house the
version information and updates the various code to use it.  This allows
both dcrd and dcrctl to make use of the package so the version
information only needs to be bumped in one place and also ensure that
any link-time overrides to the pre-release and/or build metadata apply
to both.

Also, while here, include the OS and architecture in the version log at
start of day as well as the output from the version CLI flag.
2018-09-04 17:34:31 -05:00
Dave Collins
97a8f5f34c
peer: Add support for specifying ua comments.
This adds a new parameter named UserAgentComments to the peer Config
struct so that callers may specify additional comments to add to the
user agent string.

It also updates the server to include the prelease portion of the
semantic version as a comment when creating peers.
2018-08-21 13:44:01 -05:00
Donald Adu-Poku
9b08b582d7 multi: add specialized rebroadcast handling for stake txs. 2018-07-05 23:20:00 -05:00
Dave Collins
90adb7ceee
blockchain: Combine block by hash functions.
This modifies the BlockByHash function to return blocks regardless of
whether or not the block is on a side chain and removes the
FetchBlockByHash function since this change makes it redundant.

This is being changed to simplify the API and because there are no
current cases where calls into chain to retrieve a block need to be
limited to the main chain and if the need should ever arise, the caller
can simply make use of the MainChainHasBlock function to verify.
2018-07-02 14:25:30 -05:00
David Hill
2f5e473712 server: only call time.Now() once
When a peer sends an addr message, use the same time for each
address sent.  This saves up to wire.MaxAddrPerMsg-1 syscalls.
2018-06-26 19:13:31 -05:00
Josh Rickmar
37fcf957dd server: Always reply to getheaders with headers
This reverts a change made in 4f6ed9afdb
which resulted in a headers response to not be created for a
getheaders request if there were no more discovered headers.  This was
a deviation from the previous behavior of queueing a headers message
with an empty vector of headers.

This was a protocol change without a protocol bump, so the behavior
must be reverted.

I also cross referenced the Bitcoin Core source code and, just like
the now-restored behavior, headers messages were always sent even when
no new headers were discovered.  I don't see any reason why Decred
should deviate from this behavior.
2018-06-13 16:49:32 -05:00
Dave Collins
53ec802091
server: Convert CF code to use new inv discovery.
This modifies the getcfheaders handling code to use the recently
refactored block locator code that is now available in blockchain
instead of manually performing the task.

Not only is the code in chain more efficient, it also helps ensure the
handling for block locators is consistent.

While here, it also modifies a few cfilter-related comments for
consistency and corrects a near bug which was limiting the response to
the maximum allowed block headers per message as opposed to maximum
allowed cfilter headers per message.  Since the two constants are
currently the same value, this is no functional change in this regard.
2018-06-12 13:22:59 -05:00
Dave Collins
ffabd89988
server: Minor function definition order cleanup.
This moves the function definition for enforceNodeCFFlag so it are more
consistent with the preferred order used throughout the codebase.  In
particular, the functions are defined before they're first used and
generally as close as possible to the first use when they're defined in
the same file.

While moving, it also reformats the code to match the same spacing as
the other CF functions for consistency.

There are no functional changes.
2018-06-12 13:08:23 -05:00
Dave Collins
b5de14847c
server: Correct comment in getblocks handler. 2018-06-07 16:24:40 -05:00
Dave Collins
750f274202
server: Use local addr var in version handler.
This modifies the OnVersion handler for server peers to use a local
variable for the remote address of the peer in order to avoid grabbing
the mutex multiple times.

There are no functional changes.
2018-06-05 11:02:29 -05:00
Dave Collins
c806163ffa
server: Only advertise local addr when current.
This changes the server peers OnVersion handler to only advertise the
server as a viable target for inbound connections when the server
believes it is close the best known tip.
2018-06-05 10:41:50 -05:00
Dave Collins
8883a7cbae
server: Use local inbound var in version handler.
This modifies the OnVersion handler for server peers to use a local
variable for the inbound status of the peer in order to avoid grabbing
the mutex multiple times.

While here, it also does some light cleanup.  There are no functional
changes.
2018-06-05 10:33:34 -05:00
Dave Collins
c0e114d837
server: Update addrmgr services on outbound conns.
This adds code to update the address manager services for a known
address to the services advertised by peers when they are connected to
via an outbound connection.  It is only done for outbound connections to
help prevent malicious behavior from inbound connections.
2018-06-04 18:40:47 -05:00
Dave Collins
166c71efc3
server: Reject outbound conns to non-full nodes.
This modifies the server connection code to reject outbound peers that
do not offer full node services.
2018-06-04 17:56:13 -05:00
Dave Collins
9adc12e26f
peer: Allow OnVersion callback to reject peer.
This modifies the OnVersion callback to allow a reject message to be
returned in which case the message will be sent to the peer and the peer
will be disconnected.
2018-06-04 15:59:31 -05:00
Dave Collins
774139283b
peer: Rework version negotiation.
This modifies the negotiation logic to ensure the callback has the
opportunity to see the message before the peer is disconnected and
improves the error handling when reading the remote version message.

It also has the side effect of ensuring the protocol version is
negotiated before sending reject messages with the exception of the
first message not being a version message since negotiation is not
possible in that case.

This is being changed because it is useful for the server to see the
message regardless in order to have the opportunity to things such as
update the address manager and reject peers that don't have desired
services.
2018-06-04 15:35:54 -05:00
Dave Collins
5f3a1506b4
server: Only respond to getaddr once per conn.
This modifies the OnGetAddr handler to prevent the server from
responding to getaddr messages more than once per connection which helps
reduce unhelpful traffic and fingerprinting attacks.
2018-06-04 15:24:25 -05:00
Dave Collins
4f6ed9afdb
multi: Refactor and optimize inv discovery.
This refactors the code that locates blocks (inventory discovery) out of
server and into blockchain where it can make use of the fact that all
block nodes are now in memory and more easily be tested.  As an aside,
it really belongs in blockchain anyways since it's purely dealing with
the block index and best chain.

In order to do this reasonably efficiently, a new memory-only height
to block node mapping for the main chain is introduced to allow
efficient forward traversal of the main chain.  This is ultimately
intended to be replaced by a chain view.

Since the network will be moving to header-based semantics, this also
provides an additional optimization to allow headers to be located
directly versus needing to first discover the hashes and then fetch the
headers.

The new functions are named LocateBlocks and LocateHeaders. The former
returns a slice of located hashes and the latter returns a slice of
located headers.

Finally, it also updates the RPC server getheaders call and related
plumbing to use the new LocateHeaders function.

A comprehensive suite of tests is provided to ensure both functions
behave correctly for both correct and incorrect block locators.
2018-06-01 13:20:04 -05:00
David Hill
5a4f367b66 multi: Remove everything to do about bloom filters. 2018-05-01 11:43:32 -05:00