Commit Graph

60 Commits

Author SHA1 Message Date
Dave Collins
3dc80cf238
build: Add CI support for test and module cache.
This makes use of the github actions cache to save and restore the Go
test and module caches.  This should result in faster CI runs since most
changes only affect a small number of tests.

It also updates the RPC integration tests to ensure the logs directory
is not in the source code dir so the go testing cache can be used.

Next, it renames the txscript module's data dir to testdata so go does
not treat it like a package.

Finally, it adds a script that stabilizes the timestamps on all files in
testdata directories when running the github action.  This is necessary
because the go testing cache logic uses the timestamps of all input
files when determining whether or not a test needs to be rerun and
github clones a fresh repo on every run which causes the timestamps of
the test data to change.
2023-06-19 14:18:30 -05:00
Dave Collins
b77b43b71b
txscript: Add versioned short form parsing.
This adds the ability for the short form script parsing to handle
different script versions and updates all of the tests to use the
version 0 function appropriately.
2021-10-14 16:13:28 -05:00
jholdstock
e3f7f58a68 multi: Don't use deprecated ioutil package.
As of go 1.16, the "io/ioutil" package is deprecated. All functionality
from "io/ioutil" has been moved to either the "io" or "os" packages.
2021-09-01 06:09:37 -05:00
Dave Collins
a94c027208
txscript: Separate short form script parsing.
This separates the test code related to parsing scripts using the
human-readable short form used throughout the tests into a separate file
so it can more easily be copied into other packages where it might be
useful for the tests as well.  Allowing it to be copied is preferred to
making it part of the public API of some package since it is an ad-hoc
format and it is not possible to access test-specific code across
package boundaries without making it part of the actual public API.
2021-06-15 13:01:24 -05:00
Dave Collins
76f80ba180
txscript: Break dcrutil dependency.
Now that the addresses have all been converted over to use the stdaddr
package, this removes only remaining dependencies on dcrutil which are
in the tests in order to avoid cyclic dependencies when updating the
dcrutil code to the use the stdaddr package.
2021-04-12 11:21:01 -05:00
Dave Collins
ce77185203
txscript: Add script bldr unchecked op add.
This adds a new method to ScriptBuilder named AddOpsUnchecked that is
similar to AddDataUnchecked in that it allows the limits that are
ordinarily impose to be bypassed for regression testing purposes where
sizes are intentionally made larger than allowed.

It also updates the test code to make use of the method instead of
reaching into the internals to manually concatenate the opcodes.
2021-03-12 17:33:15 -06:00
Dave Collins
e4d2cb39db
txscript: Rename script bldr add data to unchecked.
This renames the AddFullData method of the ScriptBuilder to
AddDataUnchecked to make its semantics more obvious.
2021-03-12 17:33:14 -06:00
Donald Adu-Poku
48e43ca109 multi: Start dcrutil v4 module dev cycle.
This updates the dcrutil module version to v4
and updates import and deps sites.
2020-12-16 16:30:24 -06:00
Ryan Staudt
380c8d512b txscript: Store short tx hash in sigcache.
This adds a uint64 short transaction hash to sigcache entries.  This can
be used to proactively evict entries from the sigcache based on the
transaction that they are associated with.
2020-09-24 12:19:59 -05:00
Marco Peereboom
80f5feb1db
multi: Add decentralized treasury support.
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.
2020-09-21 12:15:31 -05:00
Dave Collins
6fc98347d9
txscript: Add support for errors.Is/As.
This updates the txscript package to provide support for the errors.Is
and errors.As functions introduced in Go 1.13 per the recently
documented best practices.

The following is an overview of the changes:

- Rename the ErrorCode type to ErrorKind and make it a string
- Implement the error interface on ErrorKind
- Update all error code definitions to the new type
- Remove error code string map that is no longer required
- Remove unused ErrInternal definition
- Change the error code field of the Error type to Err
- Implement Unwrap on the Error type to support unwrapping via
  errors.Is/As
- Remove the IsErrorCode function since it is no longer needed due to
  errors.Is
- Update IsDERSigError to cope with the changes
- Modify various comments to refer to error kinds instead of codes
- Update all test code to use the new ErrorKind directly along with
  errors.Is for detecting the expect errors
- Add full test coverage to ensure the new error definitions work as
  intended
- Update the doc.go errors section accordingly
2020-05-26 21:50:17 -05:00
David Hill
3c04174f55 txscript: use errors api; require go 1.13+ 2020-04-04 07:12:01 -05:00
David Hill
4971faff25 multi: remove whitespace 2019-11-21 18:31:30 -06:00
David Hill
6d39abb6be dcrutil: Start v3 module dev cycle.
Several upcoming changes constitute breaking the public API.
2019-10-24 19:13:26 -05:00
Aaron Campbell
03678bb754 multi: Correct typos.
Correct typos found by reading code and creative grepping.
2019-08-16 17:37:58 -05:00
Dave Collins
1e34495ddb
txscript: Use dcrutil/v2.
This udpates the txscript module to use v2 of the dcrutil module and v2
of the chaincfg module since dcrutil/v2 requires it.

