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.
233 lines
7.1 KiB
Go
233 lines
7.1 KiB
Go
// Copyright (c) 2017 The btcsuite developers
|
|
// Copyright (c) 2015-2019 The Decred developers
|
|
// Use of this source code is governed by an ISC
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package txscript
|
|
|
|
import (
|
|
"errors"
|
|
"io"
|
|
"testing"
|
|
)
|
|
|
|
// TestErrorKindStringer tests the stringized output for the ErrorKind type.
|
|
func TestErrorKindStringer(t *testing.T) {
|
|
tests := []struct {
|
|
in ErrorKind
|
|
want string
|
|
}{
|
|
{ErrInvalidIndex, "ErrInvalidIndex"},
|
|
{ErrInvalidSigHashSingleIndex, "ErrInvalidSigHashSingleIndex"},
|
|
{ErrUnsupportedAddress, "ErrUnsupportedAddress"},
|
|
{ErrTooManyRequiredSigs, "ErrTooManyRequiredSigs"},
|
|
{ErrTooMuchNullData, "ErrTooMuchNullData"},
|
|
{ErrUnsupportedScriptVersion, "ErrUnsupportedScriptVersion"},
|
|
{ErrNotMultisigScript, "ErrNotMultisigScript"},
|
|
{ErrEarlyReturn, "ErrEarlyReturn"},
|
|
{ErrEmptyStack, "ErrEmptyStack"},
|
|
{ErrEvalFalse, "ErrEvalFalse"},
|
|
{ErrScriptUnfinished, "ErrScriptUnfinished"},
|
|
{ErrInvalidProgramCounter, "ErrInvalidProgramCounter"},
|
|
{ErrScriptTooBig, "ErrScriptTooBig"},
|
|
{ErrElementTooBig, "ErrElementTooBig"},
|
|
{ErrTooManyOperations, "ErrTooManyOperations"},
|
|
{ErrStackOverflow, "ErrStackOverflow"},
|
|
{ErrInvalidPubKeyCount, "ErrInvalidPubKeyCount"},
|
|
{ErrInvalidSignatureCount, "ErrInvalidSignatureCount"},
|
|
{ErrNumOutOfRange, "ErrNumOutOfRange"},
|
|
{ErrVerify, "ErrVerify"},
|
|
{ErrEqualVerify, "ErrEqualVerify"},
|
|
{ErrNumEqualVerify, "ErrNumEqualVerify"},
|
|
{ErrCheckSigVerify, "ErrCheckSigVerify"},
|
|
{ErrCheckMultiSigVerify, "ErrCheckMultiSigVerify"},
|
|
{ErrCheckSigAltVerify, "ErrCheckSigAltVerify"},
|
|
{ErrP2SHStakeOpCodes, "ErrP2SHStakeOpCodes"},
|
|
{ErrDisabledOpcode, "ErrDisabledOpcode"},
|
|
{ErrReservedOpcode, "ErrReservedOpcode"},
|
|
{ErrMalformedPush, "ErrMalformedPush"},
|
|
{ErrInvalidStackOperation, "ErrInvalidStackOperation"},
|
|
{ErrUnbalancedConditional, "ErrUnbalancedConditional"},
|
|
{ErrNegativeSubstrIdx, "ErrNegativeSubstrIdx"},
|
|
{ErrOverflowSubstrIdx, "ErrOverflowSubstrIdx"},
|
|
{ErrNegativeRotation, "ErrNegativeRotation"},
|
|
{ErrOverflowRotation, "ErrOverflowRotation"},
|
|
{ErrDivideByZero, "ErrDivideByZero"},
|
|
{ErrNegativeShift, "ErrNegativeShift"},
|
|
{ErrOverflowShift, "ErrOverflowShift"},
|
|
{ErrP2SHTreasuryOpCodes, "ErrP2SHTreasuryOpCodes"},
|
|
{ErrMinimalData, "ErrMinimalData"},
|
|
{ErrInvalidSigHashType, "ErrInvalidSigHashType"},
|
|
{ErrSigTooShort, "ErrSigTooShort"},
|
|
{ErrSigTooLong, "ErrSigTooLong"},
|
|
{ErrSigInvalidSeqID, "ErrSigInvalidSeqID"},
|
|
{ErrSigInvalidDataLen, "ErrSigInvalidDataLen"},
|
|
{ErrSigMissingSTypeID, "ErrSigMissingSTypeID"},
|
|
{ErrSigMissingSLen, "ErrSigMissingSLen"},
|
|
{ErrSigInvalidSLen, "ErrSigInvalidSLen"},
|
|
{ErrSigInvalidRIntID, "ErrSigInvalidRIntID"},
|
|
{ErrSigZeroRLen, "ErrSigZeroRLen"},
|
|
{ErrSigNegativeR, "ErrSigNegativeR"},
|
|
{ErrSigTooMuchRPadding, "ErrSigTooMuchRPadding"},
|
|
{ErrSigInvalidSIntID, "ErrSigInvalidSIntID"},
|
|
{ErrSigZeroSLen, "ErrSigZeroSLen"},
|
|
{ErrSigNegativeS, "ErrSigNegativeS"},
|
|
{ErrSigTooMuchSPadding, "ErrSigTooMuchSPadding"},
|
|
{ErrSigHighS, "ErrSigHighS"},
|
|
{ErrNotPushOnly, "ErrNotPushOnly"},
|
|
{ErrPubKeyType, "ErrPubKeyType"},
|
|
{ErrCleanStack, "ErrCleanStack"},
|
|
{ErrDiscourageUpgradableNOPs, "ErrDiscourageUpgradableNOPs"},
|
|
{ErrNegativeLockTime, "ErrNegativeLockTime"},
|
|
{ErrUnsatisfiedLockTime, "ErrUnsatisfiedLockTime"},
|
|
}
|
|
|
|
for i, test := range tests {
|
|
result := test.in.Error()
|
|
if result != test.want {
|
|
t.Errorf("#%d: got: %s want: %s", i, result, test.want)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestError tests the error output for the Error type.
|
|
func TestError(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
in Error
|
|
want string
|
|
}{
|
|
{
|
|
Error{Description: "some error"},
|
|
"some error",
|
|
},
|
|
{
|
|
Error{Description: "human-readable error"},
|
|
"human-readable error",
|
|
},
|
|
}
|
|
|
|
t.Logf("Running %d tests", len(tests))
|
|
for i, test := range tests {
|
|
result := test.in.Error()
|
|
if result != test.want {
|
|
t.Errorf("#%d: got: %s want: %s", i, result, test.want)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestIsDERSigError ensures IsDERSigError returns true for all error kinds that
|
|
// can be returned as a result of non-canonically-encoded DER signatures.
|
|
func TestIsDERSigError(t *testing.T) {
|
|
tests := []struct {
|
|
kind ErrorKind
|
|
want bool
|
|
}{
|
|
{ErrSigTooShort, true},
|
|
{ErrSigTooLong, true},
|
|
{ErrSigInvalidSeqID, true},
|
|
{ErrSigInvalidDataLen, true},
|
|
{ErrSigMissingSTypeID, true},
|
|
{ErrSigMissingSLen, true},
|
|
{ErrSigInvalidSLen, true},
|
|
{ErrSigInvalidRIntID, true},
|
|
{ErrSigZeroRLen, true},
|
|
{ErrSigNegativeR, true},
|
|
{ErrSigTooMuchRPadding, true},
|
|
{ErrSigInvalidSIntID, true},
|
|
{ErrSigZeroSLen, true},
|
|
{ErrSigNegativeS, true},
|
|
{ErrSigTooMuchSPadding, true},
|
|
{ErrSigHighS, true},
|
|
{ErrEvalFalse, false},
|
|
{ErrInvalidIndex, false},
|
|
}
|
|
for _, test := range tests {
|
|
result := IsDERSigError(Error{Err: test.kind})
|
|
if result != test.want {
|
|
t.Errorf("%v: unexpected result -- got: %v want: %v", test.kind,
|
|
result, test.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestErrorKindIsAs ensures both ErrorKind and Error can be identified as being
|
|
// a specific error kind via errors.Is and unwrapped via errors.As.
|
|
func TestErrorKindIsAs(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
err error
|
|
target error
|
|
wantMatch bool
|
|
wantAs ErrorKind
|
|
}{{
|
|
name: "ErrInvalidIndex == ErrInvalidIndex",
|
|
err: ErrInvalidIndex,
|
|
target: ErrInvalidIndex,
|
|
wantMatch: true,
|
|
wantAs: ErrInvalidIndex,
|
|
}, {
|
|
name: "Error.ErrInvalidIndex == ErrInvalidIndex",
|
|
err: scriptError(ErrInvalidIndex, ""),
|
|
target: ErrInvalidIndex,
|
|
wantMatch: true,
|
|
wantAs: ErrInvalidIndex,
|
|
}, {
|
|
name: "ErrEarlyReturn != ErrInvalidIndex",
|
|
err: ErrEarlyReturn,
|
|
target: ErrInvalidIndex,
|
|
wantMatch: false,
|
|
wantAs: ErrEarlyReturn,
|
|
}, {
|
|
name: "Error.ErrEarlyReturn != ErrInvalidIndex",
|
|
err: scriptError(ErrEarlyReturn, ""),
|
|
target: ErrInvalidIndex,
|
|
wantMatch: false,
|
|
wantAs: ErrEarlyReturn,
|
|
}, {
|
|
name: "ErrEarlyReturn != Error.ErrInvalidIndex",
|
|
err: ErrEarlyReturn,
|
|
target: scriptError(ErrInvalidIndex, ""),
|
|
wantMatch: false,
|
|
wantAs: ErrEarlyReturn,
|
|
}, {
|
|
name: "Error.ErrEarlyReturn != Error.ErrInvalidIndex",
|
|
err: scriptError(ErrEarlyReturn, ""),
|
|
target: scriptError(ErrInvalidIndex, ""),
|
|
wantMatch: false,
|
|
wantAs: ErrEarlyReturn,
|
|
}, {
|
|
name: "Error.ErrEarlyReturn != io.EOF",
|
|
err: scriptError(ErrEarlyReturn, ""),
|
|
target: io.EOF,
|
|
wantMatch: false,
|
|
wantAs: ErrEarlyReturn,
|
|
}}
|
|
|
|
for _, test := range tests {
|
|
// Ensure the error matches or not depending on the expected result.
|
|
result := errors.Is(test.err, test.target)
|
|
if result != test.wantMatch {
|
|
t.Errorf("%s: incorrect error identification -- got %v, want %v",
|
|
test.name, result, test.wantMatch)
|
|
continue
|
|
}
|
|
|
|
// Ensure the underlying error kind can be unwrapped is and is the
|
|
// expected kind.
|
|
var kind ErrorKind
|
|
if !errors.As(test.err, &kind) {
|
|
t.Errorf("%s: unable to unwrap to error kind", test.name)
|
|
continue
|
|
}
|
|
if kind != test.wantAs {
|
|
t.Errorf("%s: unexpected unwrapped error kind -- got %v, want %v",
|
|
test.name, kind, test.wantAs)
|
|
continue
|
|
}
|
|
}
|
|
}
|