This updates the txscript module dependencies, the copyright year in the
files modified since the previous release, and serves as a base for
txscript/v4.0.0.
The updated direct dependencies in this commit are as follows:
- github.com/decred/dcrd/chaincfg/chainhash@v1.0.3
- github.com/decred/dcrd/chaincfg/v3@v3.1.0
- github.com/decred/dcrd/dcrec/edwards/v2@v2.0.2
- github.com/decred/dcrd/dcrec/secp256k1/v4@v4.0.1
- github.com/decred/dcrd/wire@v1.5.0
- github.com/decred/slog@v1.2.0
The full list of updated direct dependencies since the previous
txscript/v3.0.0 release are as follows:
- github.com/dchest/siphash@v1.2.2
- github.com/decred/base58@v1.0.3
- github.com/decred/dcrd/chaincfg/chainhash@v1.0.3
- github.com/decred/dcrd/chaincfg/v3@v3.1.0
- github.com/decred/dcrd/crypto/blake256@v1.0.0
- github.com/decred/dcrd/dcrec/edwards/v2@v2.0.2
- github.com/decred/dcrd/dcrec/secp256k1/v4@v4.0.1
- github.com/decred/dcrd/wire@v1.5.0
- github.com/decred/slog@v1.2.0
The following direct dependencies are no longer required as compared to
the previous txscript/v3.0.0 release:
- github.com/decred/dcrd/dcrutil/v3
Finally, all modules in the repository that depend on txscript are
tidied to ensure they are updated to use the latest versions hoisted
forward as a result.
This adds support for determining the number of signatures required by a
given script version and script for the known standard types along with
an implementation for version 0 scripts.
Full test coverage is included.
This moves the GenerateSSGenVotes method to script.go since it is used
in consensus code and therefore should not be in standard.go which is
only intended for standardness code.
It also moves the associated test to script_test.go to match and does
some other misc cleanup such as improving the comments and tests for
consistency.
This moves the GenerateSSGenBlockRef method to script.go since it is
used in consensus code and therefore should not be in standard.go which
is only intended for standardness code.
It also moves the associated test to script_test.go to match and does
some other misc cleanup such as improving the comments and tests for
consistency.
This moves the ContainsStakeOpCodes method to script.go since it is used
in consensus code and therefore should not be in standard.go which is
only intended for standardness code.
This is based on https://proposals.decred.org/proposals/c96290a but was
modified in order to deal with realities that were unknown at the time
of the specification draft.
It is large and could not really be broken apart due to the pervasive
use of the isTreasuryEnabled flag. It was primarily authored by
* Marco Peereboom <marco@peereboom.us>
* Dave Collins <davec@conformal.com>
* Matheus Degiovani <opensource@matheusd.com>
With additional contributions from
* Donald Adu-Poku <donald.adu@gmail.com>
* Jamie Holdstock <jholdstock@decred.org>
Major changes:
* Add decentralized treasury agenda, as specified in DCP0006, to all supported
nets.
* Add functions to determine if the decentralized treasury agenda is active at
given block.
* Add new opcode OP_TADD that is a nop in txscript but is used to tag scripts
that credit the treasury account. This opcode is overloaded for treasurybase
and for normal transactions.
* Add new opcode OP_TSPEND that is a nop in txscript but is used to tag scripts
that debit the treasury account.
* Add new opcode OP_TGEN that is a nop in txscript but is used to tag P2PKH and
P2SH outputs in a TSpend transaction.
* Add functions that detect if a transaction is a valid TAdd, TSpend
or treasurybase transaction.
* Add error codes that return specific treasurybase/TAdd/TSpend consensus
violations.
* Modify countSpentOutputs to deal with treasury opcodes accordingly.
* Modify indexBlock to skip treasury transactions that do not have inputs.
* Add IsTreasuryEnabled call to ChainQueryer interface.
* Add treasury logger for debugging and logging the decentralized treasury
subsystem.
* Add IsTreasuryActive flag to BlockConnectedNtfnsData and
BlockDisconnectedNtfnsData.
* Modify OP_SSGEN to allow an optional output that contains votes for a TSpend
transaction hash.
* Add function that returns TSpend votes from an SSGen transaction.
* Modify CalcStakeVoteSubsidy so that treasurybase, unlike coinbase, is always
awarded the full percentage of the assigned block reward.
* Add helper functions to do all TSpend math so that callers don't roll their
own.
* Modify IsCoinBaseTx to not mistake a TSpend transaction as a coinbase.
* Add checkTreasuryBase function that verifies that a treasurybase is properly
constructed and pays the right amount to the treasury account.
* Add functions to calculate treasury balance for the provided block hash/node.
* Add function that verifies if a TSpend has a valid signature.
* Add functions to determine if a TSpend is not overspending.
* Add function to determine if a TSpend has been mined on the provided chain.
* Add functions that count and verifies treasury spend votes.
* Modify connectTransaction and disconnectTransactions to deal with the various
treasury transactions.
* Split CheckTransactionSanity in two functions
checkTransactionSanityContextFree and checkTransactionSanityContextual. This
is done in order to keep the decentralized treasury, which is always
contextual, from infecting the context free checks.
* Modify checkTransactionSanityContextual to recognize and verify treasury
transactions.
* Modify CheckTransactionSanity to deal with treasury transactions.
* Split checkBlockSanity in two functions checkBlockSanityContextFree and
checkBlockSanityContextual. This is done in order to keep the decentralized
treasury, which is always contextual, from infecting the context free checks.
* Modify checkBlockSanityContextual to enforce treasurybase and TAdd consensus
checks.
* Modify checkBlockPositional by unindenting it and adding TSpend consensus
enforcement.
* Modify checkCoinbaseUniqueHeightWithAddress to deal with the removal of the
project subsidy from output 0.
* Add checkCoinbaseUniqueHeightWithTreasuryBase that verifies coinbase and
treasurybase in the provided block.
* Unindent checkBlockContext.
* Modify checkTicketRedeemerCommitments and checkVoteInputs to deal with
potential tspend votes.
* Modify CheckTransactionInputs to skip treasurybase transactions.
* Modify CheckTransactionInputs to deal with TSpend transactions. Ensure the
provided Pi key is valid and that the signature is valid for the transaction.
Ensure that treasury TAdd and TSpend transaction utxo can only be spent after
coinbase maturity.
* Modify CountSigOps to deal with treasury transactions.
* Modify CountP2SHSigOps to deal with treasury transactions.
* Modify getStakeTreeFees to skip treasury transactions. Modify
totalOutputs to subtract ValueIn 0 for TSpend and treasurybase transactions.
* Modify checkTransactionsAndConnect to deal with modified amounts.
* Add tspendChecks function that verifies an entire TSpend transaction
validity at the point of the provided block. It ensures a TSpend is on a TVI.
It ensures the TSpend is in the valid window. It verifies that a TSpend In
and Out amounts match. It ensures a TSpend has the ValueIn amount encoded in
the OP_RETURN in Out 0. It ensures a TSpend has not been mined before on this
chain. It ensures a TSpend has the requisite votes. It ensures a TSpend is
not overspending.
* Modify checkConnectBlock to call checkTreasuryBase and tspendChecks when
treasury agenda is active.
* Add two tables to the database. Table "treasury" records the balance as of
this block and balance changes that occurred in this block which will become
active in CoinbaseMaturity blocks. Table "tspend" records all block hashes
where a TSpend has been mined this is to detect forks and prevent a Tspend
from being mined more than once.
* Modify handleBlockchainNotification to communicate if the treasury agenda is
active and skip treasurybase transaction when needed.
* Add various Treasury parameters to chaincfg params.
* Add hardcoded Tspend signatures in dcr_tmux_simnet_setup.sh.
* Add notifytspend and stoptspend calls to the RPC server. notifytspend
notifies the mempool when a TSpend transaction arrives.
* Modify commit filters V2 to recognize TAdd and TSpend transactions. It was
possible to modify V2 instead of introducing V3 because nothing changes from
the viewpoint of the wallet and treasury opcodes are disallowed prior to
agenda activation.
* Modify AddMemPoolTransaction to skip TSpend transactions that would throw the
fee estimator off.
* Add IsTreasuryAgendaActive, OnTSpendReceived and TSpendMinedOnAncestor to
mempool.Config in order to reject/accept TSpends in the mempool.
* Modify checkPoolDoubleSpend to ignore treasurybase.
* Modify mempool.maybeAcceptTransaction to enforce treasury standardness rules.
Don't allow TSpend transactions prior to stake validation height. Skip
treasurybase and tspend transactions in the orphan test. Ensure a tspend is
in a valid window. Ensure not more than 7 TSpends are active in the mempool.
Ensure TSpend has a well-known Pi key. Ensure The provided Pi key was used to
sign the transaction. Ensure TSpend was not mined in an ancestor block.
Notify subscribers that a valid TSpend was received.
* Add standardCoinbaseOpReturn and standardTreasurybaseOpReturn to create an
OP_RETURN followed by a data push that little endian encodes the height of
the block. Then there are a number of random bytes to ensure that the
transaction hash is always random.
* Modify createCoinbaseTx to create a coinbase that is valid when treasury is
enabled or not. Additionally, alter the transaction version if treasury is
enabled.
* Add createTreasuryBaseTx that creates a standard treasurybase.
* Modify maybeInsertStakeTx to recognize treasurybase and TSpend transactions.
* Modify handleTooFewVoters to call createTreasuryBaseTx when the treasury
agenda is active. Skip copying treasurybase.
* Modify NewBlockTemplate to recognize and deal with treasury transactions.
Skip TSpend transaction if block is not a TVI. Skip TSpend transaction if it
is not in the proper window. Skip TSpend transaction if a TSpend does not
have enough yes votes. Skip TSpend transaction if it overspends the treasury
account. Skip TAdd if there are more than 20 TAdds in the block. Create
treasurybase if required. Insert valid TAdd/TSpend transactions into stake
tree.
* Add TreasuryBalance and IsTreasuryAgendaActive to rpcserver Chain interface.
* Add gettreasurybalance, sendfromtreasury and sendtotreasury calls to RPC
server.
* Add notifytspend and stopnotifytspend to RPC websocket commands.
* Add simnet miner to generate large number of blocks during rpctests without
triggering PoW difficulty increases. This is used to verify various treasury
and tspend conditions during CI/CT.
* Modify RPC voting wallet to also vote on TSpends.
* Add json tests to verify all new opcodes and corner cases in the script
engine.
* Modify isStakeOpcode to recognize treasury opcodes.
* Modify countSigOpsV0 to count TSpends.
* Modify handleStakeOutSign to deal with TSpends.
* Modify SignTxOutput to recognize TSpends.
* Add TSpendSignatureScript that signs a TSpend transaction.
* Add TreasuryAddTy and TreasurySpendTy types to the standard scripts.
* Add isTreasuryAddScript and isTreasurySpendScript functions that recognize
a form of TAdd and TSpend transactions.
* Modify ExtractPkScriptAddrs to deal with TAdd and TSpend outputs.
* Add TxVersionSeqLock = 2 and TxVersionTreasury = 3 to wire. This is
used to discriminate between treasury and non-treasury scripts.
* Rig up all functions that need the isTreasuryEnabledflag directly or
indirectly.
* Shuffle various functions around and export them when they were needed to be
called from other packages.
* Added and modified numerous tests to verify (hopefully) all corner cases that
the decentralized treasury agenda has added.
This exports the ExtractScriptHash function which extracts the script
hash from the passed script if it is a standard pay-to-script-hash
script or nil when it is not.
This modifies the consensus critical function which determines if the
redeem script of a p2sh or stake-tagged p2sh contains stake opcodes to
avoid calling the GetScriptClass function which is only intended
explicitly for working with standard script forms which only apply in
the context of the more restrictive standardness policy rules.
It also renames the function to better indicate its purpose is to
specifically check the redeem script as opposed to the entire signature
script.
This introduces a new function named removeOpcodeByDataRaw which accepts
the raw scripts and data to remove versus requiring the parsed opcodes
to both significantly optimize it as well as make it more flexible for
working with raw scripts.
There are several places in the rest of the code that currently only
have access to the parsed opcodes, so this only introduces the function
for use in the future and deprecates the existing one.
Note that, in practice, the script will never actually contain the data
that is intended to be removed since the function is only used during
signature verification to remove the signature itself which would
require some incredibly non-standard code to create.
Thus, as an optimization, it avoids allocating a new script unless there
is actually a match that needs to be removed.
Finally, it updates the tests to use the new function.
This renames the canonicalPush function to isCanonicalPush and converts
it to accept an opcode as a byte and the associate data as a byte slice
instead of the internal parse opcode data struct in order to make it
more flexible for raw script analysis.
It also updates all callers and tests accordingly.
This converts the IsUnspendable function to make use of a combination of
raw script analysis and the new tokenizer instead of the far less
efficient parseScript thereby significantly optimizing the function.
It is important to note that this new implementation intentionally has a
semantic difference from the existing implementation in that it will now
report scripts that are larger than the max allowed script size are
unspendable as well.
Finally, the comment is modified to explicitly call out the script
version semantics.
The following is a before and after comparison of analyzing a large
script:
benchmark old ns/op new ns/op delta
-----------------------------------------------------------
BenchmarkIsUnspendable 149899 860 -99.43%
benchmark old allocs new allocs delta
-----------------------------------------------------------
BenchmarkIsUnspendable 1 0 -100.00%
benchmark old bytes new bytes delta
-----------------------------------------------------------
BenchmarkIsUnspendable 466945 0 -100.00%
This converts the GetPreciseSigOpCount function to use a combination of
raw script analysis and the new tokenizer instead of the far less
efficient parseScript thereby significantly optimizing the function.
In particular it uses the recently converted isScriptHashScript,
IsPushOnlyScript, and countSigOpsV0 functions along with the recently
added finalOpcodeData functions.
It also modifies the comment to explicitly call out the script version
semantics.
The following is a before and after comparison of analyzing a large
script:
benchmark old ns/op new ns/op delta
------------------------------------------------------------------
BenchmarkGetPreciseSigOpCount 287939 1077 -99.63%
benchmark old allocs new allocs delta
------------------------------------------------------------------
BenchmarkGetPreciseSigOpCount 3 0 -100.00%
benchmark old bytes new bytes delta
------------------------------------------------------------------
BenchmarkGetPreciseSigOpCount 934657 0 -100.00%
This converts the IsPushOnlyScript function to make use of the new
tokenizer instead of the far less efficient parseScript thereby
significantly optimizing the function.
It also deprecates the isPushOnly function that requires opcodes in
favor of the new function and modifies the comment on IsPushOnlyScript
to explicitly call out the script version semantics.
The following is a before and after comparison of analyzing a large
script:
benchmark old ns/op new ns/op delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 139961 0.66 -100.00%
benchmark old allocs new allocs delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 1 0 -100.00%
benchmark old bytes new bytes delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 466944 0 -100.00%
This converts the isAnyKindOfScriptHash function to analyze the raw
script instead of requiring far less efficient parsed opcodes thereby
significantly optimizing the function.
Since the function relies on isStakeScriptHash to identify a stake
tagged pay-to-script-hash, and is the only consumer of it, this also
converts that function to analyze the raw script and renames it to
isStakeScriptHashScript for more consistent naming.
Finally, the tests are updated accordingly.
The following is a before and after comparison of analyzing a large
script:
benchmark old ns/op new ns/op delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash 101249 3.83 -100.00%
benchmark old allocs new allocs delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash 1 0 -100.00%
benchmark old bytes new bytes delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash 466944 0 -100.00%
This converts the GetSigOpCount function to make use of the new
tokenizer instead of the far less efficient parseScript thereby
significantly optimizing the function.
A new function named countSigOpsV0 which accepts the raw script is
introduced to perform the bulk of the work so it can be reused for
precise signature operation counting as well in a later commit. It
retains the same semantics in terms of counting the number of signature
operations either up to the first parse error or the end of the script
in the case it parses successfully as required by consensus.
Finally, this also deprecates the getSigOpCount function that requires
opcodes in favor of the new function and modifies the comment on
GetSigOpCount to explicitly call out the script version semantics.
The following is a before and after comparison of analyzing a large
script:
benchmark old ns/op new ns/op delta
-----------------------------------------------------------
BenchmarkGetSigOpCount 163896 1048 -99.36%
benchmark old allocs new allocs delta
-----------------------------------------------------------
BenchmarkGetSigOpCount 1 0 -100.00%
benchmark old bytes new bytes delta
-----------------------------------------------------------
BenchmarkGetSigOpCount 466945 0 -100.00%
This converts the IsMultisigSigScript function to analyze the raw script
and make use of the new tokenizer instead of the far less efficient
parseScript thereby significantly optimizing the function.
In order to accomplish this, it first rejects scripts that can't
possibly fit the bill due to the final byte of what would be the redeem
script not being the appropriate opcode or the overall script not having
enough bytes. Then, it uses a new function that is introduced named
finalOpcodeData that uses the tokenizer to return any data associated
with the final opcode in the signature script (which will be nil for
non-push opcodes or if the script fails to parse) and analyzes it as if
it were a redeem script when it is non nil.
It is also worth noting that this new implementation intentionally has
the same semantic difference from the existing implementation as the
updated IsMultisigScript function in regards to allowing zero pubkeys
whereas previously it incorrectly required at least one pubkey.
Finally, the comment is modified to explicitly call out the script
version semantics.
The following is a before and after comparison of analyzing a large
script that is not a multisig script and both a 1-of-2 multisig public
key script (which should be false) and a signature script comprised of a
pay-to-script-hash 1-of-2 multisig redeem script (which should be true):
benchmark old ns/op new ns/op delta
-----------------------------------------------------------------------
BenchmarkIsMultisigSigScriptLarge 158149 4 -100.00%
BenchmarkIsMultisigSigScript 3445 202 -94.14%
benchmark old allocs new allocs delta
-----------------------------------------------------------------------
BenchmarkIsMultisigSigScriptLarge 9 0 -100.00%
BenchmarkIsMultisigSigScript 3 0 -100.00%
benchmark old bytes new bytes delta
-----------------------------------------------------------------------
BenchmarkIsMultisigSigScriptLarge 533189 0 -100.00%
BenchmarkIsMultisigSigScript 9472 0 -100.00%
This converts the IsPayToScriptHash function to analyze the raw script
instead of using the far less efficient parseScript thereby
significantly optimizing the function.
In order to accomplish this, it introduces two new functions. The first
one is named extractScriptHash and works with the raw script bytes to
simultaneously determine if the script is a p2sh script, and in the case
it is, extract and return the hash. The second new function is named
isScriptHashScript and is defined in terms of the former.
The extract function approach was chosen because it is common for
callers to want to only extract relevant details from a script if the
script is of the specific type. Extracting those details requires
performing the exact same checks to ensure the script is of the correct
type, so it is more efficient to combine the two into one and define the
type determination in terms of the result so long as the extraction does
not require allocations.
Finally, this also deprecates the isScriptHash function that requires
opcodes in favor of the new functions and modifies the comment on
IsPayToScriptHash to explicitly call out the script version semantics.
The following is a before and after comparison of analyzing a large
script that is not a p2sh script:
benchmark old ns/op new ns/op delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 139961 0.66 -100.00%
benchmark old allocs new allocs delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 1 0 -100.00%
benchmark old bytes new bytes delta
---------------------------------------------------------------
BenchmarkIsPayToScriptHash 466944 0 -100.00%
This converts the isStakeOpcode function to accept an opcode as a byte
instead of the internal opcode data struct in order to make it more
flexible for raw script analysis.
It also updates all callers accordingly.
This converts the asSmallInt function to accept an opcode as a byte
instead of the internal opcode data struct in order to make it more
flexible for raw script analysis.
It also updates all callers accordingly.
This converts the isSmallInt function to accept an opcode as a byte
instead of the internal opcode data struct in order to make it more
flexible for raw script analysis.
The comment is modified to explicitly call out the script version
semantics.
Finally, it updates all callers accordingly.
This modifies the CalcSignatureHash function to make use of the new
signature hash calculation function that accepts raw scripts without
needing to first parse them. Consequently, it also doubles as a slight
optimization to the execution time and a significant reduction in the
number of allocations.
In order to convert the CalcScriptHash function and keep the same
semantics, a new function named checkScriptParses is introduced which
will quickly determine if a script can be fully parsed without failure
and return the parse failure in the case it can't.
The following is a before and after comparison of analyzing a large
multiple input transaction:
benchmark old ns/op new ns/op delta
-------------------------------------------------------
BenchmarkCalcSigHash 2792057 2760042 -1.15%
benchmark old allocs new allocs delta
-------------------------------------------------------
BenchmarkCalcSigHash 1691 1068 -36.84%
benchmark old bytes new bytes delta
-------------------------------------------------------
BenchmarkCalcSigHash 521673 438604 -15.92%
This introduces a new function named calcSignatureHashRaw which accepts
the raw script bytes to calculate the script hash versus requiring the
parsed opcode only to unparse them later in order to make it more
flexible for working with raw scripts.
Since there are several places in the rest of the code that currently
only have access to the parsed opcodes, this modifies the existing
calcSignatureHash to first unparse the script before calling the new
function.
Note that the code in the signature hash calculation to remove all
instances of OP_CODESEPARATOR from the script is removed because that is
a holdover from BTC code which does not apply to v0 Decred scripts since
OP_CODESEPARATOR is completely disabled in Decred and thus there can
never actually be one in the script.
Finally, it removes the removeOpcode function and related tests since it
is no longer used.
This converts the DisasmString function to make use of the new
zero-allocation script tokenizer instead of the far less efficient
parseScript thereby significantly optimizing the function.
In order to facilitate this, the opcode disassembly functionality is
split into a separate function called disasmOpcode that accepts the
opcode struct and data independently as opposed to requiring a parsed
opcode. The new function also accepts a pointer to a string builder so
the disassembly can be more efficiently be built.
While here, the comment is modified to explicitly call out the script
version semantics.
The following is a before and after comparison of a large script:
benchmark old ns/op new ns/op delta
----------------------------------------------------------
BenchmarkDisasmString 288729 94157 -67.39%
benchmark old bytes new bytes delta
----------------------------------------------------------
BenchmarkDisasmString 584611 177528 -69.63%
This converts the majority of script errors from generic errors created
via errors.New and fmt.Errorf to use a concrete type that implements the
error interface with an error code and description.
This allows callers to programmatically detect the type of error via
type assertions and an error code while still allowing the errors to
provide more context.
For example, instead of just having an error the reads "disabled opcode"
as would happen prior to these changes when a disabled opcode is
encountered, the error will now read "attempt to execute disabled opcode
OP_FOO".
While it was previously possible to programmatically detect many errors
due to them being exported, they provided no additional context and
there were also various instances that were just returning errors
created on the spot which callers could not reliably detect without
resorting to looking at the actual error message, which is nearly always
bad practice.
Also, while here, export the MaxStackSize and MaxScriptSize constants
since they can be useful for consumers of the package and perform some
minor cleanup of some of the tests.
This slightly cleans up the handling for pay-to-script-hash scripts and
related stake opcode checking as follows:
- Move the isScriptHash and isAnyKindOfScriptHash functions to script.go
since they are required by consensus and therefore do not belong in
standard.go which is reserved for standardness only rules
- Introduce a new function named isStakeOpcode and use it throughout
versus repeating the specific logic in multiple places
- Use the stake opcode constants instead of magic numbers in the
aforementioned new function
- Introduce a new function named isStakeScriptHash which specifically
determines if a script is of the special stake p2sh form
- Update isAnyKindOfScriptHash to make use of the original isScriptHash
function instead of repeating the logic and the newly introduced
isStakeScriptHash function
This moves the logic to calculate the signature hash and the associated
test to separate files. Since there will ultimately be a new signature
algorithm, it makes sense to separate all logic related to signature
hashes for better code organization.
It contains no functional changes.
This modifies the exported CalcSignatureHash function to accept a script
as bytes instead of an array of parsed opcodes which are not available
to callers outside of the package.
While here, it also adds a proper comment for the exported function
since it is intended for more than testing as the previous comment
claimed.
Finally, it updates the tests to use a valid script instead of the
previous impossible to achieve constructed series of parsed opcodes.
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.
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 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.