Commit Graph

148 Commits

Author SHA1 Message Date
David Hill
65a467e0cf mining: fix data race
use a local prng variable
2019-09-11 10:35:24 -05:00
David Hill
78fd2b33a4 mining: fix data race
Use the read template.
2019-09-11 10:11:36 -05:00
Dave Collins
cffc300c6a
mining: Minor cleanup of aggressive mining path.
This combines the two conditions for the aggressive mining path into a
single condition and does a bit of light cleanup to remove the template
copies that are no longer necessary due to the removal of the old style
template caching.
2019-09-09 12:19:53 -05:00
Dave Collins
280ccb732c
mining: Remove unused extra nonce update code.
This removes the UpdateExtraNonce function which updated an extra nonce
in the coinbase transaction and recalculated the merkle root since it is
not necessary and wasteful for Decred due to the extra nonce being
available the block header.

Further, due to the aforementioned and the fact the template doesn't
have a height set, it isn't currently actually being called anyway as
can be seen by diffing the decoded output of subsequent getwork calls
and noting the only thing that is being updated in between full
regeneration of new templates is the timestamp as expected.

$ diff -uNp work1.txt work2.txt
--- work1.txt   2019-09-07 08:18:58.410917100 -0500
+++ work2.txt   2019-09-07 08:19:01.216456300 -0500
@@ -16,7 +16,7 @@
     "sbits": 0.00021026,
     "height": 98,
     "size": 7221,
-    "time": 1567862338,
+    "time": 1567862341,
     "nonce": 0,
     "extradata": "0000000000000000000000000000000000000000000000000000000000000000",
     "stakeversion": 0,
2019-09-09 11:57:29 -05:00
Dave Collins
48c0585e6b
mining: Remove dead code.
This removes all of the code related to setting and updating cached
templates in the block manager since they are no longer used.

It is easy to see this is the case by considering that the only places
that set cachedCurrentTemplate and cachedParentTemplate set them to nil.
2019-09-09 11:51:04 -05:00
Donald Adu-Poku
1e7fe1fe31 multi: use chain ref. from blockmanager config.
This removes the chain field from the block
manager in favour of the chain field in the
block manager config.
2019-09-05 10:13:01 -05:00
Aaron Campbell
8be96a8729 multi: Correct typos.
Correct typos found by reading code, ispell, and creative grepping.
2019-08-22 10:20:03 -05:00
Aaron Campbell
9a368f5edc mining: Remove unused error return value. 2019-08-22 08:31:52 -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
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
David Hill
70c14042d8 multi: fix recent govet findings
add govet to linter tests.
2019-04-29 17:58:06 -05:00
Donald Adu-Poku
e69a789183 multi: fix onVoteReceivedHandler shutdown.
This updates onVoteReceivedHandler to call regenTemplate
 as a goroutine to prevent blocking on shutdown.
2019-04-13 12:53:04 -05:00
Dave Collins
b203c8af58
mining: Run vote ntfn in a separate goroutine.
This ensures the vote handling for the new background miner template
happens in a goroutine in order to prevent blocking more transactions
being added to the mempool and the vote itself from being immediately
relayed to the rest of the network.

It also prevents a potential deadlock that can occur due to the cycle
created by being called under the mempool lock and in turn generating a
template which itself attempts to grab the mempool lock to get the list
of transactions.

This really should be handled better overall, but this serves as a quick
solution until the rest of the mining updates are made.
2019-04-03 01:51:57 -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
Donald Adu-Poku
e9b2b4854f mining: fix scheduled template regen.
This fixes a case where a block with five votes
immediately triggers a regen (as it should) but also
schedules another regen in a second.
2019-04-01 16:38:54 -05:00
Dave Collins
6875c3fde9
mining: Improve template key handling.
This factors out the code which deals with generating a unique block
template key to a separate function, modifies it to only be comprised of
the merkle root + timestamp, and renames the associated variables
accordingly.  The separate function is useful because work submission
will ultimately need to create the same key.

The rationale for switching to only using the merkle root + timestamp is
as follows:

- It is more efficient to use smaller keys
- The combination is guaranteed to be unique for every template so long
  as there are no more than one per second generated with the exact same
  txns (which is already the case with the inclusion of the stake merkle
  root in the key too)
- There are future plans to combine the stake root and merkle roots into
  the merkle root field and repurpose the stake root

Finally, the naming is also being changed from ID to key because the
name templateID already has a distinct meaning in the rpcserver code in
how it applies to long polling clients and it is better to avoid
potential confusion.
2019-04-01 11:12:30 -05:00
Dave Collins
903be52b17
mining: Remove unnecessary notify goroutine.
This modifies the code which notifies subscribed clients about a new
block template to avoid creating an unnecessary goroutine since the
channel is single use and intentionally buffered to ensure the sender
can't block.
2019-04-01 10:35:30 -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
Sarlor
dcd2d701b5 mining: Optimize get the block's votes tx.
The optimizes to check the height of the next block is greater than the
threshold first since it is more likely in the NewBlockTemplate
function.
2019-02-08 01:25:53 -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
Sarlor
353f84e75a mining: Remove superfluous error check.
This removes a superfluous error check in the NewBlockTemplate
function.
2019-01-03 20:33:17 -06: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
15f7f61e32
multi: Latest consensus active from simnet genesis.
This modifies simnet to include the latest consensus changes that have
been successfully voted into mainnet to date starting from its genesis
block.  This means it is no longer necessary to vote those changes in to
simnet first before making use of them.

The changes entail removing the deployment entries for those votes,
updating the mining templates to start from version 5, which matches the
current mainnet version, and modifying the various sections in
blockchain which make decisions accordingly.

The chaincfg and blockchain modules are affected, but since their
version has already been bumped since their last release tags, they are
not bumped again.
2018-10-10 15:58:53 -05:00
Dave Collins
2dcfb0a6da
multi: Move update blk time to blk templ generator.
This moves the UpdateBlockTime function to the recently introduced
BlkTmplGenerator type in order to break its dependence on the block
manager.
2018-09-13 23:32:58 -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
3b33c0cc93 multi: move MinHighPriority into mining package.
Port of upstream commit a18f883.
2018-09-12 15:40:55 +00:00
Donald Adu-Poku
fbbfb22c1f mining: remove chainState dependency.
Port of upstream commit 2274d36 (subset). In preparation of the
removal of chainState.
2018-09-12 15:24:35 +00:00
Donald Adu-Poku
3921320d55 multi: remove chainState dependency in rpcserver.
this updates the function signatures of minimumMedianTime and
medianAdjustedTime and removes all chainState usage  in
rpcserver.go in favour of using BestState.

Port of upstream commit 2274d36 (subset). In preparation of the
removal of chainState.
2018-09-12 10:06:33 -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
Dave Collins
6327ed7fab
blockchain: CheckConnectBlockTemplate with tests.
This removes the CheckConnectBlock function in favor of a new function
named CheckConnectBlockTemplate which more accurately reflects its
purpose of testing block template proposals and uses this fact to be
more restrictive about the allowed inputs and to avoid performing the
proof of work check.

In particular, the provided block template must only build from the
current tip or its parent or an error is returned.

All mining code has been updated to call the new function accordingly.

Finally, it also adds a full suite of tests for the new function using
the chaingen framework in order to ensure proper functionality.
2018-05-03 13:53:24 -05:00
Dave Collins
19511af927
mining: Correct initial template generation.
This corrects the code to create a new template when first starting up
with aggressive mining enable before votes on the most recent block are
known.

First, the code is expecting the current best block, not its parent, and
second, the coinbase script should match what is created in the normal
path as well.
2018-03-05 12:57:36 -06:00
Dave Collins
9f7d6a1aac
mempool/mining: TxSource separation.
This finishes separating the mining code from the mempool that was
partially done in commit 9031d85 by extending the TxSource interface to
include the new functionality required by Decred.

The following is an overview of the changes to accomplish this:
- Move the VoteTx struct out of the mempool package in the mining
  package and rename it to VoteDesc instead to signify it is a vote
  descriptor and be consistent with the naming of TxDesc
