Commit Graph

45 Commits

Author SHA1 Message Date
Aaron Campbell
8be96a8729 multi: Correct typos.
Correct typos found by reading code, ispell, and creative grepping.
2019-08-22 10:20:03 -05:00
Dave Collins
6dea351b42
txscript: Remove third GetPreciseSigOpCount param.
This removes the previously deprecated and unused third parameter of the
GetPreciseSigOpCount function.
2019-06-24 15:13:31 -05:00
Dave Collins
f71b0d246f
txscript: Cleanup opcode removal by data tests.
This converts the test definitions for TestRemoveOpcodeByData to make
use of mustParseShortForm which improves the readability and
construction of the tests as well as makes them more consistent with the
rest of the code base.

It also cleans up the recently added stake tx tests so that they don't
exceed col 80 and sets their names to indicate they are p2pkh and p2sh
forms.
2019-03-28 16:56:33 -05:00
Dave Collins
fcb1f3a7a1
txscript: Remove unused parseScriptTemplate func.
Also remove tests associated with the func accordingly.
2019-03-26 14:55:45 -05:00
Dave Collins
861032aa1e
txscript: Remove unused unparseScript func.
Also remove tests associated with unparsing opcodes accordingly.
2019-03-26 14:55:43 -05:00
Dave Collins
c598f59151
txscript: Rename removeOpcodeByDataRaw func.
This renames the removeOpcodeByDataRaw to removeOpcodeByData now that
the old version has been removed.
2019-03-26 14:55:41 -05:00
Dave Collins
f93c1de13f
txscript: Implement efficient opcode data removal.
This introduces a new function named removeOpcodeByDataRaw which accepts
the raw scripts and data to remove versus requiring the parsed opcodes
to both significantly optimize it as well as make it more flexible for
working with raw scripts.

There are several places in the rest of the code that currently only
have access to the parsed opcodes, so this only introduces the function
for use in the future and deprecates the existing one.

Note that, in practice, the script will never actually contain the data
that is intended to be removed since the function is only used during
signature verification to remove the signature itself which would
require some incredibly non-standard code to create.

Thus, as an optimization, it avoids allocating a new script unless there
is actually a match that needs to be removed.

Finally, it updates the tests to use the new function.
2019-03-26 14:55:35 -05:00
Dave Collins
67d73853b2
txscript: Make canonicalPush accept raw opcode.
This renames the canonicalPush function to isCanonicalPush and converts
it to accept an opcode as a byte and the associate data as a byte slice
instead of the internal parse opcode data struct in order to make it
more flexible for raw script analysis.

It also updates all callers and tests accordingly.
2019-03-26 14:51:45 -05:00
Dave Collins
a598838fb7
txscript: Optimize isAnyKindOfScriptHash.
This converts the isAnyKindOfScriptHash function to analyze the raw
script instead of requiring far less efficient parsed opcodes thereby
significantly optimizing the function.

Since the function relies on isStakeScriptHash to identify a stake
tagged pay-to-script-hash, and is the only consumer of it, this also
converts that function to analyze the raw script and renames it to
isStakeScriptHashScript for more consistent naming.

Finally, the tests are updated accordingly.

The following is a before and after comparison of analyzing a large
script:

benchmark                        old ns/op    new ns/op    delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash   101249       3.83         -100.00%

benchmark                        old allocs   new allocs   delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash   1            0            -100.00%

benchmark                        old bytes    new bytes    delta
-------------------------------------------------------------------
BenchmarkIsAnyKindOfScriptHash   466944       0            -100.00%
2019-03-26 14:51:08 -05:00
Dave Collins
51f76392b4
txscript: Add tests for stake-tagged script hash.
This adds tests to ensure the isAnyKindOfScriptHash function properly
identifies the four stake-tagged pay-to-script-hash possibilities in
addition to ensuring they are not misidentified as standard
pay-to-script-hash scripts.
2019-03-26 14:51:06 -05:00
Dave Collins
f306a72a16
txscript: Introduce raw script sighash calc func.
This introduces a new function named calcSignatureHashRaw which accepts
the raw script bytes to calculate the script hash versus requiring the
parsed opcode only to unparse them later in order to make it more
flexible for working with raw scripts.

Since there are several places in the rest of the code that currently
only have access to the parsed opcodes, this modifies the existing
calcSignatureHash to first unparse the script before calling the new
function.

Note that the code in the signature hash calculation to remove all
instances of OP_CODESEPARATOR from the script is removed because that is
a holdover from BTC code which does not apply to v0 Decred scripts since
OP_CODESEPARATOR is completely disabled in Decred and thus there can
never actually be one in the script.

