Commit Graph

65 Commits

Author SHA1 Message Date
David Hill
39e5af860b stake: optimize FindSpentTicketsInBlock slightly 2018-02-18 19:07:49 -06:00
David Hill
2b03537689 mempool: cleaner 2018-02-17 12:42:14 -06:00
Dave Collins
6b36299994
blockchain/stake: Rename tix spent to tix voted.
This renames the fields dealing with the hashes of tickets that have
been voted on from ticketsSpent to ticketsVoted to more accurately
differentiate them from revocations which also technically spend
tickets.
2018-02-15 21:22:55 -06:00
David Hill
393a95c079 multi: fix some maligned linter warnings 2018-02-13 14:50: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
David Hill
dce7e3f161 multi: various cleanups 2018-02-02 14:18:41 -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
Dave Collins
b486cada60
blockchain/stake: Use Hash256PRNG init vector.
This modifies the stake package to accept an initialization vector for
the node connection and disconnection code so that the caller can
provide a cached value versus the data having to be recomputed.  All
tests in the stake package have been updated for the changes.

It also updates the blockchain package to calculate the iv for the block
header and cache the value with each block node and updates the callers
into the modified stake package functions to use the cached values.
2018-01-29 11:00:39 -06:00
Dave Collins
f7f68c5855
stake: Add Hash256PRNG init vector support.
This adds initialization vector support to Hash256PRNG which is used for
determining winning tickets.  This allows callers to cache and reuse the
initialization vector for a given seed to avoid recomputation.

It accomplishes this by exporting two new functions named
CalcHash256PRNGIV and NewHash256PRNGFromIV and updating the existing
NewHash256PRNG function to use the new functions.