- Update mempool to use the new mining.VoteDesc struct
- Rename CheckIfTxsExist to HaveAllTransactions to be more consistent
  with HaveTransaction in the TxSource interface as it now lives
  alongside it
- Add VoteHashesForBlock, VotesForBlocks, and IsTxTreeKnownInvalid
  to the TxSource interface
- Switch the mining code to call the functions on the TxSource interface
  instead and remove the reference to the concrete mempool
2018-03-05 11:38:36 -06:00
Dave Collins
1e466c62ea
mempool/mining: Clarify tree validity semantics.
This replaces the mempool IsTxTreeValid function with
IsTxTreeKnownInvalid instead which more accurately describes its
semantics and purpose.

The actual purpose of this function is related to mempool acceptance and
building block templates for mining where the assumption is that the
previous block's regular transaction tree will be valid and is only
invalid specifically if there are enough known votes that vote against
it.

This change is desirable because the function provides semantics that
are actually opposite to that of the consensus rules where a tree is
only valid if it has a majority of yes votes and thus claiming it's
valid when that is not actually known for certain yet can easily cause
confusion.
2018-03-05 11:38:06 -06:00
Dave Collins
5e29dc7393
mining: Use single uint64 coinbase extra nonce.
The current code creates block templates with coinbase transactions that
have 4 uint64 extra nonces, but only ever uses one of them.  Rather than
wasting the extra space, this modifies the code so it only uses a single
uint64 extra nonce.

It should be noted that realistically there isn't even a real need for
an extra nonce in the coinbase at all because there is extra space in
the header specifically for that purpose and miners can't modify the
coinbase via getwork anyways.

However, it is still necessary to insert for the current code in order
to ensure every block template has a unique merkle root since that is
what is used to uniquely identify the block template.
2018-03-04 16:40:01 -06:00
Dave Collins
1275d1ffe9
main: Make func definition style consistent.
This modifies all files in the main package so that function definitions
are on the a single line as is the style used in the upstream code as
well as throughout its code base.  This helps minimize the differences
between them and the upstream code in order to facilitate easier syncs
due to less merge conflicts as a result of superfluous changes.
2018-03-04 14:31:43 -06:00
Dave Collins
2027fc339a
mining/mempool: Move priority code to mining pkg.
This moves the priority-related code from the mempool package to the
mining package and also exports a new constant named UnminedHeight which
takes the place of the old unexported mempoolHeight.

Even though the mempool makes use of the priority code to make decisions
about what it will accept, priority really has to do with mining since
it influences which transactions will end up into a block.  This change
also has the side effect of being a step towards enabling separation of
the mining code into its own package which, as previously mentioned,
needs access to the priority calculation code as well.

Finally, the mempoolHeight variable was poorly named since what it
really represents is a transaction that has not been mined into a block
yet.  Renaming the variable to more accurately reflect its purpose makes
it clear that it belongs in the mining package which also needs the
definition now as well since the priority calculation code relies on it.
This will also benefit an outstanding PR which needs access to the same
value.
2018-03-03 00:18:01 -06:00
Jonathan Gillham
ba2bd63533
mining: Stop transactions losing their dependants.
This fixes a bug where a transaction would lose reference to other
transactions dependant on it when being considered for inclusion in a
new block template. The issue only occurs when the transaction being
considered triggers a change of priority queue ordering to ordering by
fee. It results in none of the dependant transactions being considered
for inclusion in the new block template.
2018-03-02 23:55:41 -06:00
Dave Collins
1f2ae2f78f
mining: Fix duplicate txns in the prio heap.
This prevents the ability for duplicate transactions to be added to the
mining priority heap when a transaction spends multiple outputs from the
same input transaction by converting the dependency tracking to use a
map keyed by the transaction hash instead of a linked list.
2018-03-02 23:35:48 -06:00
Dave Collins
a6ddf038f2
mining: Obtain block by hash instead of top block.
This modifies the mining code to request the desired blocks from chain
by hash as opposed to using a separate function to get the top block and
removes the now unused plubming through block manager.

