github.com/lbryio/lbcd@v0.22.119/txscript/error.go (about)

     1  // Copyright (c) 2013-2017 The btcsuite developers
     2  // Copyright (c) 2015-2019 The Decred developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package txscript
     7  
     8  import (
     9  	"fmt"
    10  )
    11  
    12  // ErrorCode identifies a kind of script error.
    13  type ErrorCode int
    14  
    15  // These constants are used to identify a specific Error.
    16  const (
    17  	// ErrInternal is returned if internal consistency checks fail.  In
    18  	// practice this error should never be seen as it would mean there is an
    19  	// error in the engine logic.
    20  	ErrInternal ErrorCode = iota
    21  
    22  	// ---------------------------------------
    23  	// Failures related to improper API usage.
    24  	// ---------------------------------------
    25  
    26  	// ErrInvalidFlags is returned when the passed flags to NewEngine
    27  	// contain an invalid combination.
    28  	ErrInvalidFlags
    29  
    30  	// ErrInvalidIndex is returned when an out-of-bounds index is passed to
    31  	// a function.
    32  	ErrInvalidIndex
    33  
    34  	// ErrUnsupportedAddress is returned when a concrete type that
    35  	// implements a btcutil.Address is not a supported type.
    36  	ErrUnsupportedAddress
    37  
    38  	// ErrNotMultisigScript is returned from CalcMultiSigStats when the
    39  	// provided script is not a multisig script.
    40  	ErrNotMultisigScript
    41  
    42  	// ErrTooManyRequiredSigs is returned from MultiSigScript when the
    43  	// specified number of required signatures is larger than the number of
    44  	// provided public keys.
    45  	ErrTooManyRequiredSigs
    46  
    47  	// ErrTooMuchNullData is returned from NullDataScript when the length of
    48  	// the provided data exceeds MaxDataCarrierSize.
    49  	ErrTooMuchNullData
    50  
    51  	// ErrUnsupportedScriptVersion is returned when an unsupported script
    52  	// version is passed to a function which deals with script analysis.
    53  	ErrUnsupportedScriptVersion
    54  
    55  	// ------------------------------------------
    56  	// Failures related to final execution state.
    57  	// ------------------------------------------
    58  
    59  	// ErrEarlyReturn is returned when OP_RETURN is executed in the script.
    60  	ErrEarlyReturn
    61  
    62  	// ErrEmptyStack is returned when the script evaluated without error,
    63  	// but terminated with an empty top stack element.
    64  	ErrEmptyStack
    65  
    66  	// ErrEvalFalse is returned when the script evaluated without error but
    67  	// terminated with a false top stack element.
    68  	ErrEvalFalse
    69  
    70  	// ErrScriptUnfinished is returned when CheckErrorCondition is called on
    71  	// a script that has not finished executing.
    72  	ErrScriptUnfinished
    73  
    74  	// ErrScriptDone is returned when an attempt to execute an opcode is
    75  	// made once all of them have already been executed.  This can happen
    76  	// due to things such as a second call to Execute or calling Step after
    77  	// all opcodes have already been executed.
    78  	ErrInvalidProgramCounter
    79  
    80  	// -----------------------------------------------------
    81  	// Failures related to exceeding maximum allowed limits.
    82  	// -----------------------------------------------------
    83  
    84  	// ErrScriptTooBig is returned if a script is larger than MaxScriptSize.
    85  	ErrScriptTooBig
    86  
    87  	// ErrElementTooBig is returned if the size of an element to be pushed
    88  	// to the stack is over MaxScriptElementSize.
    89  	ErrElementTooBig
    90  
    91  	// ErrTooManyOperations is returned if a script has more than
    92  	// MaxOpsPerScript opcodes that do not push data.
    93  	ErrTooManyOperations
    94  
    95  	// ErrStackOverflow is returned when stack and altstack combined depth
    96  	// is over the limit.
    97  	ErrStackOverflow
    98  
    99  	// ErrInvalidPubKeyCount is returned when the number of public keys
   100  	// specified for a multsig is either negative or greater than
   101  	// MaxPubKeysPerMultiSig.
   102  	ErrInvalidPubKeyCount
   103  
   104  	// ErrInvalidSignatureCount is returned when the number of signatures
   105  	// specified for a multisig is either negative or greater than the
   106  	// number of public keys.
   107  	ErrInvalidSignatureCount
   108  
   109  	// ErrNumberTooBig is returned when the argument for an opcode that
   110  	// expects numeric input is larger than the expected maximum number of
   111  	// bytes.  For the most part, opcodes that deal with stack manipulation
   112  	// via offsets, arithmetic, numeric comparison, and boolean logic are
   113  	// those that this applies to.  However, any opcode that expects numeric
   114  	// input may fail with this code.
   115  	ErrNumberTooBig
   116  
   117  	// --------------------------------------------
   118  	// Failures related to verification operations.
   119  	// --------------------------------------------
   120  
   121  	// ErrVerify is returned when OP_VERIFY is encountered in a script and
   122  	// the top item on the data stack does not evaluate to true.
   123  	ErrVerify
   124  
   125  	// ErrEqualVerify is returned when OP_EQUALVERIFY is encountered in a
   126  	// script and the top item on the data stack does not evaluate to true.
   127  	ErrEqualVerify
   128  
   129  	// ErrNumEqualVerify is returned when OP_NUMEQUALVERIFY is encountered
   130  	// in a script and the top item on the data stack does not evaluate to
   131  	// true.
   132  	ErrNumEqualVerify
   133  
   134  	// ErrCheckSigVerify is returned when OP_CHECKSIGVERIFY is encountered
   135  	// in a script and the top item on the data stack does not evaluate to
   136  	// true.
   137  	ErrCheckSigVerify
   138  
   139  	// ErrCheckSigVerify is returned when OP_CHECKMULTISIGVERIFY is
   140  	// encountered in a script and the top item on the data stack does not
   141  	// evaluate to true.
   142  	ErrCheckMultiSigVerify
   143  
   144  	// --------------------------------------------
   145  	// Failures related to improper use of opcodes.
   146  	// --------------------------------------------
   147  
   148  	// ErrDisabledOpcode is returned when a disabled opcode is encountered
   149  	// in a script.
   150  	ErrDisabledOpcode
   151  
   152  	// ErrReservedOpcode is returned when an opcode marked as reserved
   153  	// is encountered in a script.
   154  	ErrReservedOpcode
   155  
   156  	// ErrMalformedPush is returned when a data push opcode tries to push
   157  	// more bytes than are left in the script.
   158  	ErrMalformedPush
   159  
   160  	// ErrInvalidStackOperation is returned when a stack operation is
   161  	// attempted with a number that is invalid for the current stack size.
   162  	ErrInvalidStackOperation
   163  
   164  	// ErrUnbalancedConditional is returned when an OP_ELSE or OP_ENDIF is
   165  	// encountered in a script without first having an OP_IF or OP_NOTIF or
   166  	// the end of script is reached without encountering an OP_ENDIF when
   167  	// an OP_IF or OP_NOTIF was previously encountered.
   168  	ErrUnbalancedConditional
   169  
   170  	// ---------------------------------
   171  	// Failures related to malleability.
   172  	// ---------------------------------
   173  
   174  	// ErrMinimalData is returned when the ScriptVerifyMinimalData flag
   175  	// is set and the script contains push operations that do not use
   176  	// the minimal opcode required.
   177  	ErrMinimalData
   178  
   179  	// ErrInvalidSigHashType is returned when a signature hash type is not
   180  	// one of the supported types.
   181  	ErrInvalidSigHashType
   182  
   183  	// ErrSigTooShort is returned when a signature that should be a
   184  	// canonically-encoded DER signature is too short.
   185  	ErrSigTooShort
   186  
   187  	// ErrSigTooLong is returned when a signature that should be a
   188  	// canonically-encoded DER signature is too long.
   189  	ErrSigTooLong
   190  
   191  	// ErrSigInvalidSeqID is returned when a signature that should be a
   192  	// canonically-encoded DER signature does not have the expected ASN.1
   193  	// sequence ID.
   194  	ErrSigInvalidSeqID
   195  
   196  	// ErrSigInvalidDataLen is returned a signature that should be a
   197  	// canonically-encoded DER signature does not specify the correct number
   198  	// of remaining bytes for the R and S portions.
   199  	ErrSigInvalidDataLen
   200  
   201  	// ErrSigMissingSTypeID is returned a signature that should be a
   202  	// canonically-encoded DER signature does not provide the ASN.1 type ID
   203  	// for S.
   204  	ErrSigMissingSTypeID
   205  
   206  	// ErrSigMissingSLen is returned when a signature that should be a
   207  	// canonically-encoded DER signature does not provide the length of S.
   208  	ErrSigMissingSLen
   209  
   210  	// ErrSigInvalidSLen is returned a signature that should be a
   211  	// canonically-encoded DER signature does not specify the correct number
   212  	// of bytes for the S portion.
   213  	ErrSigInvalidSLen
   214  
   215  	// ErrSigInvalidRIntID is returned when a signature that should be a
   216  	// canonically-encoded DER signature does not have the expected ASN.1
   217  	// integer ID for R.
   218  	ErrSigInvalidRIntID
   219  
   220  	// ErrSigZeroRLen is returned when a signature that should be a
   221  	// canonically-encoded DER signature has an R length of zero.
   222  	ErrSigZeroRLen
   223  
   224  	// ErrSigNegativeR is returned when a signature that should be a
   225  	// canonically-encoded DER signature has a negative value for R.
   226  	ErrSigNegativeR
   227  
   228  	// ErrSigTooMuchRPadding is returned when a signature that should be a
   229  	// canonically-encoded DER signature has too much padding for R.
   230  	ErrSigTooMuchRPadding
   231  
   232  	// ErrSigInvalidSIntID is returned when a signature that should be a
   233  	// canonically-encoded DER signature does not have the expected ASN.1
   234  	// integer ID for S.
   235  	ErrSigInvalidSIntID
   236  
   237  	// ErrSigZeroSLen is returned when a signature that should be a
   238  	// canonically-encoded DER signature has an S length of zero.
   239  	ErrSigZeroSLen
   240  
   241  	// ErrSigNegativeS is returned when a signature that should be a
   242  	// canonically-encoded DER signature has a negative value for S.
   243  	ErrSigNegativeS
   244  
   245  	// ErrSigTooMuchSPadding is returned when a signature that should be a
   246  	// canonically-encoded DER signature has too much padding for S.
   247  	ErrSigTooMuchSPadding
   248  
   249  	// ErrSigHighS is returned when the ScriptVerifyLowS flag is set and the
   250  	// script contains any signatures whose S values are higher than the
   251  	// half order.
   252  	ErrSigHighS
   253  
   254  	// ErrNotPushOnly is returned when a script that is required to only
   255  	// push data to the stack performs other operations.  A couple of cases
   256  	// where this applies is for a pay-to-script-hash signature script when
   257  	// bip16 is active and when the ScriptVerifySigPushOnly flag is set.
   258  	ErrNotPushOnly
   259  
   260  	// ErrSigNullDummy is returned when the ScriptStrictMultiSig flag is set
   261  	// and a multisig script has anything other than 0 for the extra dummy
   262  	// argument.
   263  	ErrSigNullDummy
   264  
   265  	// ErrPubKeyType is returned when the ScriptVerifyStrictEncoding
   266  	// flag is set and the script contains invalid public keys.
   267  	ErrPubKeyType
   268  
   269  	// ErrCleanStack is returned when the ScriptVerifyCleanStack flag
   270  	// is set, and after evalution, the stack does not contain only a
   271  	// single element.
   272  	ErrCleanStack
   273  
   274  	// ErrNullFail is returned when the ScriptVerifyNullFail flag is
   275  	// set and signatures are not empty on failed checksig or checkmultisig
   276  	// operations.
   277  	ErrNullFail
   278  
   279  	// ErrWitnessMalleated is returned if ScriptVerifyWitness is set and a
   280  	// native p2wsh program is encountered which has a non-empty sigScript.
   281  	ErrWitnessMalleated
   282  
   283  	// ErrWitnessMalleatedP2SH is returned if ScriptVerifyWitness if set
   284  	// and the validation logic for nested p2sh encounters a sigScript
   285  	// which isn't *exactyl* a datapush of the witness program.
   286  	ErrWitnessMalleatedP2SH
   287  
   288  	// -------------------------------
   289  	// Failures related to soft forks.
   290  	// -------------------------------
   291  
   292  	// ErrDiscourageUpgradableNOPs is returned when the
   293  	// ScriptDiscourageUpgradableNops flag is set and a NOP opcode is
   294  	// encountered in a script.
   295  	ErrDiscourageUpgradableNOPs
   296  
   297  	// ErrNegativeLockTime is returned when a script contains an opcode that
   298  	// interprets a negative lock time.
   299  	ErrNegativeLockTime
   300  
   301  	// ErrUnsatisfiedLockTime is returned when a script contains an opcode
   302  	// that involves a lock time and the required lock time has not been
   303  	// reached.
   304  	ErrUnsatisfiedLockTime
   305  
   306  	// ErrMinimalIf is returned if ScriptVerifyWitness is set and the
   307  	// operand of an OP_IF/OP_NOF_IF are not either an empty vector or
   308  	// [0x01].
   309  	ErrMinimalIf
   310  
   311  	// ErrDiscourageUpgradableWitnessProgram is returned if
   312  	// ScriptVerifyWitness is set and the versino of an executing witness
   313  	// program is outside the set of currently defined witness program
   314  	// vesions.
   315  	ErrDiscourageUpgradableWitnessProgram
   316  
   317  	// ----------------------------------------
   318  	// Failures related to segregated witness.
   319  	// ----------------------------------------
   320  
   321  	// ErrWitnessProgramEmpty is returned if ScriptVerifyWitness is set and
   322  	// the witness stack itself is empty.
   323  	ErrWitnessProgramEmpty
   324  
   325  	// ErrWitnessProgramMismatch is returned if ScriptVerifyWitness is set
   326  	// and the witness itself for a p2wkh witness program isn't *exactly* 2
   327  	// items or if the witness for a p2wsh isn't the sha255 of the witness
   328  	// script.
   329  	ErrWitnessProgramMismatch
   330  
   331  	// ErrWitnessProgramWrongLength is returned if ScriptVerifyWitness is
   332  	// set and the length of the witness program violates the length as
   333  	// dictated by the current witness version.
   334  	ErrWitnessProgramWrongLength
   335  
   336  	// ErrWitnessUnexpected is returned if ScriptVerifyWitness is set and a
   337  	// transaction includes witness data but doesn't spend an which is a
   338  	// witness program (nested or native).
   339  	ErrWitnessUnexpected
   340  
   341  	// ErrWitnessPubKeyType is returned if ScriptVerifyWitness is set and
   342  	// the public key used in either a check-sig or check-multi-sig isn't
   343  	// serialized in a compressed format.
   344  	ErrWitnessPubKeyType
   345  
   346  	// numErrorCodes is the maximum error code number used in tests.  This
   347  	// entry MUST be the last entry in the enum.
   348  	numErrorCodes
   349  )
   350  
   351  // Map of ErrorCode values back to their constant names for pretty printing.
   352  var errorCodeStrings = map[ErrorCode]string{
   353  	ErrInternal:                           "ErrInternal",
   354  	ErrInvalidFlags:                       "ErrInvalidFlags",
   355  	ErrInvalidIndex:                       "ErrInvalidIndex",
   356  	ErrUnsupportedAddress:                 "ErrUnsupportedAddress",
   357  	ErrNotMultisigScript:                  "ErrNotMultisigScript",
   358  	ErrTooManyRequiredSigs:                "ErrTooManyRequiredSigs",
   359  	ErrTooMuchNullData:                    "ErrTooMuchNullData",
   360  	ErrUnsupportedScriptVersion:           "ErrUnsupportedScriptVersion",
   361  	ErrEarlyReturn:                        "ErrEarlyReturn",
   362  	ErrEmptyStack:                         "ErrEmptyStack",
   363  	ErrEvalFalse:                          "ErrEvalFalse",
   364  	ErrScriptUnfinished:                   "ErrScriptUnfinished",
   365  	ErrInvalidProgramCounter:              "ErrInvalidProgramCounter",
   366  	ErrScriptTooBig:                       "ErrScriptTooBig",
   367  	ErrElementTooBig:                      "ErrElementTooBig",
   368  	ErrTooManyOperations:                  "ErrTooManyOperations",
   369  	ErrStackOverflow:                      "ErrStackOverflow",
   370  	ErrInvalidPubKeyCount:                 "ErrInvalidPubKeyCount",
   371  	ErrInvalidSignatureCount:              "ErrInvalidSignatureCount",
   372  	ErrNumberTooBig:                       "ErrNumberTooBig",
   373  	ErrVerify:                             "ErrVerify",
   374  	ErrEqualVerify:                        "ErrEqualVerify",
   375  	ErrNumEqualVerify:                     "ErrNumEqualVerify",
   376  	ErrCheckSigVerify:                     "ErrCheckSigVerify",
   377  	ErrCheckMultiSigVerify:                "ErrCheckMultiSigVerify",
   378  	ErrDisabledOpcode:                     "ErrDisabledOpcode",
   379  	ErrReservedOpcode:                     "ErrReservedOpcode",
   380  	ErrMalformedPush:                      "ErrMalformedPush",
   381  	ErrInvalidStackOperation:              "ErrInvalidStackOperation",
   382  	ErrUnbalancedConditional:              "ErrUnbalancedConditional",
   383  	ErrMinimalData:                        "ErrMinimalData",
   384  	ErrInvalidSigHashType:                 "ErrInvalidSigHashType",
   385  	ErrSigTooShort:                        "ErrSigTooShort",
   386  	ErrSigTooLong:                         "ErrSigTooLong",
   387  	ErrSigInvalidSeqID:                    "ErrSigInvalidSeqID",
   388  	ErrSigInvalidDataLen:                  "ErrSigInvalidDataLen",
   389  	ErrSigMissingSTypeID:                  "ErrSigMissingSTypeID",
   390  	ErrSigMissingSLen:                     "ErrSigMissingSLen",
   391  	ErrSigInvalidSLen:                     "ErrSigInvalidSLen",
   392  	ErrSigInvalidRIntID:                   "ErrSigInvalidRIntID",
   393  	ErrSigZeroRLen:                        "ErrSigZeroRLen",
   394  	ErrSigNegativeR:                       "ErrSigNegativeR",
   395  	ErrSigTooMuchRPadding:                 "ErrSigTooMuchRPadding",
   396  	ErrSigInvalidSIntID:                   "ErrSigInvalidSIntID",
   397  	ErrSigZeroSLen:                        "ErrSigZeroSLen",
   398  	ErrSigNegativeS:                       "ErrSigNegativeS",
   399  	ErrSigTooMuchSPadding:                 "ErrSigTooMuchSPadding",
   400  	ErrSigHighS:                           "ErrSigHighS",
   401  	ErrNotPushOnly:                        "ErrNotPushOnly",
   402  	ErrSigNullDummy:                       "ErrSigNullDummy",
   403  	ErrPubKeyType:                         "ErrPubKeyType",
   404  	ErrCleanStack:                         "ErrCleanStack",
   405  	ErrNullFail:                           "ErrNullFail",
   406  	ErrDiscourageUpgradableNOPs:           "ErrDiscourageUpgradableNOPs",
   407  	ErrNegativeLockTime:                   "ErrNegativeLockTime",
   408  	ErrUnsatisfiedLockTime:                "ErrUnsatisfiedLockTime",
   409  	ErrWitnessProgramEmpty:                "ErrWitnessProgramEmpty",
   410  	ErrWitnessProgramMismatch:             "ErrWitnessProgramMismatch",
   411  	ErrWitnessProgramWrongLength:          "ErrWitnessProgramWrongLength",
   412  	ErrWitnessMalleated:                   "ErrWitnessMalleated",
   413  	ErrWitnessMalleatedP2SH:               "ErrWitnessMalleatedP2SH",
   414  	ErrWitnessUnexpected:                  "ErrWitnessUnexpected",
   415  	ErrMinimalIf:                          "ErrMinimalIf",
   416  	ErrWitnessPubKeyType:                  "ErrWitnessPubKeyType",
   417  	ErrDiscourageUpgradableWitnessProgram: "ErrDiscourageUpgradableWitnessProgram",
   418  }
   419  
   420  // String returns the ErrorCode as a human-readable name.
   421  func (e ErrorCode) String() string {
   422  	if s := errorCodeStrings[e]; s != "" {
   423  		return s
   424  	}
   425  	return fmt.Sprintf("Unknown ErrorCode (%d)", int(e))
   426  }
   427  
   428  // Error identifies a script-related error.  It is used to indicate three
   429  // classes of errors:
   430  //  1. Script execution failures due to violating one of the many requirements
   431  //     imposed by the script engine or evaluating to false
   432  //  2. Improper API usage by callers
   433  //  3. Internal consistency check failures
   434  //
   435  // The caller can use type assertions on the returned errors to access the
   436  // ErrorCode field to ascertain the specific reason for the error.  As an
   437  // additional convenience, the caller may make use of the IsErrorCode function
   438  // to check for a specific error code.
   439  type Error struct {
   440  	ErrorCode   ErrorCode
   441  	Description string
   442  }
   443  
   444  // Error satisfies the error interface and prints human-readable errors.
   445  func (e Error) Error() string {
   446  	return e.Description
   447  }
   448  
   449  // scriptError creates an Error given a set of arguments.
   450  func scriptError(c ErrorCode, desc string) Error {
   451  	return Error{ErrorCode: c, Description: desc}
   452  }
   453  
   454  // IsErrorCode returns whether or not the provided error is a script error with
   455  // the provided error code.
   456  func IsErrorCode(err error, c ErrorCode) bool {
   457  	serr, ok := err.(Error)
   458  	return ok && serr.ErrorCode == c
   459  }