While here, it also modifies the signing functions to accept the new
dcrutil.AddressParams instead of a pointer to a chaincfg.Params struct
in order to remove the tight coupling between txscript and chaincfg at
the API boundary.

It also updates the tests accordingly.
2019-06-24 15:13:39 -05:00
Dave Collins
06f769ef72
txscript: Convert sighash calc tests.
This converts the tests for calculating signature hashes to use the
exported function which handles the raw script versus the now deprecated
variant requiring parsed opcodes.
2019-03-26 14:50:59 -05:00
Donald Adu-Poku
60cbb70c67 txscript: add stake opcode tests. 2018-09-11 20:21:42 +00:00
Dave Collins
535e4adb04
txscript: Remove MINIMALDATA flag from test data.
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.
2018-07-02 12:04:30 -05:00
Dave Collins
f5dc86e9cc
txscript: Remove verify minimal data flag.
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.
2018-07-02 12:02:59 -05:00
Dave Collins
a8e9a63684
txscript: Remove DERSIG flag from test data.
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.
2018-07-02 12:02:41 -05:00
Dave Collins
98e0b27dd8
txscript: Remove DER signature verification flag.
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.
2018-07-02 12:02:28 -05:00
Dave Collins
d12e172fee
txscript: Remove P2SH flag from test data.
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.
2018-07-02 12:02:14 -05:00
Dave Collins
2157079165
txscript: Remove pay-to-script-hash flag.
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.
2018-07-02 12:01:42 -05:00
Dave Collins
c0be0be19a
txscript: Convert reference tests to new format.
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
2018-07-02 11:59:13 -05:00
Dave Collins
d8306ee602
txscript: Significantly improve errors.
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.
2018-07-01 15:04:59 -05:00
Dave Collins
d3731898e9
txscript: Remove STRICTENC flag from test data.
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.
2018-06-22 00:30:02 -05:00
Dave Collins
c9ca59bf66
txscript: Remove strict encoding verification flag.
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.
2018-06-22 00:29:46 -05:00
Dave Collins
7815f0c851
txscript: Remove low S verification flag.
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.
2018-06-22 00:28:54 -05:00
Donald Adu-Poku
b105a9ef49 multi: add valueIn parameter to wire.NewTxIn.
This adds the valueIn parameter to wire.NewTxIn. Call sites and associated tests have also been updated.
2018-06-15 19:13:41 -05:00
Dave Collins
3608e8ab74
txscript: Allow multi opcode test data repeat.
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
2018-06-15 12:11:02 -05:00
Dave Collins
9e23c8e8ea
txscript: Introduce repeated syntax to test data.
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
2018-06-14 16:48:04 -05:00
Dave Collins
47cbc26b93
txscript: Add JSON-based signature hash tests.
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.
2018-04-30 12:14:14 -05:00
Dave Collins
2cb2d9a22a
txscript: Consolidate tests into txscript package.
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.
2018-04-30 10:34:59 -05:00
Josh Rickmar
6842aa006d Merge remaining dcrutil code into a dcrd package.
This merge commit adds the following code from the
github.com/decred/dcrutil package into a new
github.com/decred/dcrd/dcrutil package:

* Address handling
* Amount type
* AppDataDir func
* bitflags functions
* Block wrapper type
* Hash160 func
* Tx wrapper type
* WIF type

as well as all tests for this code.

The old github.com/decred/dcrutil/hdkeychain package has also been
merged and moved to github.com/decred/dcrd/dcrutil/hdkeychain.

dcrd packages have been updated to use the new packages and the dep
files have been updated for this change.
2017-10-11 22:06:36 -04:00
Dave Collins
ee5b56ba72
txscript: Implement CheckSequenceVerify
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
2017-09-21 15:58:48 -05:00
Dave Collins
bd78208c37
txscript: Revert upstream CSV merge.
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.
2017-09-21 11:17:58 -05:00
Dave Collins
11ae59977a
txscript: Introduce OP_SHA256.
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.
2017-09-14 11:33:48 -05:00
Dave Collins
c47ee87673
txscript: Implement CheckSequenceVerify
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.
2017-08-28 12:23:34 -05:00
Dave Collins
9a7132a56b
txscript: Cleanup reference test code.
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.
2017-08-04 03:05:42 -05:00
Dave Collins
fdb25c2f43
txscript: Use native encoding in json test data.
This modifies the valid and invalid JSON transaction test data to use
natively-encoded transactions instead of the legacy Bitcoin format.
2017-08-03 23:43:37 -05:00
Dave Collins
c162fbde71
multi: Upstream chainhash abstraction sync
Contains the following commits:

- 711f33450c
- b6b1e55d1e
  - Reverted because Travis is already at a more recent version
- bd4e64d1d4