Not only is this faster because it avoids the need to go through block
manager, it is also more robust since it does not rely on the tip of the
chain not having changing for correctness.
2018-03-01 12:41:46 -06:00
Dave Collins
479bfdead8
blockchain: Reduce GetGeneration to TipGeneration.
This replaces the GetGeneration function which allowed getting the
entire generation (all children stemming from the same parent) of an
arbitrary bock with TipGeneration which only returns the same
information for the tip block.

This is being done because the function is only used for mining purposes
to get the generation of the current tip.  The code is simplified by
reducing its scope to its actual purpose as an initial benefit.  It also
provides much better optimization opportunities later.
2018-02-26 11:41:01 -06:00
David Hill
5fc31ca578 multi: fix misspell linter warnings 2018-02-18 12:26:52 -06:00
Dave Collins
21e9a85fdb
blockchain/mining: Full checks in CCB.
This modifies the exported CheckConnectBlock function to call the
checkBlockSanity and checkBlockContext functions to ensure all
validation rules are enforced from the mining code.

Since both the mining code and tests typically work with unsolved
blocks, this also introduces a new parameter on CheckConnectBlock to
pass behavior flags which allows the caller to skip the proof of work
check.

It also modifies forceHeadReorganization to call checkBlockContext for
the same reason.

Finally, all tests and call sites are updated with the appropriate
flags and various tests are updated for the changes accordingly.
2018-02-14 13:10:33 -06:00
Dave Collins
d357113bf0
stake: Static assert of vote commitment.
This modifies the SSGenBlockVotedOn function to directly copy the hash
the vote commits to into a statically sized array versus calling the
hash function and thus can remove the potential runtime error.

This is preferred because the code will fail to compile if the size
of chainhash.HashSize is every changed which is desirable because it
would mean the assumptions the code makes would be invalidated.

It also updates all callers in the repository accordingly.
2018-02-02 14:19:59 -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
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
Dave Collins
855305962a
multi: Enable vote for DCP0002 and DCP0003.
This implements the agenda for voting on the LN features as defined in
DCP0002 and DCP0003 along with consensus tests to ensure its correctness.

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 5
  - New block version on testnet is version 6
- Introduce a convenience function for determining if the vote passed
  and is now active
- Introduce a new function for getting the consensus script verification
  flags and setting the appropriate flags to enforce the new consensus
  semantics in accordance with the state of the vote
- Enforce transaction finality checks based on the past median time in
  accordance with the state of the vote
- Enforce relative time locks via sequence numbers in accordance with
  the state of the vote
- Modify the more strict standardness checks (acceptance to the mempool
  and relay) to enforce DCP0002 in accordance with the state of the vote
  - It should be noted that the flag for DCP0003 is always set for
    the more strict standardness checks because it is a soft fork while
    the DCP0002 enforcement must depend on the result of the vote
    because it is a hard fork
- Add tests for determining consensus script verification flags for both
  mainnet and testnet
- Add tests for determining if the agenda is active for both mainnet and
  testnet
2017-09-22 11:43:58 -05:00
Dave Collins
1955bb1bf1
multi: Abstract standard verification flags.
This modifies the way standard verification flags are handled so that it
is possible to selectively enable them based on the result of agenda
votes.

First, it moves the StandardVerifyFlags constant from the txscript
package to the mempool/policy code and rename it to
BaseStandardVerifyFlags.  As the TODO in the comment of the moved
constant indicated, these flags are policy related and thus really
belong in policy.  Ideally there would be a completely separate policy
package, but since the policy code currently lives in mempool/policy.go,
the constant has been moved there.

Next, it introduces a new function named standardScriptVerifyFlags,
which accepts the chain as an argument and, for now, just returns the
BaseStandardVerifyFlags along with a nil error.  This will allow
additional flags to be selectively enabled depending on the result of an
agenda vote.

Finally, it updates the mempool policy struct to require a closure for
obtaining the flags so it can remain decoupled from the chain which in
turn allows easier and more robust unit testing of mempool functionality
since it allows a mocks to be used.
2017-09-15 12:58:21 -05:00