Commit Graph

231 Commits

Author SHA1 Message Date
Dave Collins
1a62f72f40
blockchain/indexers: Allow interrupts.
This propagates the interrupt channel through to blockchain and the
indexers so that it is possible to interrupt long-running operations
such as catching up indexes.
2018-02-18 11:18:52 -06:00
David Hill
e45c34fbfc multi: release the mutex earlier 2018-02-13 13:55:02 -06:00
Dave Collins
20a8ccc27b
blockchain: Use hash values in structs.
This modifies the BestState struct in the blockchain package to store
hashes directly instead of pointers to them and updates callers to deal
with the API change in the exported BestState struct.

In general, the preferred approach for hashes moving forward is to store
hash values in complex data structures, particularly those that will be
used for cache entries, and accept pointers to hashes in arguments to
functions.

Some of the reasoning behind making this change is:

- It is generally preferred to avoid storing pointers to data in cache
  objects since doing so can easily lead to storing interior pointers into
  other structs that then can't be GC'd
- Keeping the hash values directly in the structs provides better
  cache locality
2018-01-30 13:37:26 -06:00
Dave Collins
4d20cc1217
stake/multi: Don't return errors for IsX functions.
This modifies the IsSStx, IsSSGen, and IsSSRtx functions to only return
a bool and introduces CheckSStx, CheckSSGen, and CheckSSRtx to return
the actual error as needed by consensus.

This is being done because "is" functions are much nicer to use when
they don't return an error and the callers that use them almost never
care why they aren't of the type, they just want to determine if they
are.  In the few cases where the caller does care, they can use of the
new check functions.

While here, also update the comments to call out what the more common
names for the transaction types are and to add comments to the test
functions for consistency.

Finally, it updates all callers in the repo accordingly.
2018-01-30 10:20:12 -06:00
Matheus Degiovani
735d1e48db blockchain: Switch to FindSpentTicketsInBlock.
This adds a new function FindSpentTicketsInBlock that extracts all spent and
revoked tickets, plus the vote bits of a given block and uses that function
instead of the individual functions when loading a new node into the blockchain.

This improves startup time a bit, as the isSSGen, isSSRtx and determineTxType
are somewhat slow, as they need to decode the output script of the transactions.
Looping over the transactions once and doing a single test is faster.

Numbers for my computer:
```
| variation     | mainnet | testnet |
| with patch    |   23.7s |   42.6s |
| without patch |   35.9s |  118.0s |
```
2018-01-28 21:21:10 -06:00
Donald Adu-Poku
05c90ddfc8 blockmanager: sync with the most updated peer. 2018-01-28 03:14:48 -06:00
David Hill
fc31a0b39e multi: remove unused funcs and vars 2017-12-07 21:46:25 -06:00
David Hill
20686cd775 travis: add gosimple linter 2017-11-20 18:49:55 -06:00
Josh Rickmar
6842aa006d Merge remaining dcrutil code into a dcrd package.
This merge commit adds the following code from the
github.com/decred/dcrutil package into a new
github.com/decred/dcrd/dcrutil package:

* Address handling
* Amount type
* AppDataDir func
* bitflags functions
* Block wrapper type
* Hash160 func
* Tx wrapper type
* WIF type

as well as all tests for this code.

The old github.com/decred/dcrutil/hdkeychain package has also been
merged and moved to github.com/decred/dcrd/dcrutil/hdkeychain.