Finally, it removes the removeOpcode function and related tests since it
is no longer used.
2019-03-26 14:50:57 -05:00
VcTT
8695142d02 txscript: Add stake tx remove opcode tests.
txscript: Add stake tx remove opcode tests.
2019-03-26 14:49:15 -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
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
Dave Collins
f6be618a1b
txscript: Move sig hash logic to separate file.
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.
2018-04-30 08:54:07 -05:00
Markus Richter
1e42b8524d multi: Properly capitalize Decred.
Decred is inconsistencly capitalized in the code base,
change all occurences of decred to Decred.
2018-03-01 17:41:35 -06:00
Dave Collins
1ca1017813
txscript: Allow external signature hash calc.
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.
2017-12-21 14:28:22 -06:00
David Hill
fc31a0b39e multi: remove unused funcs and vars 2017-12-07 21:46:25 -06: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
fce24223cd
multi: Separate tx serialization type from version.
Decred's serialized format for transactions split the 32-bit version
field into two 16-bit components such that the upper bits are used to
encode a serialization type and the lower 16 bits are the actual
transaction version.

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

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

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

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

The following is an overview of all changes:
- Introduce new SerType field to MsgTx to specify the serialization type
- Change MsgTx.Version to a uint16 to properly reflect its maximum
  allowed value
- Change the semantics of MsgTx.Version to be the actual transaction
  version as intended
- Update all callers that had special code to deal with the previous
  Version field semantics to use the new semantics
- Switch all of the code that deals with encoding and decoding the
  serialized version field to use more efficient masks and shifts
  instead of binary writes into buffers which cause allocations
- Correct several issues that would prevent producing expected
  serializations for transactions with actual transaction versions that
  are not 1
- Simplify the various serialize functions to use a single func which
  accepts the serialization type to reduce code duplication
- Make serialization type switch usage more consistent with the rest of
  the code base
- Update the utxoview and related code to use uint16s for the
  transaction version as well since it should not care about the
  serialization type due to using its own
- Make code more consistent in how it uses bytes.Buffer
- Clean up several of the comments regarding hashes and add some new
  comments to better describe the serialization types
2017-08-07 14:10:27 -05:00
Dave Collins
c162fbde71
multi: Upstream chainhash abstraction sync
Contains the following commits:

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

Also, the merge commit contains the necessary decred-specific
alterations, converts all other references to sha to hash to keep with
the spirit of the merged commits, and various other cleanup intended to
bring the code bases more in line with one another.
2016-11-16 12:48:40 -06:00
Dave Collins
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
885070a4df Sync upstream through Sep 2, 2015. 2016-05-17 12:15:10 -05:00
cjepson
653e13db0e Waste less memory if sighash optimizations are on
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.
2016-05-16 16:18:04 -04:00
David Hill
5fcef8aa56 txscript: New function IsUnspendable
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
2016-03-22 11:34:32 -04:00
cjepson
df701d8cdf Revert sync merge
The sync merge does not build and needs further testing. It is
being reverted.
2016-03-08 22:16:06 -05:00
Alex Yocom-Piatt
5b2b97e858 Sync to upstream 0280fa0264
Conflicts:
	blockchain/chain.go
	blockchain/checkpoints.go
	blockchain/difficulty.go
	blockchain/internal_test.go
	blockchain/txlookup.go
	blockchain/validate.go
	blockchain/validate_test.go
	blockmanager.go
	chaincfg/params.go
	cmd/dropafter/dropafter.go
	cpuminer.go
	database/db.go
	database/interface_test.go
	database/ldb/block.go
	database/ldb/insertremove_test.go
	database/ldb/leveldb.go
	database/ldb/operational_test.go
	database/ldb/tx.go
	database/memdb/memdb.go
	database/reorg_test.go
	dcrjson/walletsvrcmds.go
	docs/README.md
	docs/json_rpc_api.md
	mempool.go
	mining.go
	peer.go
	rpcserver.go
	rpcserverhelp.go
	rpcwebsocket.go
	sample-dcrd.conf
	txscript/consensus.go
	txscript/script_test.go
	txscript/sign.go
	txscript/standard.go
	wire/blockheader_test.go
	wire/msgtx_test.go
2016-03-07 11:35:24 -06:00
John C. Vernaleo
14769a741b Resolve all remaining issues caught by goclean.sh 2016-02-15 11:24:00 -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
David Hill
3331d6098b txscript: New function IsUnspendable
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
2015-08-03 10:10:23 -04:00
Dave Collins
927a0e9c37 txscript: Test consistency and cleanup.
- Move reference tests to test package since they are intended to
  exercise the engine as callers would
- Improve the short form script parsing to allow additional opcodes:
  DATA_#, OP_#, FALSE, TRUE
- Make use of a function to decode hex strings rather than manually
  defining byte slices
- Update the tests to make use of the short form script parsing logic
  rather than manually defining byte slices
- Consistently replace all []byte{} and [][]byte{} with nil
- Define tests only used in a specific function inside that func
- Move invalid flag combination test to engine_test since that is what
  it is testing
- Remove all redundant script tests in favor of the JSON-based tests in
  the data directory.