Also, the merge commit contains the necessary decred-specific
alterations, converts all other references to sha to hash to keep with
the spirit of the merged commits, and various other cleanup intended to
bring the code bases more in line with one another.
2016-11-16 12:48:40 -06:00
David Hill
a6bf1d9850 txscript: Implement CheckSequenceVerify (BIP0112) 2016-10-19 12:06:44 -04:00
cjepson
02bb5123d6 Merge in btcd commit '3b39edcaa1e867efc4223d95ca1496aaadf8eca3'
Merges in 3b39edcaa1 from btcd.
2016-09-22 15:52:37 -04:00
Dave Collins
b6d426241d blockchain: Rework to use new db interface.
This commit is the first stage of several that are planned to convert
the blockchain package into a concurrent safe package that will
ultimately allow support for multi-peer download and concurrent chain
processing.  The goal is to update btcd proper after each step so it can
take advantage of the enhancements as they are developed.

In addition to the aforementioned benefit, this staged approach has been
chosen since it is absolutely critical to maintain consensus.
Separating the changes into several stages makes it easier for reviewers
to logically follow what is happening and therefore helps prevent
consensus bugs.  Naturally there are significant automated tests to help
prevent consensus issues as well.

The main focus of this stage is to convert the blockchain package to use
the new database interface and implement the chain-related functionality
which it no longer handles.  It also aims to improve efficiency in
various areas by making use of the new database and chain capabilities.

The following is an overview of the chain changes:

- Update to use the new database interface
- Add chain-related functionality that the old database used to handle
  - Main chain structure and state
  - Transaction spend tracking
- Implement a new pruned unspent transaction output (utxo) set
  - Provides efficient direct access to the unspent transaction outputs
  - Uses a domain specific compression algorithm that understands the
    standard transaction scripts in order to significantly compress them
  - Removes reliance on the transaction index and paves the way toward
    eventually enabling block pruning
- Modify the New function to accept a Config struct instead of
  inidividual parameters
- Replace the old TxStore type with a new UtxoViewpoint type that makes
  use of the new pruned utxo set
- Convert code to treat the new UtxoViewpoint as a rolling view that is
  used between connects and disconnects to improve efficiency
- Make best chain state always set when the chain instance is created
  - Remove now unnecessary logic for dealing with unset best state
- Make all exported functions concurrent safe
  - Currently using a single chain state lock as it provides a straight
    forward and easy to review path forward however this can be improved
    with more fine grained locking
- Optimize various cases where full blocks were being loaded when only
  the header is needed to help reduce the I/O load
- Add the ability for callers to get a snapshot of the current best
  chain stats in a concurrent safe fashion
  - Does not block callers while new blocks are being processed
- Make error messages that reference transaction outputs consistently
  use <transaction hash>:<output index>
- Introduce a new AssertError type an convert internal consistency
  checks to use it
- Update tests and examples to reflect the changes
- Add a full suite of tests to ensure correct functionality of the new
  code

The following is an overview of the btcd changes:

- Update to use the new database and chain interfaces
- Temporarily remove all code related to the transaction index
- Temporarily remove all code related to the address index
- Convert all code that uses transaction stores to use the new utxo
  view
- Rework several calls that required the block manager for safe
  concurrency to use the chain package directly now that it is
  concurrent safe
- Change all calls to obtain the best hash to use the new best state
  snapshot capability from the chain package
- Remove workaround for limits on fetching height ranges since the new
  database interface no longer imposes them
- Correct the gettxout RPC handler to return the best chain hash as
  opposed the hash the txout was found in
- Optimize various RPC handlers:
  - Change several of the RPC handlers to use the new chain snapshot
    capability to avoid needlessly loading data
  - Update several handlers to use new functionality to avoid accessing
    the block manager so they are able to return the data without
    blocking when the server is busy processing blocks
  - Update non-verbose getblock to avoid deserialization and
    serialization overhead
  - Update getblockheader to request the block height directly from
    chain and only load the header
  - Update getdifficulty to use the new cached data from chain
  - Update getmininginfo to use the new cached data from chain
  - Update non-verbose getrawtransaction to avoid deserialization and
    serialization overhead
  - Update gettxout to use the new utxo store versus loading
    full transactions using the transaction index

The following is an overview of the utility changes:
- Update addblock to use the new database and chain interfaces
- Update findcheckpoint to use the new database and chain interfaces
- Remove the dropafter utility which is no longer supported

NOTE: The transaction index and address index will be reimplemented in
another commit.
2016-08-18 15:42:18 -04:00
Dave Collins
bd4e64d1d4 chainhash: Abstract hash logic to new package. (#729)
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
2016-08-08 14:04:33 -05:00
Dave Collins
18e35febe5 dcrjson/txscript: Merge arm-specific test updates.
Contains the following upstream commits:
- 3c2c858888
- c7e6c1e88f
2016-05-27 09:48:01 -05:00
Dave Collins
e310d1dac5 Integrate a valid ECDSA signature cache
Upstream commit 0029905d43
2016-05-18 13:37:06 -05:00
Olaoluwa Osuntokun
3b39edcaa1 txscript: optimize sigcache lookup (#598)
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.
2016-04-13 21:56:10 -05:00
John C. Vernaleo
5076a00512 Initial Decred Commit.
Includes work by cjepson, ay-p, jolan, and jcv.

Initial conceptual framework by tacotime.
2016-02-07 14:00:12 -05:00