dcrd packages have been updated to use the new packages and the dep
files have been updated for this change.
2017-10-11 22:06:36 -04:00
David Hill
6f7ef0421b blockmanager: remove unused logBlockHeight 2017-08-03 15:37:26 -04:00
Dave Collins
fbbe728139
blockchain: Remove exported CalcPastTimeMedian func.
Upstream commit 1cba5c8fc0.
2017-07-27 13:05:55 -05:00
David Hill
21df6b7664 mining: call CheckConnectBlock directly. 2017-07-24 13:03:24 -04:00
David Hill
6c16fe19c2 blockmanager: remove unused GetBlockFromHash function. 2017-07-24 12:55:27 -04:00
David Hill
a9234850e7 remove deadcode 2017-07-17 15:06:47 -05:00
David Hill
2ffbad1e88 chainstate only needs the previous block hash
... not the entire block header.
2017-06-21 12:13:30 -04:00
David Hill
3428a4011f adjust for dcrutil Block changes. (#700) 2017-05-18 16:42:56 -04:00
jolan
a60c70e1c2 blockmanager: Fix new tickets notification. (#694) 2017-05-09 15:57:59 -05:00
Dave Collins
734684d288
multi: Implement stake difficulty change and vote.
This implements a new stake difficulty algorithm along with a voting
agenda for all networks to change and a comprehensive set of tests.  It
also implements estimation using the new algorithm for the
estimatestakediff RPC.

The following is an overview of the changes:

- Add new agenda to vote on changing the stake difficulty algorithm to
  all networks
  - The version on mainnet is version 4
  - The version on testnet and simnet is version 5
- Modifies the stake difficulty calculation function to calculate the
  difficulty based on the result of the vote
- Modifies the stake difficulty estimation function to calculate the
  difficulty based on the result of the vote
- Makes the stake difficulty estimation function concurrent safe
  - Calls it directly from the RPC server instead of going through block
    manager
  - Removes no longer needed code from the block manager
- Generate new version blocks and reject old version blocks after a
  super majority has been reached
  - New block version on mainnet is version 4
  - New block version on testnet and simnet is version 5
- Add tests for the supply estimation used in the new algorithm
- Add tests for the new algorithm calculations
- Add tests for the estimation based on the new algorithm
2017-04-26 13:00:28 -05:00
David Hill
caa57df468 travis: enable gometalinter (#603)
* Hook up gometalinter

* travis: enable unconvert

* travis: enable gosimple
2017-03-08 15:44:15 -05:00
Dave Collins
e9acb1d35b
mempool: Refactor mempool code to its own package.
Upstream commit 7fac099bee.

Also, the merge commit contains the necessary decred-specific
alterations, adds a new policy parameter for AllowOldVotes to keep with
the spirit of the merged commit, modifies the RawMempoolVerbose to
accept an optional filter type to retain that functionality, and various
other cleanup intended to bring the code bases more in line with one
another.
2016-11-29 15:32:22 -06:00
Dave Collins
c162fbde71
multi: Upstream chainhash abstraction sync
Contains the following commits:

- 711f33450c
- b6b1e55d1e
  - Reverted because Travis is already at a more recent version
- bd4e64d1d4

Also, the merge commit contains the necessary decred-specific
alterations, converts all other references to sha to hash to keep with
the spirit of the merged commits, and various other cleanup intended to
bring the code bases more in line with one another.
2016-11-16 12:48:40 -06:00
Dave Collins
748ecb2a52
blockchain: Associate time src with chain instance.
Upstream commit 00ebb9d14d

Also, the merge commit contains the necessary decred-specific
alterations.
2016-11-11 18:06:09 -06:00
Marco Peereboom
2d242b224e Add StakeVersion bits to various subsystems. (#441)
Bump block version and add stake version to wire.  Currently
StakeVersions are unused and once the enforcement logic goes in the
versions will bump again.

This fixes #435
2016-11-07 13:06:17 -06:00
Dave Collins
1cba5c8fc0
blockchain: Remove exported CalcPastTimeMedian func.
This removes the exported CalcPastTimeMedian function from the
blockchain package as it is no longer needed since the information is
now available via the BestState snapshot.

Also, update the only known caller of this, which is the chain state in
block manager, to use the snapshot instead.  In reality, now that
everything the block manager chain state provides is available via the
blockchain BestState snapshot, the entire thing can be removed, however
that will be done in a separate to commit to keep the changes targeted.
2016-10-17 10:41:25 -05:00
Dave Collins
77913ad2e8
blockchain: Expose main chain flag on ProcessBlock.
This modifies the blockchain.ProcessBlock function to return an
additional boolean as the first parameter which indicates whether or not
the block ended up on the main chain.

This is primarily useful for upcoming test code that needs to be able to
tell the difference between a block accepted to a side chain and a block
that either extends the main chain or causes a reorganize that causes it
to become the main chain.  However, it is also useful for the addblock
utility since it allows a better error in the case a file with out of
order blocks is provided.
2016-10-13 16:47:50 -05:00
Josh Rickmar
d58299b059 Replace some unnecessary dcrutil.Tx usage with wire.MsgTx. (#419) 2016-10-12 13:57:47 -04:00
C Jepson
393c48d32e Fix the dumpblockchain function (#405)
The dumpblockchain function used to serialize a map of block
into gob serialized format, which was used for testing but which
was incompatible with the addblock tool.  The function now dumps
a flat file the the same format required by the addblock tool.

A couple shutdown assertions were added as well, to prevent
potential panics if pointers were nil.  The duration of time
it took to sync the blockchain with addblock is now
reported.
2016-10-10 11:35:46 -05:00
C Jepson
8037faca0e Fix a bug for forced reorganizations (#392)
A bug when updating the chain state during forced reorganizations
was fixed. An assertion was added into the mining code so that it
now errors out if the blockchain and chainState of the block
manager are inconsistent.

The blockchain function to fetch the latest block header was
renamed for consistency and now returns a copy of the block header
instead of the pointer itself.
2016-10-05 11:20:42 -05:00
C Jepson
d98fc8319f Replace the ticket database with an efficient, atomic implementation
The legacy ticket database, which was GOB serialized and stored on
shut down, has been removed.  Ticket state information is now held in
a stake node, which acts as a modularized "black box" to contain all
information about the state of the stake system.  Stake nodes are now
a component of the blockchain blockNode struct, and are updated with
them.

Stake nodes, like their internal treap primitives, are immutable
objects that are created with their connect and disconnect node
functions.  The blockchain database now stores all information about
the stake state of the best node in the block database.  The blockchain
makes the assumption that the stake state of the best node is known at
any given time.  If the states of former blocks or sidechains must be
evaluated, this can be achieved by iterating backwards along the
blockchain from the best node, and then connecting stake nodes
iteratively if necessary.

Performance improvements with this new module are dramatic.  The long
delays on start up and shut down are removed.  Blockchain
synchronization time is improved approximately 5-10x on the mainnet
chain.  The state of the database is atomic, so unexpected shut downs
should no longer have the ability to disrupt the chain state.

An upgrade path has been added for version 1 blockchain databases.
Users with this blockchain database will automatically update when
they start their clients.
2016-10-04 13:40:19 -04:00
cjepson
f0ac3dba9c Merge in btcd commit '1b234102147901738bb79b2edf2d803225a36d57'
Merges in btcd commit 1b23410214.
2016-09-23 14:02:00 -04:00
C Jepson
16f6dab402 Fix a bug with invalidating blocks in new DB and add more sanity checks (#343)
A bug prevented STXO data from being written correctly in the event
that a block became invalidated. This could cause failures on testnet
when a block was invalidated. There was also some debug code and a panic
that were in master that have now been removed. A new test has been
added to ensure that STXO data is being properly written, and more
stringent checks for STXO data validity when added or removing blocks
has been added.
2016-09-13 11:27:28 -04:00
C Jepson
4960414937 Fix merge regression bugs relating to transaction notifications (#328)
There were two major regression related bugs from merging in the new
database. The first was failure to properly notify transactions in the
stake tree. The second was that the wrong sentinel value was being
used to terminate the rescanning loop, which normally causes
registration for relevant outpoints and addresses. Both bugs are
patched.
2016-08-30 11:32:26 -05:00
C Jepson
f82e56d252 Fix a mining bug that occurs during reorgs (#325)
When a main chain block has been reorganized out, the current
template for mining should be dropped because the parent no
longer exists in the main chain. Fixes #324.
2016-08-29 13:33:25 -05:00
Dave Collins
3740feb673 database: Replace with new version.
This commit removes the old database package, moves the new package into
its place, and updates all imports accordingly.
2016-08-23 17:40:38 -04:00
Dave Collins
7fac099bee mempool: Refactor mempool code to its own package. (#737)
This does the minimum work necessary to refactor the mempool code into
its own package.  The idea is that separating this code into its own
package will greatly improve its testability, allow independent
benchmarking and profiling, and open up some interesting opportunities
for future development related to the memory pool.

There are likely some areas related to policy that could be further
refactored, however it is better to do that in future commits in order
to keep the changeset as small as possible during this refactor.

Overview of the major changes:

- Create the new package
- Move several files into the new package:
  - mempool.go -> mempool/mempool.go
  - mempoolerror.go -> mempool/error.go
  - policy.go -> mempool/policy.go
  - policy_test.go -> mempool/policy_test.go
- Update mempool logging to use the new mempool package logger
- Rename mempoolPolicy to Policy (so it's now mempool.Policy)
- Rename mempoolConfig to Config (so it's now mempool.Config)
- Rename mempoolTxDesc to TxDesc (so it's now mempool.TxDesc)
- Rename txMemPool to TxPool (so it's now mempool.TxPool)
- Move defaultBlockPrioritySize to the new package and export it
- Export DefaultMinRelayTxFee from the mempool package
- Export the CalcPriority function from the mempool package
- Introduce a new RawMempoolVerbose function on the TxPool and update
  the RPC server to use it
- Update all references to the mempool to use the package.
- Add a skeleton README.md
2016-08-19 11:08:37 -05:00
Dave Collins
8e71bcf41a indexers: Implement optional tx/address indexes.
This introduces a new indexing infrastructure for supporting optional
indexes using the new database and blockchain infrastructure along with
two concrete indexer implementations which provide both a
transaction-by-hash and a transaction-by-address index.

The new infrastructure is mostly separated into a package named indexers
which is housed under the blockchain package.  In order to support this,
a new interface named IndexManager has been introduced in the blockchain
package which provides methods to be notified when the chain has been
initialized and when blocks are connected and disconnected from the main
chain.  A concrete implementation of an index manager is provided by the
new indexers package.

The new indexers package also provides a new interface named Indexer
which allows the index manager to manage concrete index implementations
which conform to the interface.

The following is high level overview of the main index infrastructure
changes:

- Define a new IndexManager interface in the blockchain package and
  modify the package to make use of the interface when specified
- Create a new indexers package
  - Provides an Index interface which allows concrete indexes to plugin
    to an index manager
  - Provides a concrete IndexManager implementation
    - Handles the lifecycle of all indexes it manages
    - Tracks the index tips
    - Handles catching up disabled indexes that have been reenabled
    - Handles reorgs while the index was disabled
    - Invokes the appropriate methods for all managed indexes to allow
      them to index and deindex the blocks and transactions
  - Implement a transaction-by-hash index
    - Makes use of internal block IDs to save a significant amount of
      space and indexing costs over the old transaction index format
  - Implement a transaction-by-address index
    - Makes use of a leveling scheme in order to provide a good tradeoff
      between space required and indexing costs
- Supports enabling and disabling indexes at will
- Support the ability to drop indexes if they are no longer desired

The following is an overview of the btcd changes:

- Add a new index logging subsystem
- Add new options --txindex and --addrindex in order to enable the
  optional indexes
  - NOTE: The transaction index will automatically be enabled when the
    address index is enabled because it depends on it
- Add new options --droptxindex and --dropaddrindex to allow the indexes
  to be removed
  - NOTE: The address index will also be removed when the transaction
    index is dropped because it depends on it
- Update getrawtransactions RPC to make use of the transaction index
- Reimplement the searchrawtransaction RPC that makes use of the address
  index
- Update sample-btcd.conf to include sample usage for the new optional
  index flags
2016-08-18 15:42:18 -04:00
Dave Collins
b6d426241d blockchain: Rework to use new db interface.
This commit is the first stage of several that are planned to convert
the blockchain package into a concurrent safe package that will
ultimately allow support for multi-peer download and concurrent chain
processing.  The goal is to update btcd proper after each step so it can
take advantage of the enhancements as they are developed.

In addition to the aforementioned benefit, this staged approach has been
chosen since it is absolutely critical to maintain consensus.
Separating the changes into several stages makes it easier for reviewers
to logically follow what is happening and therefore helps prevent
consensus bugs.  Naturally there are significant automated tests to help
prevent consensus issues as well.

The main focus of this stage is to convert the blockchain package to use
the new database interface and implement the chain-related functionality
which it no longer handles.  It also aims to improve efficiency in
various areas by making use of the new database and chain capabilities.

The following is an overview of the chain changes:

- Update to use the new database interface
- Add chain-related functionality that the old database used to handle
  - Main chain structure and state
  - Transaction spend tracking
- Implement a new pruned unspent transaction output (utxo) set
  - Provides efficient direct access to the unspent transaction outputs
  - Uses a domain specific compression algorithm that understands the
    standard transaction scripts in order to significantly compress them
  - Removes reliance on the transaction index and paves the way toward
    eventually enabling block pruning
- Modify the New function to accept a Config struct instead of
  inidividual parameters
- Replace the old TxStore type with a new UtxoViewpoint type that makes
  use of the new pruned utxo set
- Convert code to treat the new UtxoViewpoint as a rolling view that is
  used between connects and disconnects to improve efficiency
- Make best chain state always set when the chain instance is created
  - Remove now unnecessary logic for dealing with unset best state
- Make all exported functions concurrent safe
  - Currently using a single chain state lock as it provides a straight
    forward and easy to review path forward however this can be improved
    with more fine grained locking
- Optimize various cases where full blocks were being loaded when only
  the header is needed to help reduce the I/O load
- Add the ability for callers to get a snapshot of the current best
  chain stats in a concurrent safe fashion
  - Does not block callers while new blocks are being processed
- Make error messages that reference transaction outputs consistently
  use <transaction hash>:<output index>
- Introduce a new AssertError type an convert internal consistency
  checks to use it
- Update tests and examples to reflect the changes
- Add a full suite of tests to ensure correct functionality of the new
  code

The following is an overview of the btcd changes:

- Update to use the new database and chain interfaces
- Temporarily remove all code related to the transaction index
- Temporarily remove all code related to the address index
- Convert all code that uses transaction stores to use the new utxo
  view
- Rework several calls that required the block manager for safe
  concurrency to use the chain package directly now that it is
  concurrent safe
- Change all calls to obtain the best hash to use the new best state
  snapshot capability from the chain package
- Remove workaround for limits on fetching height ranges since the new
  database interface no longer imposes them
- Correct the gettxout RPC handler to return the best chain hash as
  opposed the hash the txout was found in
- Optimize various RPC handlers:
  - Change several of the RPC handlers to use the new chain snapshot
    capability to avoid needlessly loading data
  - Update several handlers to use new functionality to avoid accessing
    the block manager so they are able to return the data without
    blocking when the server is busy processing blocks
  - Update non-verbose getblock to avoid deserialization and
    serialization overhead
  - Update getblockheader to request the block height directly from
    chain and only load the header
  - Update getdifficulty to use the new cached data from chain
  - Update getmininginfo to use the new cached data from chain
  - Update non-verbose getrawtransaction to avoid deserialization and
    serialization overhead
  - Update gettxout to use the new utxo store versus loading
    full transactions using the transaction index

The following is an overview of the utility changes:
- Update addblock to use the new database and chain interfaces
- Update findcheckpoint to use the new database and chain interfaces
- Remove the dropafter utility which is no longer supported

NOTE: The transaction index and address index will be reimplemented in
another commit.
2016-08-18 15:42:18 -04:00
David Hill
696dcddb23 Return from syncMiningStateAfterSync if peer disconnected. (#310)
Before this fix, if a peer disconnected before the chain was marked
current, its goroutine and memory would hang around until the chain
was marked current.  This would cause out-of-memory errors.

This should also speed up blockchain processing since there are
no longer many goroutines calling IsCurrent every 3 seconds.
2016-08-09 13:59:46 -05:00
David Hill
35a103d454 blockmanager: current() for testnet should check blockchain timesource. (#302) 2016-08-09 12:10:13 -05:00
Dave Collins
bd4e64d1d4 chainhash: Abstract hash logic to new package. (#729)
This is mostly a backport of some of the same modifications made in
Decred along with a few additional things cleaned up.  In particular,
this updates the code to make use of the new chainhash package.

Also, since this required API changes anyways and the hash algorithm is
no longer tied specifically to SHA, all other functions throughout the
code base which had "Sha" in their name have been changed to Hash so
they are not incorrectly implying the hash algorithm.

The following is an overview of the changes:

- Remove the wire.ShaHash type
- Update all references to wire.ShaHash to the new chainhash.Hash type
- Rename the following functions and update all references:
  - wire.BlockHeader.BlockSha -> BlockHash
  - wire.MsgBlock.BlockSha -> BlockHash
  - wire.MsgBlock.TxShas -> TxHashes
  - wire.MsgTx.TxSha -> TxHash
  - blockchain.ShaHashToBig -> HashToBig
  - peer.ShaFunc -> peer.HashFunc
- Rename all variables that included sha in their name to include hash
  instead
- Update for function name changes in other dependent packages such as
  btcutil
- Update copyright dates on all modified files
- Update glide.lock file to use the required version of btcutil
2016-08-08 14:04:33 -05:00
Dave Collins
00ebb9d14d blockchain: Associate time src with chain instance.
Rather than making the caller to pass in the median time source on
ProcessBlock and IsCurrent, modify the Config struct to include the
median time source and associate it with the chain instance when it is
created.

This is being done because both the ProcessBlock and IsCurrent functions
require access to the blockchain state already, it is a little bit safer
to ensure the time source matches the chain instance state, it
simplifies the caller logic, and it also allows its use within the logic
of the blockchain package itself which will be required by upcoming
rule change warning logic that is part of BIP9.
2016-07-14 13:10:47 -05:00
C Jepson
eda86f5267 Asynchronously call TicketPoolValue to stop block manager blocking (#265) 2016-06-03 15:13:47 -05:00
Dave Collins
c21db7afba server: Optimize map limiting in block manager.
Upstream commit 23f59144c7.
2016-06-01 13:28:28 -05:00
Dave Collins
2ad0b1aa4c mining: Export block template fields.
Upstream commit a3fa066745.

Also updates all of the new references for the newly exported fields as
part of the merge commit.
2016-06-01 13:25:58 -05:00
Dave Collins
51250786c6 Keep track of recently rejected transactions.
Upstream commit cab74feb59.
2016-06-01 13:17:53 -05:00
Dave Collins
2030b4d057 multi: Fix several misspellings in the comments.
Contains the following upstream commits:
- ef9c50be57
- eb882f39f8

In addition to merging the fixes in the commits, this also fixes a few
more misspellings that were introduced in the new Decred code.
2016-05-30 12:24:21 -05:00
David Hill
619de720e0 dcrd: do not process empty getdata messages 2016-05-24 15:47:08 -04:00
Dave Collins
85d85e8a49 Sync upstream blockmanager comments improvements.
Upstream commit 912a8d8301
2016-05-21 02:12:16 -05:00
Dave Collins
756eff2fee peer: Refactor peer code into its own package.
Contains the following upstream commits:

- 00bddf7540
- 250228c32f
- f1bd2f8d6e
- cbbe3a8bbe
- aa03d68e1e

In addition to the normal required changes for syncing, the following
changes have been made in order to facilitate integration of the new
package into Decred:

- Removed check in PushRejectMsg against protocol version since all
  peers since the initial version support it
- Fixed leaked timer in `syncMiningStateAfterSync` function
- Add the Decred-specific OnGetMiningState and OnMiningState handlers to
  the new peer package
- Add handler for the new mining state messages to the 'serverPeer' type
  and register them
- Use the new constant for wire.InitialProtocolVersion in the reject
  message instead of hard coded number
- Remove logic specific to the regression network since Decred does not
  have it
2016-05-20 13:58:23 -05:00
Dave Collins
e310d1dac5 Integrate a valid ECDSA signature cache
Upstream commit 0029905d43
2016-05-18 13:37:06 -05:00