- Move several functions from internal_test.go to the test files
  associated with what the tests are checking
2015-05-04 16:04:29 -05:00
Dave Collins
005b540895 txscript: Separate code for standard scripts.
This commit moves all code related to standard scripts into a separate
file named standard.go as well as the associated tests into
standard_test.go.  Since the code in address.go and address_test.go is
only related to standard scripts, it has been combined into the new
files and the old files deleted.

The intent here is to make it clear that the code in standard.go is not
related to consensus.
2015-05-01 15:20:48 -05:00
Dave Collins
6e402deb35 Relicense to the btcsuite developers.
This commit relicenses all code in this repository to the btcsuite
developers.
2015-05-01 12:00:56 -05:00
Dave Collins
a8fe1ad5fe txscript: Code consistency and doco improvements.
This commit contains a lot of cleanup on the txscript code to make it
more consistent with the code throughout the rest of the project.  It
doesn't change any operational logic.

The following is an overview of the changes:

- Add a significant number of comments throughout in order to better
  explain what the code is doing
- Fix several comment typos
- Move a couple of constants only used by the engine to engine.go
- Move a variable only used by the engine to engine.go
- Fix a couple of format specifiers in the test prints
- Reorder functions so they're defined before/closer to use
- Make the code lint clean with the exception of the opcode definitions
2015-04-29 13:16:22 -05:00
Dave Collins
3fc2444309 txscript: Separate signing code.
This commit separate the transaction signing code into sign.go and the
related tests into sign_test.go.
2015-04-20 17:00:23 -05:00
Dave Collins
8dd7412a84 txscript: Rename Script to Engine.
This commit renames the Script type to Engine to better reflect its
purpose.  It also renames the NewScript function to NewEngine to match.

This is being done because name Script for the engine is confusing since
it implies it is an actual script rather than the execution environment
for the script.  It also paves the way for eventually supplying a
ParsedScript type which will be less likely to be confused with the
execution environment.

While moving the code, some additional variable names and comments have
been updated to better match the style used throughout the rest of the
code base.  In addition, an attempt has been made to use consistent naming
of the engine as 'vm' instead of using different variables names as it was
previously.

Finally, the relevant engine code has been moved into a new file named
engine.go and related tests moved to engine_test.go.
2015-04-20 15:31:23 -05:00
Dave Collins
bec90e253c txscript: Remove unneeded param from NewScript.
This commit removes the unnecessary sigScript parameter from the
txscript.NewScript function.  This has bothered me for a while because it
can and really should be obtained from the provided transaction and input
index.  The way it was, the passed script could technically be different
than what is in the transaction.  Obviously that would be an improper use
of the API, but it's safer and more convenient to simply pull it from the
provided transaction and index.

Also, since the function signature is changing anyways, make the input
index parameter come after the transaction which it references.
2015-04-20 13:46:11 -05:00
David Hill
9523345814 txscript: Add new flag ScriptVerifyCleanStack
The ScriptVerifyCleanStack flag requires that only a single
stack element remains after evaluation and that when interpreted
as a bool, it must be true.  This is BIP0062, rule 6.

This mimics Bitcoin Core commit b6e03cc59208305681745ad06f2056ffe6690597
2015-03-13 15:54:17 -04:00
David Hill
436fb8203c txscript: Increase maximum allowed nulldata bytes
This change increases the maximum allowed bytes allowed in pushed
data to be considered a nulldata transaction.  This matches the current
value the reference implementation uses by default.
2015-03-09 23:40:46 -04:00
David Hill
ff747f8eae Use ScriptVerifyMinimalData
Additionally, drop HasCanoncialPushes as ScriptVerifyMinimalData
offers more complete checks.
2015-02-26 13:13:16 -05:00
David Hill
f79c72f18a txscript: Remove ScriptCanonicalSignatures
Remove ScriptCanonicalSignatures and use the new
ScriptVerifyDERSignatures flag.  The ScriptVerifyDERSignatures
flag accomplishes the same functionality.
2015-02-23 22:04:15 -05:00
Dave Collins
e7c7c3399f Update btcec path import paths to new location. 2015-02-06 10:54:32 -06:00
Dave Collins
c6bc8ac1eb Update btcnet path import paths to new location. 2015-02-05 23:24:53 -06:00
Dave Collins
03433dad6a Update btcwire path import paths to new location. 2015-02-05 15:16:39 -06:00
Dave Collins
cbda064842 Import btcscript repo into txscript directory.
This commit contains the entire btcscript repository along with several
changes needed to move all of the files into the txscript directory in
order to prepare it for merging.  This does NOT update btcd or any of the
other packages to use the new location as that will be done separately.

- All import paths in the old btcscript test files have been changed to the
  new location
- All references to btcscript as the package name have been chagned to
  txscript

This is ongoing work toward #214.
2015-01-30 10:30:16 -06:00