This removes the deprecated functions along with the additional code and
tests which are no longer necessary as a result of removing the
functions.
The following is a list of exported types and functions removed along
with what they were replaced by when applicable:
- DisableLog -> UseLogger(slog.Disabled)
- BlockOneCoinbasePaysTokens -> no alternative, internal only
- IsCoinBase -> standalone.IsCoinBaseTx
- IsCoinBaseTx -> standalone.IsCoinBaseTx
- BuildMerkleTreeStore -> standalone.CalcTxTreeMerkleRoot
- BuildMsgTxMerkleTreeStore -> standalone.CalcTxTreeMerkleRoot
- SubsidyCache -> standalone.SubsidyCache
- NewSubsidyCache -> standalone.NewSubsidyCache
- CalcBlockWorkSubsidy -> standalone.SubsidyCache.CalcWorkSubsidy
- CalcStakeVoteSubsidy -> standalone.SubsidyCache.CalcStakeVoteSubsidy
- CalcBlockTaxSubsidy -> standalone.SubsidyCache.CalcTreasurySubsidy
- CoinbasePaysTax -> no alternative, internal only
- CalculateAddedSubsidy -> no alternative, internal only
- BestPrevHash -> BestSnapshot.PrevHash
- TotalSubsidy -> BestSnapshot.TotalSubsidy
- FetchSubsidyCache -> standalone.NewSubsidyCache passed to chain
- HashToBig -> standalone.HashToBig
- CompactToBig -> standalone.CompactToBig
- BigToCompact -> standalone.BigToCompact
- CalcWork -> standalone.CalcWork
- CheckProofOfWork -> standalone.CheckProofOfWork
This udpates the blockchain module to use the lastest module major
versions.
While here, it also corrects a few typos and updates some test function
names to more accurately reflect their purpose.
The updated direct dependencies are as follows:
- github.com/decred/dcrd/blockchain/stake/v2@v2.0.1
- github.com/decred/dcrd/chaincfg/v2@v2.2.0
- github.com/decred/dcrd/database/v2@v2.0.0
- github.com/decred/dcrd/dcrutil/v2@v2.0.0
- github.com/decred/dcrd/txscript/v2@v2.0.0
This updates blockchain to make use of the new work functions in the
standalone module.
Finally, it also deprecates the related exported functions in the
blockchain module so they can be removed in the next major version and
rewrites them in terms of the standalone module in the mean time.
This modifies the various code which deals with choosing which set of
consensus rules to use based upon the result of consensus votes to
remove the hard coded network checks. Not only does it simplify the
existing code, but it makes it less error prone and cumbersome to
introduce new consensus votes in the future.
In order to accomplish this, introduce a new map to associate each
vote/agenda ID to the version that defines it within a given set of
chain parameters and populate the map when creating the chain instance.
Then, when the version is needed to make a decision regarding which
consensus rules are active, query the version from the map by ID. A
missing entry means there is no voting agenda for the given network
(such as will be the case on simnet), and therefore the new rules will
always be in effect for that network.
An important point is that it is theoretically possible that the same ID
could be used in multiple consensus votes since they are only
technically unique per deployment version, although in practice reusing
IDs would be confusing. Given the former, and since duplicate IDs would
break this logic otherwise, the chain instance will now return an error
if a duplicate ID is detected.
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.
This resurrects the regression test network that was removed before
initial launch although it really should not have been. The simulation
test network and the regression test network do not serve the same
purpose. Specifically, the regression test network is intended for unit
tests, RPC server tests, and consensus tests. On the other hand, the
simulation test network is intended for private use within a group of
individuals doing simulation testing and full integration tests between
different applications such as wallets, voting service providers, mining
pools, block explorers, and other services that build on Decred.
Keeping the concerns separate will allow the simulation test network to
be modified in ways such as activating consensus changes that have been
successfully voted into mainnet without also needing to vote them in on
the simulation test network while still preserving the ability for the
unit tests to properly test the voting semantics and handling to help
prevent regressions.
In addition to resurrecting the regression test network, this also fully
fleshes out new values for the various addresses prefixes (Rk, Rs, Re,
etc), HD key prefixes (rprv, rpub), and treasury multisig details.
As a part of resurrecting the network, a new CLI flag `--regnet` is
added to allow the RPC test harness connect to a running instance, the
areas of the code which involve votes have been modified to allow the
votes to apply to the new network, and tests have been added to the
relevant modules.
This bumps the affected module versions as follows:
- github.com/decred/dcrd/wire@v1.2.0
- github.com/decred/dcrd/chaincfg@v1.2.0
- github.com/decred/dcrd/dcrutil@v1.2.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
The blockchain module is also affected, but since its version has
already been bumped since the last release tag, it is not bumped again.
Finally, this does not include switching unit tests or the RPC test
harness over the new network since that will be done in a separate
commit.
This adds a new testnet3 network with new genesis block, block one
ledger, treasury address, and network magic.
All consensus rules that were voted in by testnet2 are automatically
active on the new testnet3 without having to vote them in again.
Consequently, there are no consensus vote agendas defined for it.
This modifies the logic which allows the reduction of difficulty on
testnet to match the upstream code such that after a block has not been
produced for a long period of time, as configured by the parameters, the
difficulty drops to the minimum allowed by the configured proof-of-work
limit for the network.
It should be noted that this would be a hard fork if the test network
had the code path enabled, however, since the code is disabled for
testnet2, it does not technically change the consensus rules for it.
The modified code will be active for testnet3.
This refactors and simplifies the code in blockchain to use the new more
efficient chain views.
An overview of the logic changes are as follows:
- Remove inMainChain from block nodes since that can now be efficiently
determined by using the chain view
- Track the best chain via a chain view instead of a single block node
- Use the tip of the best chain view everywhere bestNode was used
- Update chain view tip instead of updating best node
- Remove height map and associated lock in favor of chain view
- Use chain view NodeByHeight everywhere height map was used
- Change reorg logic to use more efficient chain view fork finding logic
- Change block locator code over to use more efficient chain view logic
- Remove now unused block-index-based block locator code
- Move BlockLocator definition to chain.go
- Move BlockLocatorFromHash and LatestBlockLocator to chain.go
- Update both to use more efficient chain view logic
- Rework several functions to use chain view for main chain detection
- fetchMainChainBlockByNode
- BlockByHeight
- MainChainHasBlock
- findPreviousCheckpoint
- IsCheckpointCandidate
This reworks the block index code such that it loads all of the headers
in the main chain at startup and constructs the full block index
accordingly.
Since the full index from the current best tip all the way back to the
genesis block is now guaranteed to be in memory, this also removes all
code related to dynamically loading the nodes and updates some of the
logic to take advantage of the fact traversing the block index can no
longer potentially fail. There are also many more optimizations and
simplifications that can be made in the future as a result of this.
Due to removing all of the extra overhead of tracking the dynamic state,
and ensuring the block node structs are aligned to eliminate extra
padding, the end result of a fully populated block index now takes quite
a bit less memory than the previous dynamically loaded version.
It also speeds up the initial startup process by roughly 2x since it is
faster to bulk load the nodes in order as opposed to dynamically loading
only the nodes near the tip in backwards order.
For example, here is some startup timing information before and after
this commit on a node that contains roughly 238,000 blocks:
7200 RPM HDD:
-------------
Startup time before this commit: ~7.71s
Startup time after this commit: ~3.47s
SSD:
----
Startup time before this commit: ~6.34s
Startup time after this commit: ~3.51s
Some additional benefits are:
- Since every block node is in memory, the code which reconstructs
headers from block nodes means that all headers can always be served
from memory which will be important since the network will be moving
to header-based semantics
- Several of the error paths can be removed since they are no longer
necessary
- It is no longer expensive to calculate CSV sequence locks or median
times of blocks way in the past
- It is much less expensive to calculate the initial states for the
various intervals such as the stake and voter version
- It will be possible to create much more efficient iteration and
simplified views of the overall index
An overview of the logic changes are as follows:
- Move AncestorNode from blockIndex to blockNode and greatly simplify
since it no longer has to deal with the possibility of dynamically
loading nodes and related failures
- Replace nodeAtHeightFromTopNode from BlockChain with RelativeAncestor
on blockNode and define it in terms of AncestorNode
- Move CalcPastMedianTime from blockIndex to blockNode and remove no
longer necessary test for nil
- Remove findNode and replace all of its uses with direct queries of the
block index
- Remove blockExists and replace all of its uses with direct queries of
the block index
- Remove all functions and fields related to dynamically loading nodes
- children and parentHash fields from blockNode
- depNodes from blockIndex
- loadBlockNode from blockIndex
- PrevNodeFromBlock from blockIndex
- {p,P}revNodeFromNode from blockIndex
- RemoveNode
- Replace all instances of iterating backwards through nodes to directly
access the parent now that nodes don't potentially need to be
dynamically loaded
- Introduce a lookupNode function on blockIndex which allows the
initialization code to locklessly query the index
- No longer take the chain lock when only access to the block index,
which has its own lock, is needed
- Removed the error paths from several functions that can no longer fail
- getReorganizeNodes
- findPrevTestNetDifficulty
- sumPurchasedTickets
- findStakeVersionPriorNode
- Removed all error paths related to node iteration that can no longer
fail
- Modify FetchUtxoView to return an empty view for the genesis block
Currently, the stake difficulty estimation function for algorithm
defined in DCP0001 only works with mainnet due to a limitation of only
working when the interval size is less than or equal to the ticket
maturity.
This generalizes the function to work with all values of interval size
and ticket maturity and adds a full suite of tests using the testnet
parameters to ensure proper functionality.
Of particular note is the case when the current height is before the
ticket maturity floor since that means some of the tickets being
estimated will mature during the interval and that there can be no
non-estimated immature tickets.
This also implies that, unlike when the ticket maturity is greater than
or equal to the interval size, the estimate may not exactly match the
real final value when given the exact same number of tickets to estimate
as real purchased tickets in the remainder of the interval depending on
whether or not the current height is before the ticket maturity floor.
This is the case because the number of real tickets that end up being
purchased before the maturity floor may not match the estimated
assumption of max tickets per block.
This modifies the newBlockNode function to accept the parent as an
argument to automatically connect the newly created node. When it is
not nil, the work sum will automatically be summed and the parent of the
new node will be set accordingly.
This simplifies the block node construction a bit and allows some
redundant code to be removed. It also paves the way for easier simpler
full block index construction in the future.
This separates the logic for populating the stake information in a block
node from the construction of the node in order to better delineate the
difference between the two and to pave the way for that information to
be stored separately in the database versus needing to load full blocks
to retrieve it.
This refactors the block index logic into a separate struct and
introduces an individual lock for it so it can be queried independent of
the chain lock.
It also modifies the `newBlockNode` function to accept nil for the
ticket spend information parameter and updates all of the test code that
doesn't require it to use nil.
This modifies the block node structure to include only the specifically
used fields, some of which in a more compact format, as opposed to
copying the entire header and updates all code and tests accordingly.
Not only is this a more efficient approach that helps pave the way for
future optimizations, it is also consistent with the upstream code which
helps minimize the differences to facilitate easier syncs due to less
merge conflicts.
In particular, since the merkle and stake roots, number of revocations,
size, nonce, and extradata fields aren't used currently, they are no
longer copied into the block node. Also, the block node already had a
height field, which is also in the header, so this change also removes
that duplication.
Another change is that the block node now stores the timestamp as an
int64 unix-style timestamp which is only 8 bytes versus the old
timestamp that was in the header which is a time.Time and thus 24 bytes.
It should be noted that future optimizations will very likely end up
adding most of the omitted header fields back to the block node as
individual fields so the headers can be efficiently reconstructed from
memory, however, these changes are still beneficial due to the ability
to decouple the block node storage format from the header struct which
allows more compact representations and reording of the fields for
optimal struct packing.
Ultimately, the need for the parent hash can also be removed, which will
save an additional 32 bytes which would not be possible without this
decoupling.
This modifies all files in the blockchain 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.
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
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.
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.
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.
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.
This moves several of the chain constants to the Params struct in the
chaincfg package which is intended for that purpose. This is mostly a
backport of the same modifications made in Decred along with a few
additional things cleaned up.
The following is an overview of the changes:
- Comment all fields in the Params struct definition
- Add locals to BlockChain instance for the calculated values based on
the provided chain params
- Rename the following param fields:
- SubsidyHalvingInterval -> SubsidyReductionInterval
- ResetMinDifficulty -> ReduceMinDifficulty
- Add new Param fields:
- CoinbaseMaturity
- TargetTimePerBlock
- TargetTimespan
- BlocksPerRetarget
- RetargetAdjustmentFactor
- MinDiffReductionTime
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
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.
The new RPC command estimatestakediff was added. It estimates the
minimum, maximum, and expected next stake difficulty. The caller can
also estimate a new difficulty given a passed number of tickets to be
mined in the remaining difficulty period.
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.
This commit converts all block height references to int32 instead of
int64. The current target block production rate is 10 mins per block
which means it will take roughly 40,800 years to reach the maximum
height an int32 affords. Even if the target rate were lowered to one
block per minute, it would still take roughly another 4,080 years to
reach the maximum.
In the mean time, there is no reason to use a larger type which results
in higher memory and disk space usage. However, for now, in order to
avoid having to reserialize a bunch of database information, the heights
are still serialized to the database as 8-byte uint64s.
This is being mainly being done in preparation for further upcoming
infrastructure changes which will use the smaller and more efficient
4-byte serialization in the database as well.
This commit contains three classes of optimizations:
- Reducing the number of unnecessary hash copies
- Improve the performance of the DoubleSha256 function
- A couple of minor optimizations of the ShaHash functions
The first class is a result of the Bytes function on a ShaHash making a
copy of the bytes before returning them. It really should have been named
CloneBytes, but that would break the API now.
To address this, a comment has been added to the function which explicitly
calls out the copy behavior. In addition, all call sites of .Bytes on a
ShaHash in the code base have been updated to simply slice the array when
a copy is not needed. This saves a significant amount of data copying.
The second optimization modifies the DoubleSha256 function to directly use
fastsha256.Sum256 instead of the hasher interface. This reduces the
number of allocations needed. A benchmark for the function has been added
as well.
old: BenchmarkDoubleSha256 500000 3691 ns/op 192 B/op 3 allocs/op
new: BenchmarkDoubleSha256 500000 3081 ns/op 32 B/op 1 allocs/op
The final optimizations are for the ShaHash IsEqual and SetBytes functions
which have been modified to make use of the fact the type is an array and
remove an unneeded subslice.
This commit contains the entire btcchain repository along with several
changes needed to move all of the files into the blockchain directory in
order to prepare it for merging. This does NOT update btcd or any of the
other packages to use the new location as that will be done separately.
- All import paths in the old btcchain test files have been changed to
the new location
- All references to btcchain as the package name have been changed to
blockchain