It also improves the comment on NewHash256PRNG while here.
2018-01-29 10:55:17 -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
Dave Collins
6fcd077696
stake: Override false positive vet error.
This adds a directive to instruct gometalinter to ignore a false
positive produced by vet.  The code in question intentionally makes use
of the property vet is warning about.
2018-01-06 19:23:23 -06:00
David Hill
b13f5dfbda travis: add ineffassign linter 2017-12-01 09:14:04 -05:00
David Hill
20686cd775 travis: add gosimple linter 2017-11-20 18:49:55 -06:00
Matheus Degiovani
2310b4c096 stake: Add IsStakeSubmission (#907)
* Add IsStakeSubmissionTxOut test

* Simplify test

* Remove mtx argument

* Fix formatting

* Fix comment
2017-11-01 13:36:34 -04:00
David Hill
6df741c633 blockchain: removed unused funcs and vars 2017-10-17 17:52:21 -05: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
b7a37a3ca2 gofmt 2017-10-09 17:01:46 -04:00
Jason Zavaglia
65cd08cc75 blockchain.stake: ticket expiry perf improvement.
Change tickettreap to allow for efficient queries by min blockheight,
allowing for O(1) ticket expiry.

This allows for a very significant performance increase as previously
the same query required an iteration of 40,000 or so items while
processing each block.

Remove tickettreap.Mutable - it is not used, and it is difficult to
maintain with the other changes made to the treapNode class used by
Immutable.
2017-10-04 22:55:43 -05:00
Jason Zavaglia
4cbd3b738d blockchain.stake: treap index perf improvement.
Fix O(n) lookups-by-position into being O(ln n) in liveTickets.
This reduces the time to handle a new block by around a third.

Update memory-usage calculations to be more accurate, and have
extra testing.
2017-10-04 22:55:43 -05:00
Dave Collins
6d35635b9a
stake: Modify ticket tests to use chaincfg params.
Rather than redefining the simnet parameters in the tests, just use the
existing chaincfg simnet parameters.  This is acceptable because there
are now full block consensus tests that have their own definitions and
ensure the consensus handling for tickets is correct.

Further, if these tests really wanted to have their own versions, they
should instead start with the definition in chain params, make a copy,
and change whatever they require that is different versus redefining
them which makes them cumbersome to update.
2017-09-08 13:22:13 -05:00
David Hill
4c1f4f1038 blockchain: cast to int64. (#817)
fixes 32-bit
2017-08-15 17:14:28 -04:00
Dave Collins
fce24223cd
multi: Separate tx serialization type from version.
Decred's serialized format for transactions split the 32-bit version
field into two 16-bit components such that the upper bits are used to
encode a serialization type and the lower 16 bits are the actual
transaction version.

Unfortunately, when this was done, the in-memory transaction struct was
not also updated to hide this complexity, which means that callers
currently have to understand and take special care when dealing with the
version field of the transaction.

Since the main purpose of the wire package is precisely to hide these
details, this remedies the situation by introducing a new field on the
in-memory transaction struct named SerType which houses the
serialization type and changes the Version field back to having the
desired semantics of actually being the real transaction version.  Also,
since the maximum version can only be a 16-bit value, the Version field
has been changed to a uint16 to properly reflect this.

The serialization and deserialization functions now deal with properly
converting to and from these fields to the actual serialized format as
intended.

Finally, these changes also include a fairly significant amount of
related code cleanup and optimization along with some bug fixes in order
to allow the transaction version to be bumped as intended.

The following is an overview of all changes:
- Introduce new SerType field to MsgTx to specify the serialization type
- Change MsgTx.Version to a uint16 to properly reflect its maximum
  allowed value
- Change the semantics of MsgTx.Version to be the actual transaction
  version as intended
- Update all callers that had special code to deal with the previous
  Version field semantics to use the new semantics
- Switch all of the code that deals with encoding and decoding the
  serialized version field to use more efficient masks and shifts
  instead of binary writes into buffers which cause allocations
- Correct several issues that would prevent producing expected
  serializations for transactions with actual transaction versions that
  are not 1
- Simplify the various serialize functions to use a single func which
  accepts the serialization type to reduce code duplication
- Make serialization type switch usage more consistent with the rest of
  the code base
- Update the utxoview and related code to use uint16s for the
  transaction version as well since it should not care about the
  serialization type due to using its own
- Make code more consistent in how it uses bytes.Buffer
- Clean up several of the comments regarding hashes and add some new
  comments to better describe the serialization types
2017-08-07 14:10:27 -05:00
David Hill
dfbedbd701 stake: less casting 2017-07-17 19:36:57 -05:00
David Hill
59db139d19 blockchain: check errors and remove ineffectual assignments. 2017-07-17 13:52:06 -05:00
Josh Rickmar
ce4b77d3d9 all: Remove seelog logger.
The btclog package has been changed to defining its own logging
interface (rather than seelog's) and provides a default implementation
for callers to use.

There are two primary advantages to the new logger implementation.

First, all log messages are created before the call returns.  Compared
to seelog, this prevents data races when mutable variables are logged.

Second, the new logger does not implement any kind of artifical rate
limiting (what seelog refers to as "adaptive logging").  Log messages
are outputted as soon as possible and the application will appear to
perform much better when watching standard output.

Because log rotation is not a feature of the btclog logging
implementation, it is handled by the main package by importing a file
rotation package that provides an io.Reader interface for creating
output to a rotating file output.  The rotator has been configured
with the same defaults that btcd previously used in the seelog config
(10MB file limits with maximum of 3 rolls) but now compresses newly
created roll files.  Due to the high compressibility of log text, the
compressed files typically reduce to around 15-30% of the original
10MB file.
2017-06-20 10:58:10 -04: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
Dave Collins
05d8456d3e
multi: Rename vote choice IsIgnore to IsAbstain.
This renames the chaincfg parameter for the vote choice which represents
an abstaining vote to be named IsAbstain instead of IsIgnore since that
more accurately describes its intent and behavior.

It also updates the RPC server choice result field for isignore to be
named isabstain to match and bumps the major version accordingly.

Finally, it renames other internal variables which make use of the
choice to include the word abstain as well for clarity and renames a
couple of other internal variables.
2017-04-24 16:17:27 -05:00
David Hill
99d04eea40 Preallocate the exact number of bytes if known. 2017-03-20 21:46:33 -05:00
John C. Vernaleo
ef71103c95 Remove variables for testnet v1. 2017-03-16 20:19:07 -04: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
637e6d9e10
multi: Implement block size hard fork demo voting.
This implements a new voting agenda for the testnet and simnet networks
for increasing the maximum block size from 1MiB to 1.25MB.

The following is an overview of the changes:

- Bump the maximum protocol block size limit to 1.25MB
- Bump the protocol version to 4
- Add wire tests for v3 protocol sizes and update tests for latest
- Update all wire values that are defined in terms of the max block size
  to respect the protocol version
- Update the MaxSigOpsPerBlock constant to maintain existing value
  regardless of the raised max protocol block size
- Decouple the maximum tx size from the block size by creating a chain
  parameter for it with the current sizes so it is not a part of the
  hard fork vote
- Add definition for new version 4 stake vote along with agenda to vote
  on block size to the testnet and simnet networks
- Convert the MaximumBlockSize chain parameter to a slice in order to
  hold the different possible sizes
- Adds a new function that returns the maximum block size based upon the
  result of the vote
- Change the existing context-free block size check to enforce the max
  protocol size and introduce a context-specific check which enforces a
  restricted size based upon the network consensus parameters and the
  result of the vote
- Set the max allowed size in generated block templates based upon the
  network params and result of the vote
- Generate version 4 blocks and reject version 3 blocks after a super
  majority has been reached
2017-02-13 13:28:21 -06:00
Marco Peereboom
6967358649 blockchain: Implement configurable voting on top of PoS. (#542)
Port BIP0009 over from btcd.  The following is an overview of the
changes:
- Add new configuration options to the chaincfg package which allows the
  rule deployments to be defined per chain
- Implement code to calculate the threshold state as required by voting
  - Use threshold state caches that are stored to the database in order
    to accelerate startup time
  - Remove caches that are invalid due to definition changes in the
    params including additions, deletions, and changes to existing
    entries
  - Verify that PoW and PoS majorities have been reached.
- Add tests for new error type
- Add tests for threshold state
- Deployments are per stake version.
- Add human readable vote/choice infrastructure.
- Add RPC command to interrogate vote status (getvoteinfo).
2017-02-13 13:32:40 -05:00
David Hill
0e91858c85 stake: Add SSGenVoteBitsExtendedMaxSize const (#541) 2017-01-04 18:09:23 -05:00
Dave Collins
face803542 blockchain: Make params used in tests match. (#517)
This updates the various definitions of the simnet params used
exclusively in the tests to match their definitions used by the actual
simnet parameters defined in chaincfg.

While it would certainly be easier to simply use the params defined in
chaincfg, that also would not allow the tests to detect them being
inadvertently changed.
2016-12-20 10:37:22 -06:00
Dave Collins
698fee123b multi: Restore correct upstream majority version code. (#490)
This reverts to the correct upstream majority version code which
properly detects when certain thresholds of the network have been
updated in order to determine when to start rejecting old version
blocks and enforcing the rules in the new version block.
2016-11-25 20:59:46 -06:00
Dave Collins
a227189444 stake: Convert TxType constants to enum syntax. 2016-11-23 19:32:36 -06:00
Dave Collins
67b9004bab
stake/dcrjson: Simplify code with gofmt -s. 2016-11-21 11:03:17 -06:00
Dave Collins
60c812e735
multi: Upstream parameter abstraction sync
Upstream commit a7b35d9f9e.

Also, the merge commit contains necessary decred-specific alterations.
It also has the side effect of correcting a couple of min reduction bugs
even though they can't currently ever be hit due to the min reduction
interval flag being disabled for all networks.
2016-11-16 19:34:01 -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
a0c19ada7b
wire: Export transaction tree constants.
This exports the transaction tree constants from the wire package
instead of from dcrutil.  The tree is a fundamental part of a
transaction and therefore its definitions belong in wire alongside the
other constants that are also related to fundamental transaction fields.

Further, the wire package most definitely should not depend on dcrutil
since that would create a cyclic import cycle.
2016-11-14 14:35:22 -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
cjepson
cc25399f6a Add new setticketsvotebits command
The dcrwallet command to set multiple tickets vote bits fields at
the same time has been added.  Functions to encode/decode relevant
hex strings (as passed over JSON) were also added, along with tests.
2016-10-14 13:06:30 -04:00
C Jepson
f26d1e4b34 Add voting version parsing function (#420)
A voting version parsing function was added.  Vote versions are
uint32s.
2016-10-13 11:56:29 -05:00
Josh Rickmar
d58299b059 Replace some unnecessary dcrutil.Tx usage with wire.MsgTx. (#419) 2016-10-12 13:57:47 -04:00
Josh Rickmar
e206421edd Optimize coinbase output tax check.
Profiling indicated that significant time was being spent validating
coinbase outputs, ensuring that they paid to the development
organization's P2SH tax address.  This check was more inefficient than
necessary for a couple of reasons:

* The tax address was always decoded from a string to a dcrutil.Address.

* The actual script being validated was always parsed for addresses to
  check if they matched the tax address.

Neither of these are needed.  To optimize the algorithm, only the
equality of the output script and script version are checked.
2016-10-07 16:39:40 -04:00
Dave Collins
ccc3b7a133 stake: Correct prng uint32 rollover. (#403)
This corrects the the hash256 deterministic prng generator to properly
rollover and avoid repeating values when it has been invoked more than
2^35 + 8 times.

While here, it also removes the unnecessary 'seedState' struct field in
favor of storing the seed as a chainhash.Hash directly and just updating
it on rollover.

Finally, it also refactors the seed const to a package level constant to
avoid generating a new byte slice (and hence extra garbage) every time a
new generator is created.

It should be noted that this does not affect Decred consensus at all
because it's impossible to invoke the generator more than 2^35 + 8 times
due to other constraints.
2016-10-06 13:20:13 -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
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
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
Alex Yocom-Piatt
3285b88ce3 docs: Add/update doc.go in a few spots (#277) 2016-07-08 11:09:32 -05:00