This deprecates the GetMultisigMandN function which should never have
been added since the CalcMultiSigStats function already existed for this
purpose.
While here, redefine the function in terms of CalcMultiSigStats.
This function is only useful for internal consensus purposes within the
script engine and as such should not be exported.
While here, also add a comment to specify to the script version
semantics.
This adds the go 1.11 directive to all of the modules in order to
clearly mark they build and work with that version. Go 1.12 modified
the tools such that tidy will automatically add the new version to
modules that do not already have a directive and that would prevent
builds on Go 1.11 through Go 1.11.3 which is not desirable.
As is already well commented in the code, the sequence number parameter
of the CHECKSEQUENCEVERIFY opcode requires 5 bytes instead of the
standard 4 bytes allowed by math opcodes. This introduces a constant
for the value instead of hardcoding 5 to increase readability and
potentially allow the value to be exported in the future.
As is already well commented in the code, the locktime parameter of the
CHECKLOCKTIMEVERIFY opcode requires 5 bytes instead of the standard 4
bytes allowed by math opcodes. This introduces a constant for the value
instead of hardcoding 5 to increase readability and potentially allow
the value to be exported in the future.
This tightens the multisig and pay-to-pubkey standard script
identification functions to use the same strict pubkey requirements as
the consensus rules since standardness rules are generally intended to
be more restrictive than the consensus rules which implies they are at a
minimum at least as restrictive.
The tests are also updated to deal with the additional restriction
accordingly.
This introduces a new error named ErrCheckSigAltVerify and modifies the
opcodeCheckSigAltVerify handler to use the abstractVerify function along
with the new error. This makes the handling consistent with all other
signature checking verification opcode handlers and ensures the error
both can be programmatically detected as well as be uniquely identified
as compared to a generic verify failure.
This renames the flag that indicates whether or not the script engine is
executing a pay-to-script-hash script pair to a name that more
accurately describes its behavior.
An important (and easy for implementations to miss) aspect of the
CHECKSIG opcodes is that the full signature (signature plus hash type)
that is being checked is first removed from the script prior to
calculating the signature hash against which the signature is verified.
It appears the test in the upstream btcsuite code for this was removed
during the initial Decred port instead of being converted as it should
have been.
Consequently, this converts the relevant test so it is correct for
Decred and adds it to the reference tests. Note that the first of the
two added tests is to ensure the original signature is valid prior to
testing the actual removal condition.
This modifies all of the modules, with the exception of the root module,
to remove all replacement directives from their go.mod files and update
the requirements and module sums accordingly.
While it is nice to be able to build and test directly from each module
directory and have it pull in the latest untagged changes when
developing, having all of the overrides in each module makes it
infeasible to use the module tools to help maintain the modules and thus
makes it quite difficult to ensure they are all independently accurate
for external consumers.
By maintaining all of the overrides in the root module and invoking all
builds and tests from it, the overrides will apply to ensure the latest
code is being built and tested.
This also modifies the tests script used with in CI to run all of the
tests from the root module accordingly.
This bumps the various module versions as follows:
- github.com/decred/dcrd/dcrec/secp256k1@v1.0.1
- github.com/decred/dcrd/dcrjson@v1.1.0
- github.com/decred/dcrd/database@v1.0.3
- github.com/decred/dcrd/blockchain/stake@v1.1.0
- github.com/decred/dcrd/mining@v1.1.0
- github.com/decred/dcrd/certgen@v1.0.2
- github.com/decred/dcrd/connmgr@v1.0.2
- github.com/decred/dcrd/mempool@v1.1.0
In addition, it serves as a base for tagging releases of the following
module versions that have previous been bumped since the last release,
but not yet tagged:
- 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/txscript@v1.0.2
- github.com/decred/dcrd/blockchain@v1.1.0
- github.com/decred/dcrd/hdkeychain@v1.1.1
- github.com/decred/dcrd/peer@v1.1.0
- github.com/decred/dcrd/rpcclient@v1.1.0
Finally, it updates all of the dependencies for every module accordingly,
adds a few missing overrides for transitive dependencies, and tidies up
some of the go module sum files.
This modifies the majority of the tests that make use of chain
parameters and the RPC tests to use the resurrected regression test
network.
It also bumps the affected module versions as follows:
- github.com/decred/dcrd/txscript@v1.0.2
- github.com/decred/dcrd/blockchain/stake@v1.0.3
- github.com/decred/dcrd/mempool@v1.0.2
The blockchain and dcrutil modules are also affected, but since their
version has already been bumped since their last release tags, they are
not bumped again.
This bumps the various module versions as follows:
- github.com/decred/dcrd/addrmgr@v1.0.2
- github.com/decred/dcrd/wire@v1.1.0
- github.com/decred/dcrd/chaincfg@v1.1.1
- github.com/decred/dcrd/connmgr@v1.0.1
- github.com/decred/dcrd/dcrutil@v1.1.1
- github.com/decred/dcrd/database@v1.0.1
- github.com/decred/dcrd/hdkeychain@v1.1.0
- github.com/decred/dcrd/txscript@v1.0.1
- github.com/decred/dcrd/blockchain/stake@v1.0.1
- github.com/decred/dcrd/gcs@v1.0.1
- github.com/decred/dcrd/blockchain@v1.0.1
- github.com/decred/dcrd/mining@v1.0.1
- github.com/decred/dcrd/mempool@v1.0.1
- github.com/decred/dcrd/peer@v1.0.1
- github.com/decred/dcrd/rpcclient@v1.0.1
It also updates all of the dependencies for every module accordingly and
adds a few missing overrides for transitive dependencies.
This modifies the test code for several unit tests to prefer using
another network, such as mainnet or simnet, when not specifically
testing something that requires testnet.
In the cases where where testnet is required, it also now prefers a
local reference over directly accessing the testnet parameters directly
from the chaincfg package.
This is being done because the test network undergoes periodic resets
and by reducing the number of direct references, it simplifies the
process of resetting it.
This further refines the modules to add the following new modules
instead of depending on the entire dcrd module:
- github.com/decred/dcrd/dcrjson@v1.0.0
- github.com/decred/dcrd/blockchain@v1.0.0
- github.com/decred/dcrd/blockchain/stake@v1.0.0
- github.com/decred/dcrd/gcs@v1.0.0
- github.com/decred/dcrd/mining@v1.0.0
- github.com/decred/dcrd/mempool@v1.0.0
- github.com/decred/dcrd/peer@v1.0.0
- github.com/decred/dcrd/rpcclient@v1.0.0
Also, it ensures modules that rely on other modules within the repo are
provided replacements to the latest repo code to ensure builds against
master and continuous integration use the latest code.
- github.com/decred/dcrd/addrmgr
- github.com/decred/dcrd/blockchain
- github.com/decred/dcrd/blockchain/stake
- github.com/decred/dcrd/chaincfg
- github.com/decred/dcrd/connmgr
- github.com/decred/dcrd/database
- github.com/decred/dcrd/dcrec/secp256k1
- github.com/decred/dcrd/dcrjson
- github.com/decred/dcrd/dcrutil
- github.com/decred/dcrd/gcs
- github.com/decred/dcrd/hdkeychain
- github.com/decred/dcrd/mempool
- github.com/decred/dcrd/mining
- github.com/decred/dcrd/peer
- github.com/decred/dcrd/rpcclient
- github.com/decred/dcrd/txscript
- github.com/decred/dcrd/wire
Now that the chaincfg, chainhash, dcrec, edwards, secp256k1, dcrutil,
wire, and slog modules have been defined, update the txscript module to
only depend on them instead of the entire dcrd module.
This removes the unused curve parameter from the ParseSignature and
ParseDERSignature functions of the secp256k1 package and updates all
callers in the repository accordingly.
This modifies the PeekInt function of the stack to accept a maximum
script number length to mirror PopInt for consistency. It also updates
the two callers CLTV and CSV) which were manually performing the same
task with 5 bytes due to PeekInt enforcing 4-byte script nums to use the
modified version accordingly.
It also adds some stack tests for 5-byte encodings on both PopInt and
PeekInt.
This removes the flag to require minimal encoding when create script
numbers since since all callers now call the function with true due to
the recent removal of the minimal data script verification flag from the
script engine and updates the tests accordingly.
This removes the MINIMALDATA script verify flag from the various
reference test data since it is now a noop due to the corresponding flag
being removed from the script engine.
This removes the ScriptVerifyMinimalData flag from the txscript package,
changes the default semantics to always enforce its behavior, and
updates all callers in the repository accordingly.
This change is being made to simplify the script engine code since the
flag has always been active and required by consensus in Decred, so
there is no need to require a flag to conditionally toggle it.
It should be noted that the tests removed from script_tests.json
specifically dealt with ensuring equivalency of different ways to encode
the same numbers when the ScriptVerifyMinimalData flag is not set.
Therefore, they are no longer necessary.
A few tests which dealt with equivalency that did not already have
expected failing counterparts were converted to expected failure.
Also, several of the tests which dealt with ensuring the specific
encoding of numeric opcodes is being used have been converted to use
hashes since the minimal data requirements specifically prevent
alternate ways of pushing the same encoding which is necessary for
directly checking equality of the raw bytes.
Finally, the MINIMALDATA indicator to enable the flag in the test data
has been retained for now in order to isolate the logic changes as much
as possible.
This removes the DERSIG script verify flag from the various reference
test data since it is now a noop due to the corresponding flag being
removed from the script engine.
This removes the ScriptVerifyDERSignatures flag from the txscript
package, changes the default semantics to always enforce its behavior
and updates all callers in the repository accordingly.
This change is being made to simplify the script engine code since the
flag has always been active and required by consensus in Decred, so
there is no need to require a flag to conditionally toggle it.
It should be noted that the tests removed from script_tests.json
specifically dealt with ensuring non-DER-compliant signatures were
handled properly when the ScriptVerifyDERSignatures flag was not set.
Therefore, they are no longer necessary.
Finally, the DERSIG indicator to enable the flag in the test data has
been retained for now in order to keep the logic changes separate.
This removes the P2SH script verify flag from the various reference test
data since it is now a noop due to the corresponding flag being removed
from the script engine.
This removes the ScriptBip16 flag from the txscript package, changes the
default semantics to always enforce its behavior, and updates all
callers in the repository accordingly.
This change is being made to simplify the script engine code since the
flag has always been active and required by consensus in Decred, so there is
no need to require a flag to conditionally toggle it.
Also, since it is no longer possible to invoke the script engine without
the flag with the clean stack flag, it removes the now unused
ErrInvalidFlags error and associated tests.
It should be noted that the test removed from script_tests.json
specifically dealt with ensuring a signature script that contained
non-data-pushing opcodes was successful when neither the ScriptBip16 or
ScriptVerifySigPushOnly flags were set. Therefore, it is no longer
necessary.
Finally, the P2SH indicator to enable the flag in the test data has been
retained for now in order to keep the logic changes separate.
This updates the data driven transaction script tests to combine the
previously separate valid and invalid test data files into a single file
and adds a field for the expected result. This is a nice improvement
since it means tests can now ensure script failures are due to a
specific expected reason as opposed to only generically detecting
failure as the previous format required.
Since it is possible that the script engine might return more fine
grained errors than that test data expects, the test adapter handles
this by allowing expected errors in the test data to be mapped to
multiple txscript errors.
While performing the conversion, it also adds several tests for the
following areas:
- The test harness itself to ensure the parsing logic, particularly for
the recently added repetition syntax, is working as intended
- All of the opcodes which were converted to NOPs in Decred
to ensure they are also discouraged from use
- All of the reserved opcodes in Decred
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 cleans up the code for handling the checksig and checkmultisig
opcodes to explicitly call out any semantics that are likely not
obvious, correct some comments, and improve readability.
It also adds several tests to the reference script tests which exercise
the semantics of the check[multi]sig opcodes including both positive and
negative tests.
Finally, it corrects nearly all of the negative tests related to
signature checking of the script tests which were not properly updated
for the differences introduced by Decred so that they fail for the
intended reasons.
The malformed signatures in the tests were very carefully crafted to be
valid except for the very specific condition being tested. The majority
of the negative tests modified and added can be manually verified by
commenting out the relevant checks in the script engine, although a few
of them will pass because they fail for other reasons. In those cases,
prints can be added to ensure the expected failure path is being hit.
This removes the STRICTENC script verify flag from the various test data
since it is now a noop due to the corresponding flag being removed from
the script engine.
This removes the ScriptVerifyStrictEncoding flag from the txscript
package, changes the default semantics to always enforce its behavior
and updates all callers in the repository accordingly.
This change is being made to simplify the script engine code since the
flag has always been active and required by consensus in Decred, so
there is no need to require a flag to conditionally toggle it.
It should be noted that the tests removed from script_valid.json
specifically dealt with ensuring signatures not compliant with DER
encoding did not cause execution to halt early on invalid signatures
when neither of the ScriptVerifyStrictEncoding or
ScriptVerifyDERSignatures flags were set. Therefore, they are no longer
necessary.
For nearly the same reason, the tx test related to the empty pubkey
tx_valid.json was moved to tx_invalid.json. In particular, an empty
pubkey without ScriptVerifyStrictEncoding simply failed the signature
check and continued execution, while the same condition with the flag
halts execution. Thus, without the flag the final NOT in the script
would allow the script to succeed, while it does not under the strict
encoding rules.
Finally, the STRICTENC indicator to enable the flag in the test data has
been retained for now in order to keep the logic changes separate.
This removes the SigHashOld definition from the txscript package since
it both has never been used in Decred and it has also always been
invalid to use due to the fact that strict encoding has always been
active and required by consensus in Decred.
This removes the ScriptVerifyLowS flag from the txscript package,
changes the default semantics to always enforce its behavior and updates
all callers in the repository accordingly.
This change is being made to simplify the script engine code since the
flag has always been active and required by consensus in Decred, so
there is no need to require a flag to conditionally toggle it.
This corrects some of the script tests which were not properly updated
for the differences introduced by Decred as well as adds some additional
tests for some updated semantics.
Namely:
- Correct the redeem script hash of several tests so they fail for the
intended reason instead of due to having an invalid script hash
- Correct multisig tests to remove the dummy parameter which is not
needed by Decred
- Change the tests for previously reserved opcodes to discouraged
upgradable NOP tests to match their new semantics
- Add tests to ensure all discourage NOPs are allowed when in an
unexecuted branch
- Add tests to ensure all reserved opcodes that are not always illegal
are allowed when in an unexecuted branch
This expands upon the recently added ability to specify repeated
raw and quoted data in the test data short script form syntax to also
add syntax to allow repeated sequences of opcodes and updates several
tests to make use of it.
While here, it also corrects a few tests to actually test what they were
originally intended to test but were not updated correctly for Decred
limit changes. In particular, the following tests were corrected:
- The negative test that ensures exceeding the max opcode limit via
CHECKMULTISIG and CHECKMULTISIGVERIFY results in failure
- The positive test that ensures hitting the max opcode limit via
CHECKMULTISIG and CHECKMULTISIGVERIFY with and without keys succeeds
This improves the test data short script form syntax to allow repeated
raw and quoted data and updates several tests to make use of it.
While here, it also corrects a few tests to actually test what they were
originally intended to test but were not updated correctly for Decred
limit changes. In particular, the following tests were corrected:
- The negative test that ensures to exceeding the maximum allowed script
size results in failure
- The positive test that ensures a fully maxed out script (max script
size, max element size push, max opcodes, and max stack items)
succeeds
- The positive test that ensures OP_RESERVED does not count towards the
opcode limit
This cleans up the code for handling the mod opcode to explicitly call
out its semantics which are likely not otherwise obvious as well as
improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the div opcode including both positive and negative
tests.
This cleans up the code for handling the div opcode to explicitly call
out its semantics which are likely not otherwise obvious as well as
improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the div opcode including both positive and negative
tests.
This cleans up the code for handling the right shift opcode to
explicitly call out its semantics which are likely not otherwise obvious
as well as improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the right shift opcode including both positive and
negative tests.
This cleans up the code for handling the left shift opcode to explicitly
call out its semantics which are likely not otherwise obvious as well as
improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the left shift opcode including both positive and
negative tests.
This cleans up the code for handling the left rotation opcode to
explicitly call out its semantics which are likely not otherwise obvious
as well as improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the left rotation opcode including both positive and
negative tests.
This cleans up the code for handling the right rotation opcode to
explicitly call out its semantics which are likely not otherwise obvious
as well as improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the right rotation opcode including both positive and
negative tests.
This cleans up the code for handling the cat opcode to more closely
match the style used by the rest of the code and improves its test
coverage by adding several tests to the reference script tests which
exercise its semantics including both positive and negative tests.
This cleans up the code for handling the right opcode to explicitly call
out its semantics which are likely not otherwise obvious as well as
improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the right opcode including both positive and negative
tests.
This cleans up the code for handling the left opcode to explicitly call
out its semantics which are likely not otherwise obvious as well as
improve its readability.
It also adds several tests to the reference script tests which exercise
the semantics of the left opcode including both positive and negative
tests.
This cleans up the code for handling the substr opcode to explicitly
call out its semantics which are likely not otherwise obvious as well as
improve its readability.
This adds module support for the versioned go toolchain. In particular,
the following packages are defined as modules:
* addrmgr
* blockchain
* certgen
* chaincfg
* connmgr
* database
* dcrjson
* dcrutil
* gcs
* hdkeychain
* mempool
* mining
* peer
* rpcclient
* txscript
* wire
It does not update the travis build environment or README since it is
experimental at this point.
This modifies all packages within the repository to the use the Decred
fork of btclog which has been renamed to slog and updates the dependency
files accordingly.
This removes the ScriptStrictMultiSig flag from the txscript package
since it is not used or needed by Decred.
The flag is a holdover from the upstream code which was used to address
a bug that does not exist in Decred.
Standardness rules are not the same as consensus rules and it is
important to keep clear separation between them, because standardness
rules can and do change, while the consensus rules must not change
without a specific vote, and even then, the old rules must be kept
around for validation of all blocks prior to any changes introduced by a
successful vote.
Prior to this commit, the blockchain code which enforces the consensus
rule that requires the second output of the coinbase transaction to
contain the height of the block in a provably pruneable nulldata script
push was relying on code in txscript/standard.go, which, as the name of
the file suggests, is specifically intended for code related to
standardness checks.
This introduces a new function in the txscript package named
ExtractCoinbaseNullData which does not rely on any of the code related
to standardness checks and modifies the blockchain code accordingly to
make use of the new function instead. It also removes the
standardness-dependent GetNullDataContent function which is no longer
used by anything.
Finally, it adds tests in the txscript package to ensure the new
function has the required semantics.
This modifies the signature hash calculation logic to completely
decouple it from the wire transaction serialization and significantly
optimizes it in the process. It also significantly improves the
comments to specifically call out the semantics.
This change is highly desirable because it has several beneficial
properties:
- The signature hash semantics are much clearer and specific
- There is no longer a need to copy the entire transaction and modify
the relevant portions since the necessary substitutions are made on
the fly
- Allows much faster calculation by serializing directly into byte
slices and avoiding all of the additional error handling logic
dedicated to handling network streams
- Provides the possibility of changing the wire format without breaking
signature hash calculation
- Note that the caching portion still relies on the wire format, but
that can be addressed in future commits since it is merely an
optimization that can also be decoupled
The following is a before and after comparison of signature hash
calculation for both speed and memory allocations for a transaction with
many inputs:
benchmark old ns/op new ns/op delta
------------------------------------------------------------
BenchmarkCalcSigHash 6299714 1551740 -75.37%
benchmark old allocs new allocs delta
------------------------------------------------------------
BenchmarkCalcSigHash 18601 1691 -90.91%
This updates the recently-added JSON-based signature hash test data to
actually test the SigHashAnyOneCanPay flag in the non-fuzzer
transactions as intended.
The flag is 0x80, but the JSON test data specifies the signature hash
type in decimal, so SigHashAll|SigHashAnyOneCanPay, which is 0x81,
should've been specified as 129 decimal instead of 81 decimal. The same
applies to all combinations with the SigHashAnyOneCanPay flag.
This adds a significant number of JSON-based tests with various
transactions, scripts, and hash types, to ensure the signature hash
calculated generates the expected hash in each case.
It specifically tests some specialized transactions such as coinbase,
ticket purchase, vote, and revocation. It also includes carefully
created tests for all combinations of defined hash types along with
triggering an error due to improper use of SigHashSingle.
Finally, it also includes fuzz testing by providing a selection of 100
regular transactions with various numbers of inputs and outputs along
with randomly generated (including undefined) signature hash types and
input indexes. Due to the way that masking of the signature hash type
works, a couple of the fuzzer tests also hit the improper use of
SigHashSingle.
The test data was generated as JSON in order to make it easier for
developers of software in other languages and platforms that need to
deal with generating signature hashes to consume and prove correctness
of their implementation as well.
Putting the test code in the same package makes it easier for forks
since they don't have to change the import paths as much and it also
gets rid of the need for internal_test.go to bridge.
Also, do some light cleanup on a few tests while here.
This removes the SigHashAllValue signature hash type. This is being
done because it is not currently usable without a consensus change due
to a consensus rule which enforces strict signature encoding disallowing
the hash type.
While it would be possible to change the consensus rule in question to
include SigHashAllValue, that would obviously require a consensus vote
since it constitutes a change to the consensus rules. Given that a vote
is required to make any changes in regards to this, it is ideal to
completely change the algorithm altogether to not only address this
issue, but also to address other shortcomings in regards to efficiency
and complexity of the current algorithm in addition to committing to all
input amounts per the aforementioned description.
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 is a follow-up to a previous change which removed the ability to
create a dcrutil.Address from a hybrid pubkey. It removes all
secp256k1 hybrid pubkey support from the chainec/dcrec packages since
these pubkeys are not usable when evaluated by OP_CHECKSIG or
OP_CHECKMULTISIG.
While ParsePubKey is called by consensus code and its behavior has
been changed to error when encountering a hybrid secp256k1 pubkey,
this is not a consensus change as every use of ParsePubKey in
consensus code either checks beforehand that the pubkey is compressed
or uncompressed, requires a parsed address to be P2PKH or P2SH, or
checks an address string against the premine ledger (which only
contains P2PKH addresses).
This modifies the recently-added NullDataScript function in several
ways in an effort to make them more consistent with the tests in the
rest of the code base and improve/correct the logic:
- Use the hexToBytes and mustParseShortForm functions
- Consistently format the test errors
- Replace the valid bool flag with an expected error and test against it
- Ensure the returned script type is the expected type in all cases
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.
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.
This modifies the script engine to replace OP_NOP3 with
OP_CHECKSEQUENCEVERIFY and adds a flag to selectively enable its
enforcement.
The new opcode examines the top item on the stack and compares it
against the sequence number of the associated transaction input in order
to allow scripts to conditionally enforce the inclusion of relative time
locks to the transaction.
The following is an overview of the changes:
- Introduce a new flag named ScriptVerifyCheckSequenceVerify to
provide conditional enforcement of the new opcode
- Introduce a constant named OP_CHECKSEQUENCEVERIFY which has the same
value as OP_NOP3 since it is replacing it
- Update opcode to name mappings accordingly
- Abstract the logic that deals with time lock verification since it is
the same for both the new opcode and OP_CHECKLOCKTIMEVERIFY
- Implement the required opcode semantics
- Add tests to ensure the opcode works as expected including when used
both correctly and incorrectly
This reverts the changes related to the CheckSequenceVerify opcode that
were merged from upstream since additional changes are needed and it's
much cleaner to implement all of code related to the sequence locks in
the same PR which will be referenced by the DCP as opposed to being
split up in multiple.
This modifies the way standard verification flags are handled so that it
is possible to selectively enable them based on the result of agenda
votes.
First, it moves the StandardVerifyFlags constant from the txscript
package to the mempool/policy code and rename it to
BaseStandardVerifyFlags. As the TODO in the comment of the moved
constant indicated, these flags are policy related and thus really
belong in policy. Ideally there would be a completely separate policy
package, but since the policy code currently lives in mempool/policy.go,
the constant has been moved there.
Next, it introduces a new function named standardScriptVerifyFlags,
which accepts the chain as an argument and, for now, just returns the
BaseStandardVerifyFlags along with a nil error. This will allow
additional flags to be selectively enabled depending on the result of an
agenda vote.
Finally, it updates the mempool policy struct to require a closure for
obtaining the flags so it can remain decoupled from the chain which in
turn allows easier and more robust unit testing of mempool functionality
since it allows a mocks to be used.
This modifies the script engine to replace OP_UNKNOWN192 with OP_SHA256
along with a flag named ScriptVerifySHA256 to selectively enable its
enforcement.
The new opcode consumes the top item from the data stack, computes its
SHA-256, and pushes the resulting digest back to the data stack.
Since it requires an item on the data stack, execution will terminate
with an error when the stack is empty. This behavior differs from
OP_UNKNOWN192 which does not consume any elements from the data stack
and therefore makes this is hard-forking change when interpreted with
the new semantics due to the ScriptVerifySHA256 flag being set. Code to
selectively enable the opcode based on the result of an agenda vote will
be added in a separate commit.
This also includes tests to ensure the opcode works as expected
including when used both correctly and incorrectly.
Decred updated the semantics of this opcode to use blake256, but did not
rename the opcode to reflect that. This renames the opcode so that it
is clear that a blake256 hash is produced instead of a sha256 hash.
Upstream commit a6bf1d9850.
The merge commit modifies all of the encoded transactions in the test
data to use Decred native format and contains some other minor
modifications necessary to integrate with Decred.
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
This cleans up the reference test file to remove references to bitcoin
since it no longer applies to decred and remove a TODO that was recently
completed.
This modifies the signatures of all the transactions in the invalid
transaction data which involve checking signatures to ensure that they
are not failing for the wrong reason.
In order to make it easier for future updates, it introduces three
well-known private keys, 1, 2, and 3, that are used for signing all of
the transactions and adds them to the comments in the test data. The
first one is used for regular CHECKSIG while all three are used for
CHECKMULTISIG.
This removes the tests related to max money checks since txscript does
not do sanity checking on the monetary amounts as that is done by the
consensus rules in blockchain.
While here, update dcrscript -> txscript in the comments to reflect
reality.
As an aside, the existing tests were invalid anyways since the
signatures were invalid and thus the tests were failing for the wrong
reason.
This removes the test for the original Bitcoin bug in CHECKMULTISIG that
required an additional argument since that has been fixed in Decred and
the test therefore no longer applies.
As an aside, the existing test was invalid anyways since the signature
was invalid and thus the test would've failed for the wrong reason.
This replaces the tests for CODESEPARATOR in the invalid transaction
JSON data to be correct for Decred. It is always invalid to pass over
the CODESEPARATOR opcode in Decred as opposed to the Bitcoin behavior
where it changes what is hashed for the signature hash calculation.
As an aside, the previous tests were invalid anyways since they included
a signature that was invalid so the test would've failed for the wrong
reason. For all of these tests it's important for them to pass other
than the specific failure condition they are intended to trigger.
This corrects the hashes for the p2sh scripts in the invalid transaction
JSON data. This helps ensure the transactions are failing for the
intended reason as opposed to the p2sh script never being run because
the script hashes don't match.
decred's consensus rules require address generation
to use a compressed pubkey format, this was hacked
into NewAddressSecpPubKey. This commit removes the
hack and provides NewAddressSecpPubKeyCompressed to
enforce the consensus prerequisite
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.
This updates the script signing test code to use a single chain params
variable instead of repeatedly referring to a specific network. This
makes it much easier to change in the future such as future testnet
resets.
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 modifies the recently-added NullDataScript function in several
ways in an effort to make them more consistent with the tests in the
rest of the code base and improve/correct the logic:
- Use the hexToBytes and mustParseShortForm functions
- Consistently format the test errors
- Replace the valid bool flag with an expected error and test against it
- Ensure the returned script type is the expected type in all cases
This adds a new function named NullDataScript to the txscript package that returns a provably-pruneable OP_RETURN script with the provided data. The function will return an error if the provided data is larger than the maximum allowed length for a nulldata script to be be considered standard.
Putting the test code in the same package makes it easier for forks
since they don't have to change the import paths as much and it also
gets rid of the need for internal_test.go to bridge.
Also, do some light cleanup on a few tests while here.
This corrects the isNullData standard transaction type test to work
properly with canonically-encoded data pushes. In particular, single
byte data pushes that are small integers (0-16) are converted to the
equivalent numeric opcodes when canonically encoded and the code failed
to detect them properly.
It also adds several tests to ensure that both canonical and
non-canonical nulldata scripts are recognized properly and modifies the
test failure print to include the script that failed.
This does not affect consensus since it is just a standardness check.
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 exposes a new function on the ScriptBuilder type named AddOps that
allows multiple opcodes to be added via a single call and adds tests to
exercise the new function.
Finally, it updates a couple of places in the signing code that were
abusing the interface by setting its private script directly to use the
new public function instead.
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:
- d4852101d4
- This commit has already been independently applied so it is mostly a
NOOP
- f389742b39
In addition, gofmt -s has been run again to simplify the new additions
to Decred and and all simplifications are included in the merge commit.
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.
Contains the following upstream commits:
- 87182a2ddf
- This commit does not apply to Decred so it has been reverted
- 89af747603
- This commit has already been cherry picked and is a NOOP
- d0cdd53720
- This commit has already been cherry picked and is a NOOP
- df20c1074c
- ff0c787237
- 6e133b58da
- 34a94b7d0b
- 14ccab80e7
Upstream commit 3942a116e4
This merge also includes a few Decred specific modifications and
corrects some old btcjson references that should have been updated to
dcrjson.
This sync includes a new service flag named SFNodeBloom that a node is
required to use to indicate that it supports bloom filtering. This
includes a protocol version bump to 2 and a wire version bump to 0.1.0.
dcrd:
The SFNodeBloom flag is set by default. A new configuration option
--nopeerbloomfilters has been added to to disable bloom filtering.
Also, it corrects an issue with the mining state message where it was
using the network protocol version instead of having its own version.
Legacy transaction deep copy code mandated by the Bitcoin protocol
caused large amounts of data to be copied needlessly. If the
optimization for SigHashAll is set in chaincfg/params.go, these
extra copies are avoided by directly writing the pkScript and
decorations to a buffer and then hashing to get a witness hash,
while using the cached hash for the prefix.
Fixes#126.
This changes the script template parsing function to use a pointer into
the constant global opcode array for parsed opcodes as opposed to making
a copy of the opcode entries which causes unnecessary allocations.
Profiling showed that after roughly 48 hours of operation, this
copy was the culprit of 207 million unnecessary allocations.
Profiles discovered that lookups into the signature cache included an
expensive comparison to the stored `sigInfo` struct. This lookup had the
potential to be more expensive than directly verifying the signature
itself!
In addition, evictions were rather expensive because they involved
reading from /dev/urandom, or equivalent, for each eviction once the
signature cache was full as well as potentially iterating over every
item in the cache in the worst-case.
To remedy this poor performance several changes have been made:
* Change the lookup key to the fixed sized 32-byte signature hash
* Perform a full equality check only if there is a cache hit which
results in a significant speed up for both insertions and existence
checks
* Override entries in the case of a colliding hash on insert Add an
* .IsEqual() method to the Signature and PublicKey types in the
btcec package to facilitate easy equivalence testing
* Allocate the signature cache map with the max number of entries in
order to avoid unnecessary map re-sizes/allocations
* Optimize evictions from the signature cache Delete the first entry
* seen which is safe from manipulation due to
the pre image resistance of the hash function
* Double the default maximum number of entries within the signature
cache due to the reduction in the size of a cache entry
* With this eviction scheme, removals are effectively O(1)
Fixes#575.
IsUnspendable takes a public key script and returns whether it is
spendable.
Additionally, hook this into the mempool isDust function, since
unspendable outputs can't be spent.
This mimics Bitcoin Core commit 0aad1f13b2430165062bf9436036c1222a8724da
The required number of inputs for a stake P2SH output were incorrectly
estimated by CalcScriptInfo. Now the sub class for any given output is
also checked for whether or not it is P2SH.
Corrected or added many comments.
Update test code to follow format go vet wants.
The code doesn't pass the checks 100% yet. That will come in a later
commit but these all seemed related so I'd rather get them in now.
An off by one bug caused by inheritance from Bitcoin caused
multisignature transactions that were fully signed to be rejected
due to the number of stack items. The off-by-one bug has been fixed.
This modifies the conversion of the output index from the JSON-based
test data for valid and invalid transactions as well as the signature
hash type for signature hash tests to first convert to a signed int and
then to an unsigned int. This is necessary because the result of a
direct conversion of a float to an unsigned int is implementation
dependent and doesn't result in the expected value on all platforms.
Also, while here, change the function names in the error prints to match
the actual names.
Fixes#600.
500 tests with various transactions and scripts, verifying that
calcSignatureHash generates the expected hash in each case.
This requires changing SigHashType to uint32; that won't affect the
standard use-cases, but will make calcSignatureHash behave more like the
Core counterpart for non-standard SigHashType settings, like those in
some of these tests.
First, it removes the documentation section from all the README.md files
and instead puts a web-based godoc badge and link at the top with the
other badges. This is being done since the local godoc tool no longer
ships with Go by default, so the instructions no longer work without
first installing godoc. Due to this, pretty much everyone uses the
web-based godoc these days anyways. Anyone who has manually installed
godoc won't need instructions.
Second, it makes sure the ISC license badge is at the top with the other
badges and removes the textual reference in the overview section.
Finally, it's modifies the Installation section to Installation and
Updating and adds a '-u' to the 'go get' command since it works for both
and thus is simpler.
isMultiSig was not verifying the number of pubkeys specified matched
the number of pubkeys provided. This caused certain non-standard
scripts to be considered multisig scripts.
However, the script still would have failed during execution.
NOTE: This only affects whether or not the script is considered
standard and does NOT affect consensus.
Also, add a test for this check.
See https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki for
more information.
This commit mimics Bitcoin Core commit bc60b2b4b401f0adff5b8b9678903ff8feb5867b
and includes additional tests from Bitcoin Core commit
cb54d17355864fa08826d6511a0d7692b21ef2c9
We've already been generating lowS sigs for quite a while. This removes
the malleability vector.
This mimics Bitcoin Core commit 49dd5c629df0a08cf3b1ea8085c03312d1a81696
Introduce an ECDSA signature verification into btcd in order to
mitigate a certain DoS attack and as a performance optimization.
The benefits of SigCache are two fold. Firstly, usage of SigCache
mitigates a DoS attack wherein an attacker causes a victim's client to
hang due to worst-case behavior triggered while processing attacker
crafted invalid transactions. A detailed description of the mitigated
DoS attack can be found here: https://bitslog.wordpress.com/2013/01/23/fixed-bitcoin-vulnerability-explanation-why-the-signature-cache-is-a-dos-protection/
Secondly, usage of the SigCache introduces a signature verification
optimization which speeds up the validation of transactions within a
block, if they've already been seen and verified within the mempool.
The server itself manages the sigCache instance. The blockManager and
txMempool respectively now receive pointers to the created sigCache
instance. All read (sig triplet existence) operations on the sigCache
will not block unless a separate goroutine is adding an entry (writing)
to the sigCache. GetBlockTemplate generation now also utilizes the
sigCache in order to avoid unnecessarily double checking signatures
when generating a template after previously accepting a txn to the
mempool. Consequently, the CPU miner now also employs the same
optimization.
The maximum number of entries for the sigCache has been introduced as a
config parameter in order to allow users to configure the amount of
memory consumed by this new additional caching.
While current existing numeric opcodes are limited to 4 bytes, new
opcodes may need different limits.
This mimics Bitcoin Core commit 99088d60d8a7747c6d1a7fd5d8cd388be1b3e138
This commit modifies the DisasmString function to use a bytes buffer for
constructing the disassembled string instead of naive string
concatenation. This makes a huge difference when disassembling scripts
with large numbers of opcodes.
IsUnspendable takes a public key script and returns whether it is
spendable.
Additionally, hook this into the mempool isDust function, since
unspendable outputs can't be spent.
This mimics Bitcoin Core commit 0aad1f13b2430165062bf9436036c1222a8724da