github.com/palcoin-project/palcd@v1.0.0/txscript/opcode.go (about)

     1  // Copyright (c) 2013-2017 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package txscript
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/sha1"
    10  	"crypto/sha256"
    11  	"encoding/binary"
    12  	"fmt"
    13  	"hash"
    14  
    15  	"golang.org/x/crypto/ripemd160"
    16  
    17  	"github.com/palcoin-project/palcd/btcec"
    18  	"github.com/palcoin-project/palcd/chaincfg/chainhash"
    19  	"github.com/palcoin-project/palcd/wire"
    20  )
    21  
    22  // An opcode defines the information related to a txscript opcode.  opfunc, if
    23  // present, is the function to call to perform the opcode on the script.  The
    24  // current script is passed in as a slice with the first member being the opcode
    25  // itself.
    26  type opcode struct {
    27  	value  byte
    28  	name   string
    29  	length int
    30  	opfunc func(*parsedOpcode, *Engine) error
    31  }
    32  
    33  // These constants are the values of the official opcodes used on the btc wiki,
    34  // in bitcoin core and in most if not all other references and software related
    35  // to handling BTC scripts.
    36  const (
    37  	OP_0                   = 0x00 // 0
    38  	OP_FALSE               = 0x00 // 0 - AKA OP_0
    39  	OP_DATA_1              = 0x01 // 1
    40  	OP_DATA_2              = 0x02 // 2
    41  	OP_DATA_3              = 0x03 // 3
    42  	OP_DATA_4              = 0x04 // 4
    43  	OP_DATA_5              = 0x05 // 5
    44  	OP_DATA_6              = 0x06 // 6
    45  	OP_DATA_7              = 0x07 // 7
    46  	OP_DATA_8              = 0x08 // 8
    47  	OP_DATA_9              = 0x09 // 9
    48  	OP_DATA_10             = 0x0a // 10
    49  	OP_DATA_11             = 0x0b // 11
    50  	OP_DATA_12             = 0x0c // 12
    51  	OP_DATA_13             = 0x0d // 13
    52  	OP_DATA_14             = 0x0e // 14
    53  	OP_DATA_15             = 0x0f // 15
    54  	OP_DATA_16             = 0x10 // 16
    55  	OP_DATA_17             = 0x11 // 17
    56  	OP_DATA_18             = 0x12 // 18
    57  	OP_DATA_19             = 0x13 // 19
    58  	OP_DATA_20             = 0x14 // 20
    59  	OP_DATA_21             = 0x15 // 21
    60  	OP_DATA_22             = 0x16 // 22
    61  	OP_DATA_23             = 0x17 // 23
    62  	OP_DATA_24             = 0x18 // 24
    63  	OP_DATA_25             = 0x19 // 25
    64  	OP_DATA_26             = 0x1a // 26
    65  	OP_DATA_27             = 0x1b // 27
    66  	OP_DATA_28             = 0x1c // 28
    67  	OP_DATA_29             = 0x1d // 29
    68  	OP_DATA_30             = 0x1e // 30
    69  	OP_DATA_31             = 0x1f // 31
    70  	OP_DATA_32             = 0x20 // 32
    71  	OP_DATA_33             = 0x21 // 33
    72  	OP_DATA_34             = 0x22 // 34
    73  	OP_DATA_35             = 0x23 // 35
    74  	OP_DATA_36             = 0x24 // 36
    75  	OP_DATA_37             = 0x25 // 37
    76  	OP_DATA_38             = 0x26 // 38
    77  	OP_DATA_39             = 0x27 // 39
    78  	OP_DATA_40             = 0x28 // 40
    79  	OP_DATA_41             = 0x29 // 41
    80  	OP_DATA_42             = 0x2a // 42
    81  	OP_DATA_43             = 0x2b // 43
    82  	OP_DATA_44             = 0x2c // 44
    83  	OP_DATA_45             = 0x2d // 45
    84  	OP_DATA_46             = 0x2e // 46
    85  	OP_DATA_47             = 0x2f // 47
    86  	OP_DATA_48             = 0x30 // 48
    87  	OP_DATA_49             = 0x31 // 49
    88  	OP_DATA_50             = 0x32 // 50
    89  	OP_DATA_51             = 0x33 // 51
    90  	OP_DATA_52             = 0x34 // 52
    91  	OP_DATA_53             = 0x35 // 53
    92  	OP_DATA_54             = 0x36 // 54
    93  	OP_DATA_55             = 0x37 // 55
    94  	OP_DATA_56             = 0x38 // 56
    95  	OP_DATA_57             = 0x39 // 57
    96  	OP_DATA_58             = 0x3a // 58
    97  	OP_DATA_59             = 0x3b // 59
    98  	OP_DATA_60             = 0x3c // 60
    99  	OP_DATA_61             = 0x3d // 61
   100  	OP_DATA_62             = 0x3e // 62
   101  	OP_DATA_63             = 0x3f // 63
   102  	OP_DATA_64             = 0x40 // 64
   103  	OP_DATA_65             = 0x41 // 65
   104  	OP_DATA_66             = 0x42 // 66
   105  	OP_DATA_67             = 0x43 // 67
   106  	OP_DATA_68             = 0x44 // 68
   107  	OP_DATA_69             = 0x45 // 69
   108  	OP_DATA_70             = 0x46 // 70
   109  	OP_DATA_71             = 0x47 // 71
   110  	OP_DATA_72             = 0x48 // 72
   111  	OP_DATA_73             = 0x49 // 73
   112  	OP_DATA_74             = 0x4a // 74
   113  	OP_DATA_75             = 0x4b // 75
   114  	OP_PUSHDATA1           = 0x4c // 76
   115  	OP_PUSHDATA2           = 0x4d // 77
   116  	OP_PUSHDATA4           = 0x4e // 78
   117  	OP_1NEGATE             = 0x4f // 79
   118  	OP_RESERVED            = 0x50 // 80
   119  	OP_1                   = 0x51 // 81 - AKA OP_TRUE
   120  	OP_TRUE                = 0x51 // 81
   121  	OP_2                   = 0x52 // 82
   122  	OP_3                   = 0x53 // 83
   123  	OP_4                   = 0x54 // 84
   124  	OP_5                   = 0x55 // 85
   125  	OP_6                   = 0x56 // 86
   126  	OP_7                   = 0x57 // 87
   127  	OP_8                   = 0x58 // 88
   128  	OP_9                   = 0x59 // 89
   129  	OP_10                  = 0x5a // 90
   130  	OP_11                  = 0x5b // 91
   131  	OP_12                  = 0x5c // 92
   132  	OP_13                  = 0x5d // 93
   133  	OP_14                  = 0x5e // 94
   134  	OP_15                  = 0x5f // 95
   135  	OP_16                  = 0x60 // 96
   136  	OP_NOP                 = 0x61 // 97
   137  	OP_VER                 = 0x62 // 98
   138  	OP_IF                  = 0x63 // 99
   139  	OP_NOTIF               = 0x64 // 100
   140  	OP_VERIF               = 0x65 // 101
   141  	OP_VERNOTIF            = 0x66 // 102
   142  	OP_ELSE                = 0x67 // 103
   143  	OP_ENDIF               = 0x68 // 104
   144  	OP_VERIFY              = 0x69 // 105
   145  	OP_RETURN              = 0x6a // 106
   146  	OP_TOALTSTACK          = 0x6b // 107
   147  	OP_FROMALTSTACK        = 0x6c // 108
   148  	OP_2DROP               = 0x6d // 109
   149  	OP_2DUP                = 0x6e // 110
   150  	OP_3DUP                = 0x6f // 111
   151  	OP_2OVER               = 0x70 // 112
   152  	OP_2ROT                = 0x71 // 113
   153  	OP_2SWAP               = 0x72 // 114
   154  	OP_IFDUP               = 0x73 // 115
   155  	OP_DEPTH               = 0x74 // 116
   156  	OP_DROP                = 0x75 // 117
   157  	OP_DUP                 = 0x76 // 118
   158  	OP_NIP                 = 0x77 // 119
   159  	OP_OVER                = 0x78 // 120
   160  	OP_PICK                = 0x79 // 121
   161  	OP_ROLL                = 0x7a // 122
   162  	OP_ROT                 = 0x7b // 123
   163  	OP_SWAP                = 0x7c // 124
   164  	OP_TUCK                = 0x7d // 125
   165  	OP_CAT                 = 0x7e // 126
   166  	OP_SUBSTR              = 0x7f // 127
   167  	OP_LEFT                = 0x80 // 128
   168  	OP_RIGHT               = 0x81 // 129
   169  	OP_SIZE                = 0x82 // 130
   170  	OP_INVERT              = 0x83 // 131
   171  	OP_AND                 = 0x84 // 132
   172  	OP_OR                  = 0x85 // 133
   173  	OP_XOR                 = 0x86 // 134
   174  	OP_EQUAL               = 0x87 // 135
   175  	OP_EQUALVERIFY         = 0x88 // 136
   176  	OP_RESERVED1           = 0x89 // 137
   177  	OP_RESERVED2           = 0x8a // 138
   178  	OP_1ADD                = 0x8b // 139
   179  	OP_1SUB                = 0x8c // 140
   180  	OP_2MUL                = 0x8d // 141
   181  	OP_2DIV                = 0x8e // 142
   182  	OP_NEGATE              = 0x8f // 143
   183  	OP_ABS                 = 0x90 // 144
   184  	OP_NOT                 = 0x91 // 145
   185  	OP_0NOTEQUAL           = 0x92 // 146
   186  	OP_ADD                 = 0x93 // 147
   187  	OP_SUB                 = 0x94 // 148
   188  	OP_MUL                 = 0x95 // 149
   189  	OP_DIV                 = 0x96 // 150
   190  	OP_MOD                 = 0x97 // 151
   191  	OP_LSHIFT              = 0x98 // 152
   192  	OP_RSHIFT              = 0x99 // 153
   193  	OP_BOOLAND             = 0x9a // 154
   194  	OP_BOOLOR              = 0x9b // 155
   195  	OP_NUMEQUAL            = 0x9c // 156
   196  	OP_NUMEQUALVERIFY      = 0x9d // 157
   197  	OP_NUMNOTEQUAL         = 0x9e // 158
   198  	OP_LESSTHAN            = 0x9f // 159
   199  	OP_GREATERTHAN         = 0xa0 // 160
   200  	OP_LESSTHANOREQUAL     = 0xa1 // 161
   201  	OP_GREATERTHANOREQUAL  = 0xa2 // 162
   202  	OP_MIN                 = 0xa3 // 163
   203  	OP_MAX                 = 0xa4 // 164
   204  	OP_WITHIN              = 0xa5 // 165
   205  	OP_RIPEMD160           = 0xa6 // 166
   206  	OP_SHA1                = 0xa7 // 167
   207  	OP_SHA256              = 0xa8 // 168
   208  	OP_HASH160             = 0xa9 // 169
   209  	OP_HASH256             = 0xaa // 170
   210  	OP_CODESEPARATOR       = 0xab // 171
   211  	OP_CHECKSIG            = 0xac // 172
   212  	OP_CHECKSIGVERIFY      = 0xad // 173
   213  	OP_CHECKMULTISIG       = 0xae // 174
   214  	OP_CHECKMULTISIGVERIFY = 0xaf // 175
   215  	OP_NOP1                = 0xb0 // 176
   216  	OP_NOP2                = 0xb1 // 177
   217  	OP_CHECKLOCKTIMEVERIFY = 0xb1 // 177 - AKA OP_NOP2
   218  	OP_NOP3                = 0xb2 // 178
   219  	OP_CHECKSEQUENCEVERIFY = 0xb2 // 178 - AKA OP_NOP3
   220  	OP_NOP4                = 0xb3 // 179
   221  	OP_NOP5                = 0xb4 // 180
   222  	OP_NOP6                = 0xb5 // 181
   223  	OP_NOP7                = 0xb6 // 182
   224  	OP_NOP8                = 0xb7 // 183
   225  	OP_NOP9                = 0xb8 // 184
   226  	OP_NOP10               = 0xb9 // 185
   227  	OP_UNKNOWN186          = 0xba // 186
   228  	OP_UNKNOWN187          = 0xbb // 187
   229  	OP_UNKNOWN188          = 0xbc // 188
   230  	OP_UNKNOWN189          = 0xbd // 189
   231  	OP_UNKNOWN190          = 0xbe // 190
   232  	OP_UNKNOWN191          = 0xbf // 191
   233  	OP_UNKNOWN192          = 0xc0 // 192
   234  	OP_UNKNOWN193          = 0xc1 // 193
   235  	OP_UNKNOWN194          = 0xc2 // 194
   236  	OP_UNKNOWN195          = 0xc3 // 195
   237  	OP_UNKNOWN196          = 0xc4 // 196
   238  	OP_UNKNOWN197          = 0xc5 // 197
   239  	OP_UNKNOWN198          = 0xc6 // 198
   240  	OP_UNKNOWN199          = 0xc7 // 199
   241  	OP_UNKNOWN200          = 0xc8 // 200
   242  	OP_UNKNOWN201          = 0xc9 // 201
   243  	OP_UNKNOWN202          = 0xca // 202
   244  	OP_UNKNOWN203          = 0xcb // 203
   245  	OP_UNKNOWN204          = 0xcc // 204
   246  	OP_UNKNOWN205          = 0xcd // 205
   247  	OP_UNKNOWN206          = 0xce // 206
   248  	OP_UNKNOWN207          = 0xcf // 207
   249  	OP_UNKNOWN208          = 0xd0 // 208
   250  	OP_UNKNOWN209          = 0xd1 // 209
   251  	OP_UNKNOWN210          = 0xd2 // 210
   252  	OP_UNKNOWN211          = 0xd3 // 211
   253  	OP_UNKNOWN212          = 0xd4 // 212
   254  	OP_UNKNOWN213          = 0xd5 // 213
   255  	OP_UNKNOWN214          = 0xd6 // 214
   256  	OP_UNKNOWN215          = 0xd7 // 215
   257  	OP_UNKNOWN216          = 0xd8 // 216
   258  	OP_UNKNOWN217          = 0xd9 // 217
   259  	OP_UNKNOWN218          = 0xda // 218
   260  	OP_UNKNOWN219          = 0xdb // 219
   261  	OP_UNKNOWN220          = 0xdc // 220
   262  	OP_UNKNOWN221          = 0xdd // 221
   263  	OP_UNKNOWN222          = 0xde // 222
   264  	OP_UNKNOWN223          = 0xdf // 223
   265  	OP_UNKNOWN224          = 0xe0 // 224
   266  	OP_UNKNOWN225          = 0xe1 // 225
   267  	OP_UNKNOWN226          = 0xe2 // 226
   268  	OP_UNKNOWN227          = 0xe3 // 227
   269  	OP_UNKNOWN228          = 0xe4 // 228
   270  	OP_UNKNOWN229          = 0xe5 // 229
   271  	OP_UNKNOWN230          = 0xe6 // 230
   272  	OP_UNKNOWN231          = 0xe7 // 231
   273  	OP_UNKNOWN232          = 0xe8 // 232
   274  	OP_UNKNOWN233          = 0xe9 // 233
   275  	OP_UNKNOWN234          = 0xea // 234
   276  	OP_UNKNOWN235          = 0xeb // 235
   277  	OP_UNKNOWN236          = 0xec // 236
   278  	OP_UNKNOWN237          = 0xed // 237
   279  	OP_UNKNOWN238          = 0xee // 238
   280  	OP_UNKNOWN239          = 0xef // 239
   281  	OP_UNKNOWN240          = 0xf0 // 240
   282  	OP_UNKNOWN241          = 0xf1 // 241
   283  	OP_UNKNOWN242          = 0xf2 // 242
   284  	OP_UNKNOWN243          = 0xf3 // 243
   285  	OP_UNKNOWN244          = 0xf4 // 244
   286  	OP_UNKNOWN245          = 0xf5 // 245
   287  	OP_UNKNOWN246          = 0xf6 // 246
   288  	OP_UNKNOWN247          = 0xf7 // 247
   289  	OP_UNKNOWN248          = 0xf8 // 248
   290  	OP_UNKNOWN249          = 0xf9 // 249
   291  	OP_SMALLINTEGER        = 0xfa // 250 - bitcoin core internal
   292  	OP_PUBKEYS             = 0xfb // 251 - bitcoin core internal
   293  	OP_UNKNOWN252          = 0xfc // 252
   294  	OP_PUBKEYHASH          = 0xfd // 253 - bitcoin core internal
   295  	OP_PUBKEY              = 0xfe // 254 - bitcoin core internal
   296  	OP_INVALIDOPCODE       = 0xff // 255 - bitcoin core internal
   297  )
   298  
   299  // Conditional execution constants.
   300  const (
   301  	OpCondFalse = 0
   302  	OpCondTrue  = 1
   303  	OpCondSkip  = 2
   304  )
   305  
   306  // opcodeArray holds details about all possible opcodes such as how many bytes
   307  // the opcode and any associated data should take, its human-readable name, and
   308  // the handler function.
   309  var opcodeArray = [256]opcode{
   310  	// Data push opcodes.
   311  	OP_FALSE:     {OP_FALSE, "OP_0", 1, opcodeFalse},
   312  	OP_DATA_1:    {OP_DATA_1, "OP_DATA_1", 2, opcodePushData},
   313  	OP_DATA_2:    {OP_DATA_2, "OP_DATA_2", 3, opcodePushData},
   314  	OP_DATA_3:    {OP_DATA_3, "OP_DATA_3", 4, opcodePushData},
   315  	OP_DATA_4:    {OP_DATA_4, "OP_DATA_4", 5, opcodePushData},
   316  	OP_DATA_5:    {OP_DATA_5, "OP_DATA_5", 6, opcodePushData},
   317  	OP_DATA_6:    {OP_DATA_6, "OP_DATA_6", 7, opcodePushData},
   318  	OP_DATA_7:    {OP_DATA_7, "OP_DATA_7", 8, opcodePushData},
   319  	OP_DATA_8:    {OP_DATA_8, "OP_DATA_8", 9, opcodePushData},
   320  	OP_DATA_9:    {OP_DATA_9, "OP_DATA_9", 10, opcodePushData},
   321  	OP_DATA_10:   {OP_DATA_10, "OP_DATA_10", 11, opcodePushData},
   322  	OP_DATA_11:   {OP_DATA_11, "OP_DATA_11", 12, opcodePushData},
   323  	OP_DATA_12:   {OP_DATA_12, "OP_DATA_12", 13, opcodePushData},
   324  	OP_DATA_13:   {OP_DATA_13, "OP_DATA_13", 14, opcodePushData},
   325  	OP_DATA_14:   {OP_DATA_14, "OP_DATA_14", 15, opcodePushData},
   326  	OP_DATA_15:   {OP_DATA_15, "OP_DATA_15", 16, opcodePushData},
   327  	OP_DATA_16:   {OP_DATA_16, "OP_DATA_16", 17, opcodePushData},
   328  	OP_DATA_17:   {OP_DATA_17, "OP_DATA_17", 18, opcodePushData},
   329  	OP_DATA_18:   {OP_DATA_18, "OP_DATA_18", 19, opcodePushData},
   330  	OP_DATA_19:   {OP_DATA_19, "OP_DATA_19", 20, opcodePushData},
   331  	OP_DATA_20:   {OP_DATA_20, "OP_DATA_20", 21, opcodePushData},
   332  	OP_DATA_21:   {OP_DATA_21, "OP_DATA_21", 22, opcodePushData},
   333  	OP_DATA_22:   {OP_DATA_22, "OP_DATA_22", 23, opcodePushData},
   334  	OP_DATA_23:   {OP_DATA_23, "OP_DATA_23", 24, opcodePushData},
   335  	OP_DATA_24:   {OP_DATA_24, "OP_DATA_24", 25, opcodePushData},
   336  	OP_DATA_25:   {OP_DATA_25, "OP_DATA_25", 26, opcodePushData},
   337  	OP_DATA_26:   {OP_DATA_26, "OP_DATA_26", 27, opcodePushData},
   338  	OP_DATA_27:   {OP_DATA_27, "OP_DATA_27", 28, opcodePushData},
   339  	OP_DATA_28:   {OP_DATA_28, "OP_DATA_28", 29, opcodePushData},
   340  	OP_DATA_29:   {OP_DATA_29, "OP_DATA_29", 30, opcodePushData},
   341  	OP_DATA_30:   {OP_DATA_30, "OP_DATA_30", 31, opcodePushData},
   342  	OP_DATA_31:   {OP_DATA_31, "OP_DATA_31", 32, opcodePushData},
   343  	OP_DATA_32:   {OP_DATA_32, "OP_DATA_32", 33, opcodePushData},
   344  	OP_DATA_33:   {OP_DATA_33, "OP_DATA_33", 34, opcodePushData},
   345  	OP_DATA_34:   {OP_DATA_34, "OP_DATA_34", 35, opcodePushData},
   346  	OP_DATA_35:   {OP_DATA_35, "OP_DATA_35", 36, opcodePushData},
   347  	OP_DATA_36:   {OP_DATA_36, "OP_DATA_36", 37, opcodePushData},
   348  	OP_DATA_37:   {OP_DATA_37, "OP_DATA_37", 38, opcodePushData},
   349  	OP_DATA_38:   {OP_DATA_38, "OP_DATA_38", 39, opcodePushData},
   350  	OP_DATA_39:   {OP_DATA_39, "OP_DATA_39", 40, opcodePushData},
   351  	OP_DATA_40:   {OP_DATA_40, "OP_DATA_40", 41, opcodePushData},
   352  	OP_DATA_41:   {OP_DATA_41, "OP_DATA_41", 42, opcodePushData},
   353  	OP_DATA_42:   {OP_DATA_42, "OP_DATA_42", 43, opcodePushData},
   354  	OP_DATA_43:   {OP_DATA_43, "OP_DATA_43", 44, opcodePushData},
   355  	OP_DATA_44:   {OP_DATA_44, "OP_DATA_44", 45, opcodePushData},
   356  	OP_DATA_45:   {OP_DATA_45, "OP_DATA_45", 46, opcodePushData},
   357  	OP_DATA_46:   {OP_DATA_46, "OP_DATA_46", 47, opcodePushData},
   358  	OP_DATA_47:   {OP_DATA_47, "OP_DATA_47", 48, opcodePushData},
   359  	OP_DATA_48:   {OP_DATA_48, "OP_DATA_48", 49, opcodePushData},
   360  	OP_DATA_49:   {OP_DATA_49, "OP_DATA_49", 50, opcodePushData},
   361  	OP_DATA_50:   {OP_DATA_50, "OP_DATA_50", 51, opcodePushData},
   362  	OP_DATA_51:   {OP_DATA_51, "OP_DATA_51", 52, opcodePushData},
   363  	OP_DATA_52:   {OP_DATA_52, "OP_DATA_52", 53, opcodePushData},
   364  	OP_DATA_53:   {OP_DATA_53, "OP_DATA_53", 54, opcodePushData},
   365  	OP_DATA_54:   {OP_DATA_54, "OP_DATA_54", 55, opcodePushData},
   366  	OP_DATA_55:   {OP_DATA_55, "OP_DATA_55", 56, opcodePushData},
   367  	OP_DATA_56:   {OP_DATA_56, "OP_DATA_56", 57, opcodePushData},
   368  	OP_DATA_57:   {OP_DATA_57, "OP_DATA_57", 58, opcodePushData},
   369  	OP_DATA_58:   {OP_DATA_58, "OP_DATA_58", 59, opcodePushData},
   370  	OP_DATA_59:   {OP_DATA_59, "OP_DATA_59", 60, opcodePushData},
   371  	OP_DATA_60:   {OP_DATA_60, "OP_DATA_60", 61, opcodePushData},
   372  	OP_DATA_61:   {OP_DATA_61, "OP_DATA_61", 62, opcodePushData},
   373  	OP_DATA_62:   {OP_DATA_62, "OP_DATA_62", 63, opcodePushData},
   374  	OP_DATA_63:   {OP_DATA_63, "OP_DATA_63", 64, opcodePushData},
   375  	OP_DATA_64:   {OP_DATA_64, "OP_DATA_64", 65, opcodePushData},
   376  	OP_DATA_65:   {OP_DATA_65, "OP_DATA_65", 66, opcodePushData},
   377  	OP_DATA_66:   {OP_DATA_66, "OP_DATA_66", 67, opcodePushData},
   378  	OP_DATA_67:   {OP_DATA_67, "OP_DATA_67", 68, opcodePushData},
   379  	OP_DATA_68:   {OP_DATA_68, "OP_DATA_68", 69, opcodePushData},
   380  	OP_DATA_69:   {OP_DATA_69, "OP_DATA_69", 70, opcodePushData},
   381  	OP_DATA_70:   {OP_DATA_70, "OP_DATA_70", 71, opcodePushData},
   382  	OP_DATA_71:   {OP_DATA_71, "OP_DATA_71", 72, opcodePushData},
   383  	OP_DATA_72:   {OP_DATA_72, "OP_DATA_72", 73, opcodePushData},
   384  	OP_DATA_73:   {OP_DATA_73, "OP_DATA_73", 74, opcodePushData},
   385  	OP_DATA_74:   {OP_DATA_74, "OP_DATA_74", 75, opcodePushData},
   386  	OP_DATA_75:   {OP_DATA_75, "OP_DATA_75", 76, opcodePushData},
   387  	OP_PUSHDATA1: {OP_PUSHDATA1, "OP_PUSHDATA1", -1, opcodePushData},
   388  	OP_PUSHDATA2: {OP_PUSHDATA2, "OP_PUSHDATA2", -2, opcodePushData},
   389  	OP_PUSHDATA4: {OP_PUSHDATA4, "OP_PUSHDATA4", -4, opcodePushData},
   390  	OP_1NEGATE:   {OP_1NEGATE, "OP_1NEGATE", 1, opcode1Negate},
   391  	OP_RESERVED:  {OP_RESERVED, "OP_RESERVED", 1, opcodeReserved},
   392  	OP_TRUE:      {OP_TRUE, "OP_1", 1, opcodeN},
   393  	OP_2:         {OP_2, "OP_2", 1, opcodeN},
   394  	OP_3:         {OP_3, "OP_3", 1, opcodeN},
   395  	OP_4:         {OP_4, "OP_4", 1, opcodeN},
   396  	OP_5:         {OP_5, "OP_5", 1, opcodeN},
   397  	OP_6:         {OP_6, "OP_6", 1, opcodeN},
   398  	OP_7:         {OP_7, "OP_7", 1, opcodeN},
   399  	OP_8:         {OP_8, "OP_8", 1, opcodeN},
   400  	OP_9:         {OP_9, "OP_9", 1, opcodeN},
   401  	OP_10:        {OP_10, "OP_10", 1, opcodeN},
   402  	OP_11:        {OP_11, "OP_11", 1, opcodeN},
   403  	OP_12:        {OP_12, "OP_12", 1, opcodeN},
   404  	OP_13:        {OP_13, "OP_13", 1, opcodeN},
   405  	OP_14:        {OP_14, "OP_14", 1, opcodeN},
   406  	OP_15:        {OP_15, "OP_15", 1, opcodeN},
   407  	OP_16:        {OP_16, "OP_16", 1, opcodeN},
   408  
   409  	// Control opcodes.
   410  	OP_NOP:                 {OP_NOP, "OP_NOP", 1, opcodeNop},
   411  	OP_VER:                 {OP_VER, "OP_VER", 1, opcodeReserved},
   412  	OP_IF:                  {OP_IF, "OP_IF", 1, opcodeIf},
   413  	OP_NOTIF:               {OP_NOTIF, "OP_NOTIF", 1, opcodeNotIf},
   414  	OP_VERIF:               {OP_VERIF, "OP_VERIF", 1, opcodeReserved},
   415  	OP_VERNOTIF:            {OP_VERNOTIF, "OP_VERNOTIF", 1, opcodeReserved},
   416  	OP_ELSE:                {OP_ELSE, "OP_ELSE", 1, opcodeElse},
   417  	OP_ENDIF:               {OP_ENDIF, "OP_ENDIF", 1, opcodeEndif},
   418  	OP_VERIFY:              {OP_VERIFY, "OP_VERIFY", 1, opcodeVerify},
   419  	OP_RETURN:              {OP_RETURN, "OP_RETURN", 1, opcodeReturn},
   420  	OP_CHECKLOCKTIMEVERIFY: {OP_CHECKLOCKTIMEVERIFY, "OP_CHECKLOCKTIMEVERIFY", 1, opcodeCheckLockTimeVerify},
   421  	OP_CHECKSEQUENCEVERIFY: {OP_CHECKSEQUENCEVERIFY, "OP_CHECKSEQUENCEVERIFY", 1, opcodeCheckSequenceVerify},
   422  
   423  	// Stack opcodes.
   424  	OP_TOALTSTACK:   {OP_TOALTSTACK, "OP_TOALTSTACK", 1, opcodeToAltStack},
   425  	OP_FROMALTSTACK: {OP_FROMALTSTACK, "OP_FROMALTSTACK", 1, opcodeFromAltStack},
   426  	OP_2DROP:        {OP_2DROP, "OP_2DROP", 1, opcode2Drop},
   427  	OP_2DUP:         {OP_2DUP, "OP_2DUP", 1, opcode2Dup},
   428  	OP_3DUP:         {OP_3DUP, "OP_3DUP", 1, opcode3Dup},
   429  	OP_2OVER:        {OP_2OVER, "OP_2OVER", 1, opcode2Over},
   430  	OP_2ROT:         {OP_2ROT, "OP_2ROT", 1, opcode2Rot},
   431  	OP_2SWAP:        {OP_2SWAP, "OP_2SWAP", 1, opcode2Swap},
   432  	OP_IFDUP:        {OP_IFDUP, "OP_IFDUP", 1, opcodeIfDup},
   433  	OP_DEPTH:        {OP_DEPTH, "OP_DEPTH", 1, opcodeDepth},
   434  	OP_DROP:         {OP_DROP, "OP_DROP", 1, opcodeDrop},
   435  	OP_DUP:          {OP_DUP, "OP_DUP", 1, opcodeDup},
   436  	OP_NIP:          {OP_NIP, "OP_NIP", 1, opcodeNip},
   437  	OP_OVER:         {OP_OVER, "OP_OVER", 1, opcodeOver},
   438  	OP_PICK:         {OP_PICK, "OP_PICK", 1, opcodePick},
   439  	OP_ROLL:         {OP_ROLL, "OP_ROLL", 1, opcodeRoll},
   440  	OP_ROT:          {OP_ROT, "OP_ROT", 1, opcodeRot},
   441  	OP_SWAP:         {OP_SWAP, "OP_SWAP", 1, opcodeSwap},
   442  	OP_TUCK:         {OP_TUCK, "OP_TUCK", 1, opcodeTuck},
   443  
   444  	// Splice opcodes.
   445  	OP_CAT:    {OP_CAT, "OP_CAT", 1, opcodeDisabled},
   446  	OP_SUBSTR: {OP_SUBSTR, "OP_SUBSTR", 1, opcodeDisabled},
   447  	OP_LEFT:   {OP_LEFT, "OP_LEFT", 1, opcodeDisabled},
   448  	OP_RIGHT:  {OP_RIGHT, "OP_RIGHT", 1, opcodeDisabled},
   449  	OP_SIZE:   {OP_SIZE, "OP_SIZE", 1, opcodeSize},
   450  
   451  	// Bitwise logic opcodes.
   452  	OP_INVERT:      {OP_INVERT, "OP_INVERT", 1, opcodeDisabled},
   453  	OP_AND:         {OP_AND, "OP_AND", 1, opcodeDisabled},
   454  	OP_OR:          {OP_OR, "OP_OR", 1, opcodeDisabled},
   455  	OP_XOR:         {OP_XOR, "OP_XOR", 1, opcodeDisabled},
   456  	OP_EQUAL:       {OP_EQUAL, "OP_EQUAL", 1, opcodeEqual},
   457  	OP_EQUALVERIFY: {OP_EQUALVERIFY, "OP_EQUALVERIFY", 1, opcodeEqualVerify},
   458  	OP_RESERVED1:   {OP_RESERVED1, "OP_RESERVED1", 1, opcodeReserved},
   459  	OP_RESERVED2:   {OP_RESERVED2, "OP_RESERVED2", 1, opcodeReserved},
   460  
   461  	// Numeric related opcodes.
   462  	OP_1ADD:               {OP_1ADD, "OP_1ADD", 1, opcode1Add},
   463  	OP_1SUB:               {OP_1SUB, "OP_1SUB", 1, opcode1Sub},
   464  	OP_2MUL:               {OP_2MUL, "OP_2MUL", 1, opcodeDisabled},
   465  	OP_2DIV:               {OP_2DIV, "OP_2DIV", 1, opcodeDisabled},
   466  	OP_NEGATE:             {OP_NEGATE, "OP_NEGATE", 1, opcodeNegate},
   467  	OP_ABS:                {OP_ABS, "OP_ABS", 1, opcodeAbs},
   468  	OP_NOT:                {OP_NOT, "OP_NOT", 1, opcodeNot},
   469  	OP_0NOTEQUAL:          {OP_0NOTEQUAL, "OP_0NOTEQUAL", 1, opcode0NotEqual},
   470  	OP_ADD:                {OP_ADD, "OP_ADD", 1, opcodeAdd},
   471  	OP_SUB:                {OP_SUB, "OP_SUB", 1, opcodeSub},
   472  	OP_MUL:                {OP_MUL, "OP_MUL", 1, opcodeDisabled},
   473  	OP_DIV:                {OP_DIV, "OP_DIV", 1, opcodeDisabled},
   474  	OP_MOD:                {OP_MOD, "OP_MOD", 1, opcodeDisabled},
   475  	OP_LSHIFT:             {OP_LSHIFT, "OP_LSHIFT", 1, opcodeDisabled},
   476  	OP_RSHIFT:             {OP_RSHIFT, "OP_RSHIFT", 1, opcodeDisabled},
   477  	OP_BOOLAND:            {OP_BOOLAND, "OP_BOOLAND", 1, opcodeBoolAnd},
   478  	OP_BOOLOR:             {OP_BOOLOR, "OP_BOOLOR", 1, opcodeBoolOr},
   479  	OP_NUMEQUAL:           {OP_NUMEQUAL, "OP_NUMEQUAL", 1, opcodeNumEqual},
   480  	OP_NUMEQUALVERIFY:     {OP_NUMEQUALVERIFY, "OP_NUMEQUALVERIFY", 1, opcodeNumEqualVerify},
   481  	OP_NUMNOTEQUAL:        {OP_NUMNOTEQUAL, "OP_NUMNOTEQUAL", 1, opcodeNumNotEqual},
   482  	OP_LESSTHAN:           {OP_LESSTHAN, "OP_LESSTHAN", 1, opcodeLessThan},
   483  	OP_GREATERTHAN:        {OP_GREATERTHAN, "OP_GREATERTHAN", 1, opcodeGreaterThan},
   484  	OP_LESSTHANOREQUAL:    {OP_LESSTHANOREQUAL, "OP_LESSTHANOREQUAL", 1, opcodeLessThanOrEqual},
   485  	OP_GREATERTHANOREQUAL: {OP_GREATERTHANOREQUAL, "OP_GREATERTHANOREQUAL", 1, opcodeGreaterThanOrEqual},
   486  	OP_MIN:                {OP_MIN, "OP_MIN", 1, opcodeMin},
   487  	OP_MAX:                {OP_MAX, "OP_MAX", 1, opcodeMax},
   488  	OP_WITHIN:             {OP_WITHIN, "OP_WITHIN", 1, opcodeWithin},
   489  
   490  	// Crypto opcodes.
   491  	OP_RIPEMD160:           {OP_RIPEMD160, "OP_RIPEMD160", 1, opcodeRipemd160},
   492  	OP_SHA1:                {OP_SHA1, "OP_SHA1", 1, opcodeSha1},
   493  	OP_SHA256:              {OP_SHA256, "OP_SHA256", 1, opcodeSha256},
   494  	OP_HASH160:             {OP_HASH160, "OP_HASH160", 1, opcodeHash160},
   495  	OP_HASH256:             {OP_HASH256, "OP_HASH256", 1, opcodeHash256},
   496  	OP_CODESEPARATOR:       {OP_CODESEPARATOR, "OP_CODESEPARATOR", 1, opcodeCodeSeparator},
   497  	OP_CHECKSIG:            {OP_CHECKSIG, "OP_CHECKSIG", 1, opcodeCheckSig},
   498  	OP_CHECKSIGVERIFY:      {OP_CHECKSIGVERIFY, "OP_CHECKSIGVERIFY", 1, opcodeCheckSigVerify},
   499  	OP_CHECKMULTISIG:       {OP_CHECKMULTISIG, "OP_CHECKMULTISIG", 1, opcodeCheckMultiSig},
   500  	OP_CHECKMULTISIGVERIFY: {OP_CHECKMULTISIGVERIFY, "OP_CHECKMULTISIGVERIFY", 1, opcodeCheckMultiSigVerify},
   501  
   502  	// Reserved opcodes.
   503  	OP_NOP1:  {OP_NOP1, "OP_NOP1", 1, opcodeNop},
   504  	OP_NOP4:  {OP_NOP4, "OP_NOP4", 1, opcodeNop},
   505  	OP_NOP5:  {OP_NOP5, "OP_NOP5", 1, opcodeNop},
   506  	OP_NOP6:  {OP_NOP6, "OP_NOP6", 1, opcodeNop},
   507  	OP_NOP7:  {OP_NOP7, "OP_NOP7", 1, opcodeNop},
   508  	OP_NOP8:  {OP_NOP8, "OP_NOP8", 1, opcodeNop},
   509  	OP_NOP9:  {OP_NOP9, "OP_NOP9", 1, opcodeNop},
   510  	OP_NOP10: {OP_NOP10, "OP_NOP10", 1, opcodeNop},
   511  
   512  	// Undefined opcodes.
   513  	OP_UNKNOWN186: {OP_UNKNOWN186, "OP_UNKNOWN186", 1, opcodeInvalid},
   514  	OP_UNKNOWN187: {OP_UNKNOWN187, "OP_UNKNOWN187", 1, opcodeInvalid},
   515  	OP_UNKNOWN188: {OP_UNKNOWN188, "OP_UNKNOWN188", 1, opcodeInvalid},
   516  	OP_UNKNOWN189: {OP_UNKNOWN189, "OP_UNKNOWN189", 1, opcodeInvalid},
   517  	OP_UNKNOWN190: {OP_UNKNOWN190, "OP_UNKNOWN190", 1, opcodeInvalid},
   518  	OP_UNKNOWN191: {OP_UNKNOWN191, "OP_UNKNOWN191", 1, opcodeInvalid},
   519  	OP_UNKNOWN192: {OP_UNKNOWN192, "OP_UNKNOWN192", 1, opcodeInvalid},
   520  	OP_UNKNOWN193: {OP_UNKNOWN193, "OP_UNKNOWN193", 1, opcodeInvalid},
   521  	OP_UNKNOWN194: {OP_UNKNOWN194, "OP_UNKNOWN194", 1, opcodeInvalid},
   522  	OP_UNKNOWN195: {OP_UNKNOWN195, "OP_UNKNOWN195", 1, opcodeInvalid},
   523  	OP_UNKNOWN196: {OP_UNKNOWN196, "OP_UNKNOWN196", 1, opcodeInvalid},
   524  	OP_UNKNOWN197: {OP_UNKNOWN197, "OP_UNKNOWN197", 1, opcodeInvalid},
   525  	OP_UNKNOWN198: {OP_UNKNOWN198, "OP_UNKNOWN198", 1, opcodeInvalid},
   526  	OP_UNKNOWN199: {OP_UNKNOWN199, "OP_UNKNOWN199", 1, opcodeInvalid},
   527  	OP_UNKNOWN200: {OP_UNKNOWN200, "OP_UNKNOWN200", 1, opcodeInvalid},
   528  	OP_UNKNOWN201: {OP_UNKNOWN201, "OP_UNKNOWN201", 1, opcodeInvalid},
   529  	OP_UNKNOWN202: {OP_UNKNOWN202, "OP_UNKNOWN202", 1, opcodeInvalid},
   530  	OP_UNKNOWN203: {OP_UNKNOWN203, "OP_UNKNOWN203", 1, opcodeInvalid},
   531  	OP_UNKNOWN204: {OP_UNKNOWN204, "OP_UNKNOWN204", 1, opcodeInvalid},
   532  	OP_UNKNOWN205: {OP_UNKNOWN205, "OP_UNKNOWN205", 1, opcodeInvalid},
   533  	OP_UNKNOWN206: {OP_UNKNOWN206, "OP_UNKNOWN206", 1, opcodeInvalid},
   534  	OP_UNKNOWN207: {OP_UNKNOWN207, "OP_UNKNOWN207", 1, opcodeInvalid},
   535  	OP_UNKNOWN208: {OP_UNKNOWN208, "OP_UNKNOWN208", 1, opcodeInvalid},
   536  	OP_UNKNOWN209: {OP_UNKNOWN209, "OP_UNKNOWN209", 1, opcodeInvalid},
   537  	OP_UNKNOWN210: {OP_UNKNOWN210, "OP_UNKNOWN210", 1, opcodeInvalid},
   538  	OP_UNKNOWN211: {OP_UNKNOWN211, "OP_UNKNOWN211", 1, opcodeInvalid},
   539  	OP_UNKNOWN212: {OP_UNKNOWN212, "OP_UNKNOWN212", 1, opcodeInvalid},
   540  	OP_UNKNOWN213: {OP_UNKNOWN213, "OP_UNKNOWN213", 1, opcodeInvalid},
   541  	OP_UNKNOWN214: {OP_UNKNOWN214, "OP_UNKNOWN214", 1, opcodeInvalid},
   542  	OP_UNKNOWN215: {OP_UNKNOWN215, "OP_UNKNOWN215", 1, opcodeInvalid},
   543  	OP_UNKNOWN216: {OP_UNKNOWN216, "OP_UNKNOWN216", 1, opcodeInvalid},
   544  	OP_UNKNOWN217: {OP_UNKNOWN217, "OP_UNKNOWN217", 1, opcodeInvalid},
   545  	OP_UNKNOWN218: {OP_UNKNOWN218, "OP_UNKNOWN218", 1, opcodeInvalid},
   546  	OP_UNKNOWN219: {OP_UNKNOWN219, "OP_UNKNOWN219", 1, opcodeInvalid},
   547  	OP_UNKNOWN220: {OP_UNKNOWN220, "OP_UNKNOWN220", 1, opcodeInvalid},
   548  	OP_UNKNOWN221: {OP_UNKNOWN221, "OP_UNKNOWN221", 1, opcodeInvalid},
   549  	OP_UNKNOWN222: {OP_UNKNOWN222, "OP_UNKNOWN222", 1, opcodeInvalid},
   550  	OP_UNKNOWN223: {OP_UNKNOWN223, "OP_UNKNOWN223", 1, opcodeInvalid},
   551  	OP_UNKNOWN224: {OP_UNKNOWN224, "OP_UNKNOWN224", 1, opcodeInvalid},
   552  	OP_UNKNOWN225: {OP_UNKNOWN225, "OP_UNKNOWN225", 1, opcodeInvalid},
   553  	OP_UNKNOWN226: {OP_UNKNOWN226, "OP_UNKNOWN226", 1, opcodeInvalid},
   554  	OP_UNKNOWN227: {OP_UNKNOWN227, "OP_UNKNOWN227", 1, opcodeInvalid},
   555  	OP_UNKNOWN228: {OP_UNKNOWN228, "OP_UNKNOWN228", 1, opcodeInvalid},
   556  	OP_UNKNOWN229: {OP_UNKNOWN229, "OP_UNKNOWN229", 1, opcodeInvalid},
   557  	OP_UNKNOWN230: {OP_UNKNOWN230, "OP_UNKNOWN230", 1, opcodeInvalid},
   558  	OP_UNKNOWN231: {OP_UNKNOWN231, "OP_UNKNOWN231", 1, opcodeInvalid},
   559  	OP_UNKNOWN232: {OP_UNKNOWN232, "OP_UNKNOWN232", 1, opcodeInvalid},
   560  	OP_UNKNOWN233: {OP_UNKNOWN233, "OP_UNKNOWN233", 1, opcodeInvalid},
   561  	OP_UNKNOWN234: {OP_UNKNOWN234, "OP_UNKNOWN234", 1, opcodeInvalid},
   562  	OP_UNKNOWN235: {OP_UNKNOWN235, "OP_UNKNOWN235", 1, opcodeInvalid},
   563  	OP_UNKNOWN236: {OP_UNKNOWN236, "OP_UNKNOWN236", 1, opcodeInvalid},
   564  	OP_UNKNOWN237: {OP_UNKNOWN237, "OP_UNKNOWN237", 1, opcodeInvalid},
   565  	OP_UNKNOWN238: {OP_UNKNOWN238, "OP_UNKNOWN238", 1, opcodeInvalid},
   566  	OP_UNKNOWN239: {OP_UNKNOWN239, "OP_UNKNOWN239", 1, opcodeInvalid},
   567  	OP_UNKNOWN240: {OP_UNKNOWN240, "OP_UNKNOWN240", 1, opcodeInvalid},
   568  	OP_UNKNOWN241: {OP_UNKNOWN241, "OP_UNKNOWN241", 1, opcodeInvalid},
   569  	OP_UNKNOWN242: {OP_UNKNOWN242, "OP_UNKNOWN242", 1, opcodeInvalid},
   570  	OP_UNKNOWN243: {OP_UNKNOWN243, "OP_UNKNOWN243", 1, opcodeInvalid},
   571  	OP_UNKNOWN244: {OP_UNKNOWN244, "OP_UNKNOWN244", 1, opcodeInvalid},
   572  	OP_UNKNOWN245: {OP_UNKNOWN245, "OP_UNKNOWN245", 1, opcodeInvalid},
   573  	OP_UNKNOWN246: {OP_UNKNOWN246, "OP_UNKNOWN246", 1, opcodeInvalid},
   574  	OP_UNKNOWN247: {OP_UNKNOWN247, "OP_UNKNOWN247", 1, opcodeInvalid},
   575  	OP_UNKNOWN248: {OP_UNKNOWN248, "OP_UNKNOWN248", 1, opcodeInvalid},
   576  	OP_UNKNOWN249: {OP_UNKNOWN249, "OP_UNKNOWN249", 1, opcodeInvalid},
   577  
   578  	// Bitcoin Core internal use opcode.  Defined here for completeness.
   579  	OP_SMALLINTEGER: {OP_SMALLINTEGER, "OP_SMALLINTEGER", 1, opcodeInvalid},
   580  	OP_PUBKEYS:      {OP_PUBKEYS, "OP_PUBKEYS", 1, opcodeInvalid},
   581  	OP_UNKNOWN252:   {OP_UNKNOWN252, "OP_UNKNOWN252", 1, opcodeInvalid},
   582  	OP_PUBKEYHASH:   {OP_PUBKEYHASH, "OP_PUBKEYHASH", 1, opcodeInvalid},
   583  	OP_PUBKEY:       {OP_PUBKEY, "OP_PUBKEY", 1, opcodeInvalid},
   584  
   585  	OP_INVALIDOPCODE: {OP_INVALIDOPCODE, "OP_INVALIDOPCODE", 1, opcodeInvalid},
   586  }
   587  
   588  // opcodeOnelineRepls defines opcode names which are replaced when doing a
   589  // one-line disassembly.  This is done to match the output of the reference
   590  // implementation while not changing the opcode names in the nicer full
   591  // disassembly.
   592  var opcodeOnelineRepls = map[string]string{
   593  	"OP_1NEGATE": "-1",
   594  	"OP_0":       "0",
   595  	"OP_1":       "1",
   596  	"OP_2":       "2",
   597  	"OP_3":       "3",
   598  	"OP_4":       "4",
   599  	"OP_5":       "5",
   600  	"OP_6":       "6",
   601  	"OP_7":       "7",
   602  	"OP_8":       "8",
   603  	"OP_9":       "9",
   604  	"OP_10":      "10",
   605  	"OP_11":      "11",
   606  	"OP_12":      "12",
   607  	"OP_13":      "13",
   608  	"OP_14":      "14",
   609  	"OP_15":      "15",
   610  	"OP_16":      "16",
   611  }
   612  
   613  // parsedOpcode represents an opcode that has been parsed and includes any
   614  // potential data associated with it.
   615  type parsedOpcode struct {
   616  	opcode *opcode
   617  	data   []byte
   618  }
   619  
   620  // isDisabled returns whether or not the opcode is disabled and thus is always
   621  // bad to see in the instruction stream (even if turned off by a conditional).
   622  func (pop *parsedOpcode) isDisabled() bool {
   623  	switch pop.opcode.value {
   624  	case OP_CAT:
   625  		return true
   626  	case OP_SUBSTR:
   627  		return true
   628  	case OP_LEFT:
   629  		return true
   630  	case OP_RIGHT:
   631  		return true
   632  	case OP_INVERT:
   633  		return true
   634  	case OP_AND:
   635  		return true
   636  	case OP_OR:
   637  		return true
   638  	case OP_XOR:
   639  		return true
   640  	case OP_2MUL:
   641  		return true
   642  	case OP_2DIV:
   643  		return true
   644  	case OP_MUL:
   645  		return true
   646  	case OP_DIV:
   647  		return true
   648  	case OP_MOD:
   649  		return true
   650  	case OP_LSHIFT:
   651  		return true
   652  	case OP_RSHIFT:
   653  		return true
   654  	default:
   655  		return false
   656  	}
   657  }
   658  
   659  // checkParseableInScript checks whether or not the current opcode is able to be
   660  // parsed at a certain position in a script.
   661  // This returns the position of the next opcode to be parsed in the script.
   662  func (pop *parsedOpcode) checkParseableInScript(script []byte, scriptPos int) (int, error) {
   663  	// Parse data out of instruction.
   664  	switch {
   665  	// No additional data.  Note that some of the opcodes, notably
   666  	// OP_1NEGATE, OP_0, and OP_[1-16] represent the data
   667  	// themselves.
   668  	case pop.opcode.length == 1:
   669  		scriptPos++
   670  
   671  	// Data pushes of specific lengths -- OP_DATA_[1-75].
   672  	case pop.opcode.length > 1:
   673  		if len(script[scriptPos:]) < pop.opcode.length {
   674  			str := fmt.Sprintf("opcode %s requires %d "+
   675  				"bytes, but script only has %d remaining",
   676  				pop.opcode.name, pop.opcode.length, len(script[scriptPos:]))
   677  			return 0, scriptError(ErrMalformedPush, str)
   678  		}
   679  
   680  		// Slice out the data.
   681  		pop.data = script[scriptPos+1 : scriptPos+pop.opcode.length]
   682  		scriptPos += pop.opcode.length
   683  
   684  	// Data pushes with parsed lengths -- OP_PUSHDATAP{1,2,4}.
   685  	case pop.opcode.length < 0:
   686  		var l uint
   687  		off := scriptPos + 1
   688  
   689  		if len(script[off:]) < -pop.opcode.length {
   690  			str := fmt.Sprintf("opcode %s requires %d "+
   691  				"bytes, but script only has %d remaining",
   692  				pop.opcode.name, -pop.opcode.length, len(script[off:]))
   693  			return 0, scriptError(ErrMalformedPush, str)
   694  		}
   695  
   696  		// Next -length bytes are little endian length of data.
   697  		switch pop.opcode.length {
   698  		case -1:
   699  			l = uint(script[off])
   700  		case -2:
   701  			l = ((uint(script[off+1]) << 8) |
   702  				uint(script[off]))
   703  		case -4:
   704  			l = ((uint(script[off+3]) << 24) |
   705  				(uint(script[off+2]) << 16) |
   706  				(uint(script[off+1]) << 8) |
   707  				uint(script[off]))
   708  		default:
   709  			str := fmt.Sprintf("invalid opcode length %d",
   710  				pop.opcode.length)
   711  			return 0, scriptError(ErrMalformedPush, str)
   712  		}
   713  
   714  		// Move offset to beginning of the data.
   715  		off += -pop.opcode.length
   716  
   717  		// Disallow entries that do not fit script or were
   718  		// sign extended.
   719  		if int(l) > len(script[off:]) || int(l) < 0 {
   720  			str := fmt.Sprintf("opcode %s pushes %d bytes, "+
   721  				"but script only has %d remaining",
   722  				pop.opcode.name, int(l), len(script[off:]))
   723  			return 0, scriptError(ErrMalformedPush, str)
   724  		}
   725  
   726  		pop.data = script[off : off+int(l)]
   727  		scriptPos += 1 - pop.opcode.length + int(l)
   728  	}
   729  	return scriptPos, nil
   730  }
   731  
   732  // alwaysIllegal returns whether or not the opcode is always illegal when passed
   733  // over by the program counter even if in a non-executed branch (it isn't a
   734  // coincidence that they are conditionals).
   735  func (pop *parsedOpcode) alwaysIllegal() bool {
   736  	switch pop.opcode.value {
   737  	case OP_VERIF:
   738  		return true
   739  	case OP_VERNOTIF:
   740  		return true
   741  	default:
   742  		return false
   743  	}
   744  }
   745  
   746  // isConditional returns whether or not the opcode is a conditional opcode which
   747  // changes the conditional execution stack when executed.
   748  func (pop *parsedOpcode) isConditional() bool {
   749  	switch pop.opcode.value {
   750  	case OP_IF:
   751  		return true
   752  	case OP_NOTIF:
   753  		return true
   754  	case OP_ELSE:
   755  		return true
   756  	case OP_ENDIF:
   757  		return true
   758  	default:
   759  		return false
   760  	}
   761  }
   762  
   763  // checkMinimalDataPush returns whether or not the current data push uses the
   764  // smallest possible opcode to represent it.  For example, the value 15 could
   765  // be pushed with OP_DATA_1 15 (among other variations); however, OP_15 is a
   766  // single opcode that represents the same value and is only a single byte versus
   767  // two bytes.
   768  func (pop *parsedOpcode) checkMinimalDataPush() error {
   769  	data := pop.data
   770  	dataLen := len(data)
   771  	opcode := pop.opcode.value
   772  
   773  	if dataLen == 0 && opcode != OP_0 {
   774  		str := fmt.Sprintf("zero length data push is encoded with "+
   775  			"opcode %s instead of OP_0", pop.opcode.name)
   776  		return scriptError(ErrMinimalData, str)
   777  	} else if dataLen == 1 && data[0] >= 1 && data[0] <= 16 {
   778  		if opcode != OP_1+data[0]-1 {
   779  			// Should have used OP_1 .. OP_16
   780  			str := fmt.Sprintf("data push of the value %d encoded "+
   781  				"with opcode %s instead of OP_%d", data[0],
   782  				pop.opcode.name, data[0])
   783  			return scriptError(ErrMinimalData, str)
   784  		}
   785  	} else if dataLen == 1 && data[0] == 0x81 {
   786  		if opcode != OP_1NEGATE {
   787  			str := fmt.Sprintf("data push of the value -1 encoded "+
   788  				"with opcode %s instead of OP_1NEGATE",
   789  				pop.opcode.name)
   790  			return scriptError(ErrMinimalData, str)
   791  		}
   792  	} else if dataLen <= 75 {
   793  		if int(opcode) != dataLen {
   794  			// Should have used a direct push
   795  			str := fmt.Sprintf("data push of %d bytes encoded "+
   796  				"with opcode %s instead of OP_DATA_%d", dataLen,
   797  				pop.opcode.name, dataLen)
   798  			return scriptError(ErrMinimalData, str)
   799  		}
   800  	} else if dataLen <= 255 {
   801  		if opcode != OP_PUSHDATA1 {
   802  			str := fmt.Sprintf("data push of %d bytes encoded "+
   803  				"with opcode %s instead of OP_PUSHDATA1",
   804  				dataLen, pop.opcode.name)
   805  			return scriptError(ErrMinimalData, str)
   806  		}
   807  	} else if dataLen <= 65535 {
   808  		if opcode != OP_PUSHDATA2 {
   809  			str := fmt.Sprintf("data push of %d bytes encoded "+
   810  				"with opcode %s instead of OP_PUSHDATA2",
   811  				dataLen, pop.opcode.name)
   812  			return scriptError(ErrMinimalData, str)
   813  		}
   814  	}
   815  	return nil
   816  }
   817  
   818  // print returns a human-readable string representation of the opcode for use
   819  // in script disassembly.
   820  func (pop *parsedOpcode) print(oneline bool) string {
   821  	// The reference implementation one-line disassembly replaces opcodes
   822  	// which represent values (e.g. OP_0 through OP_16 and OP_1NEGATE)
   823  	// with the raw value.  However, when not doing a one-line dissassembly,
   824  	// we prefer to show the actual opcode names.  Thus, only replace the
   825  	// opcodes in question when the oneline flag is set.
   826  	opcodeName := pop.opcode.name
   827  	if oneline {
   828  		if replName, ok := opcodeOnelineRepls[opcodeName]; ok {
   829  			opcodeName = replName
   830  		}
   831  
   832  		// Nothing more to do for non-data push opcodes.
   833  		if pop.opcode.length == 1 {
   834  			return opcodeName
   835  		}
   836  
   837  		return fmt.Sprintf("%x", pop.data)
   838  	}
   839  
   840  	// Nothing more to do for non-data push opcodes.
   841  	if pop.opcode.length == 1 {
   842  		return opcodeName
   843  	}
   844  
   845  	// Add length for the OP_PUSHDATA# opcodes.
   846  	retString := opcodeName
   847  	switch pop.opcode.length {
   848  	case -1:
   849  		retString += fmt.Sprintf(" 0x%02x", len(pop.data))
   850  	case -2:
   851  		retString += fmt.Sprintf(" 0x%04x", len(pop.data))
   852  	case -4:
   853  		retString += fmt.Sprintf(" 0x%08x", len(pop.data))
   854  	}
   855  
   856  	return fmt.Sprintf("%s 0x%02x", retString, pop.data)
   857  }
   858  
   859  // bytes returns any data associated with the opcode encoded as it would be in
   860  // a script.  This is used for unparsing scripts from parsed opcodes.
   861  func (pop *parsedOpcode) bytes() ([]byte, error) {
   862  	var retbytes []byte
   863  	if pop.opcode.length > 0 {
   864  		retbytes = make([]byte, 1, pop.opcode.length)
   865  	} else {
   866  		retbytes = make([]byte, 1, 1+len(pop.data)-
   867  			pop.opcode.length)
   868  	}
   869  
   870  	retbytes[0] = pop.opcode.value
   871  	if pop.opcode.length == 1 {
   872  		if len(pop.data) != 0 {
   873  			str := fmt.Sprintf("internal consistency error - "+
   874  				"parsed opcode %s has data length %d when %d "+
   875  				"was expected", pop.opcode.name, len(pop.data),
   876  				0)
   877  			return nil, scriptError(ErrInternal, str)
   878  		}
   879  		return retbytes, nil
   880  	}
   881  	nbytes := pop.opcode.length
   882  	if pop.opcode.length < 0 {
   883  		l := len(pop.data)
   884  		// tempting just to hardcode to avoid the complexity here.
   885  		switch pop.opcode.length {
   886  		case -1:
   887  			retbytes = append(retbytes, byte(l))
   888  			nbytes = int(retbytes[1]) + len(retbytes)
   889  		case -2:
   890  			retbytes = append(retbytes, byte(l&0xff),
   891  				byte(l>>8&0xff))
   892  			nbytes = int(binary.LittleEndian.Uint16(retbytes[1:])) +
   893  				len(retbytes)
   894  		case -4:
   895  			retbytes = append(retbytes, byte(l&0xff),
   896  				byte((l>>8)&0xff), byte((l>>16)&0xff),
   897  				byte((l>>24)&0xff))
   898  			nbytes = int(binary.LittleEndian.Uint32(retbytes[1:])) +
   899  				len(retbytes)
   900  		}
   901  	}
   902  
   903  	retbytes = append(retbytes, pop.data...)
   904  
   905  	if len(retbytes) != nbytes {
   906  		str := fmt.Sprintf("internal consistency error - "+
   907  			"parsed opcode %s has data length %d when %d was "+
   908  			"expected", pop.opcode.name, len(retbytes), nbytes)
   909  		return nil, scriptError(ErrInternal, str)
   910  	}
   911  
   912  	return retbytes, nil
   913  }
   914  
   915  // *******************************************
   916  // Opcode implementation functions start here.
   917  // *******************************************
   918  
   919  // opcodeDisabled is a common handler for disabled opcodes.  It returns an
   920  // appropriate error indicating the opcode is disabled.  While it would
   921  // ordinarily make more sense to detect if the script contains any disabled
   922  // opcodes before executing in an initial parse step, the consensus rules
   923  // dictate the script doesn't fail until the program counter passes over a
   924  // disabled opcode (even when they appear in a branch that is not executed).
   925  func opcodeDisabled(op *parsedOpcode, vm *Engine) error {
   926  	str := fmt.Sprintf("attempt to execute disabled opcode %s",
   927  		op.opcode.name)
   928  	return scriptError(ErrDisabledOpcode, str)
   929  }
   930  
   931  // opcodeReserved is a common handler for all reserved opcodes.  It returns an
   932  // appropriate error indicating the opcode is reserved.
   933  func opcodeReserved(op *parsedOpcode, vm *Engine) error {
   934  	str := fmt.Sprintf("attempt to execute reserved opcode %s",
   935  		op.opcode.name)
   936  	return scriptError(ErrReservedOpcode, str)
   937  }
   938  
   939  // opcodeInvalid is a common handler for all invalid opcodes.  It returns an
   940  // appropriate error indicating the opcode is invalid.
   941  func opcodeInvalid(op *parsedOpcode, vm *Engine) error {
   942  	str := fmt.Sprintf("attempt to execute invalid opcode %s",
   943  		op.opcode.name)
   944  	return scriptError(ErrReservedOpcode, str)
   945  }
   946  
   947  // opcodeFalse pushes an empty array to the data stack to represent false.  Note
   948  // that 0, when encoded as a number according to the numeric encoding consensus
   949  // rules, is an empty array.
   950  func opcodeFalse(op *parsedOpcode, vm *Engine) error {
   951  	vm.dstack.PushByteArray(nil)
   952  	return nil
   953  }
   954  
   955  // opcodePushData is a common handler for the vast majority of opcodes that push
   956  // raw data (bytes) to the data stack.
   957  func opcodePushData(op *parsedOpcode, vm *Engine) error {
   958  	vm.dstack.PushByteArray(op.data)
   959  	return nil
   960  }
   961  
   962  // opcode1Negate pushes -1, encoded as a number, to the data stack.
   963  func opcode1Negate(op *parsedOpcode, vm *Engine) error {
   964  	vm.dstack.PushInt(scriptNum(-1))
   965  	return nil
   966  }
   967  
   968  // opcodeN is a common handler for the small integer data push opcodes.  It
   969  // pushes the numeric value the opcode represents (which will be from 1 to 16)
   970  // onto the data stack.
   971  func opcodeN(op *parsedOpcode, vm *Engine) error {
   972  	// The opcodes are all defined consecutively, so the numeric value is
   973  	// the difference.
   974  	vm.dstack.PushInt(scriptNum((op.opcode.value - (OP_1 - 1))))
   975  	return nil
   976  }
   977  
   978  // opcodeNop is a common handler for the NOP family of opcodes.  As the name
   979  // implies it generally does nothing, however, it will return an error when
   980  // the flag to discourage use of NOPs is set for select opcodes.
   981  func opcodeNop(op *parsedOpcode, vm *Engine) error {
   982  	switch op.opcode.value {
   983  	case OP_NOP1, OP_NOP4, OP_NOP5,
   984  		OP_NOP6, OP_NOP7, OP_NOP8, OP_NOP9, OP_NOP10:
   985  		if vm.hasFlag(ScriptDiscourageUpgradableNops) {
   986  			str := fmt.Sprintf("OP_NOP%d reserved for soft-fork "+
   987  				"upgrades", op.opcode.value-(OP_NOP1-1))
   988  			return scriptError(ErrDiscourageUpgradableNOPs, str)
   989  		}
   990  	}
   991  	return nil
   992  }
   993  
   994  // popIfBool enforces the "minimal if" policy during script execution if the
   995  // particular flag is set.  If so, in order to eliminate an additional source
   996  // of nuisance malleability, post-segwit for version 0 witness programs, we now
   997  // require the following: for OP_IF and OP_NOT_IF, the top stack item MUST
   998  // either be an empty byte slice, or [0x01]. Otherwise, the item at the top of
   999  // the stack will be popped and interpreted as a boolean.
  1000  func popIfBool(vm *Engine) (bool, error) {
  1001  	// When not in witness execution mode, not executing a v0 witness
  1002  	// program, or the minimal if flag isn't set pop the top stack item as
  1003  	// a normal bool.
  1004  	if !vm.isWitnessVersionActive(0) || !vm.hasFlag(ScriptVerifyMinimalIf) {
  1005  		return vm.dstack.PopBool()
  1006  	}
  1007  
  1008  	// At this point, a v0 witness program is being executed and the minimal
  1009  	// if flag is set, so enforce additional constraints on the top stack
  1010  	// item.
  1011  	so, err := vm.dstack.PopByteArray()
  1012  	if err != nil {
  1013  		return false, err
  1014  	}
  1015  
  1016  	// The top element MUST have a length of at least one.
  1017  	if len(so) > 1 {
  1018  		str := fmt.Sprintf("minimal if is active, top element MUST "+
  1019  			"have a length of at least, instead length is %v",
  1020  			len(so))
  1021  		return false, scriptError(ErrMinimalIf, str)
  1022  	}
  1023  
  1024  	// Additionally, if the length is one, then the value MUST be 0x01.
  1025  	if len(so) == 1 && so[0] != 0x01 {
  1026  		str := fmt.Sprintf("minimal if is active, top stack item MUST "+
  1027  			"be an empty byte array or 0x01, is instead: %v",
  1028  			so[0])
  1029  		return false, scriptError(ErrMinimalIf, str)
  1030  	}
  1031  
  1032  	return asBool(so), nil
  1033  }
  1034  
  1035  // opcodeIf treats the top item on the data stack as a boolean and removes it.
  1036  //
  1037  // An appropriate entry is added to the conditional stack depending on whether
  1038  // the boolean is true and whether this if is on an executing branch in order
  1039  // to allow proper execution of further opcodes depending on the conditional
  1040  // logic.  When the boolean is true, the first branch will be executed (unless
  1041  // this opcode is nested in a non-executed branch).
  1042  //
  1043  // <expression> if [statements] [else [statements]] endif
  1044  //
  1045  // Note that, unlike for all non-conditional opcodes, this is executed even when
  1046  // it is on a non-executing branch so proper nesting is maintained.
  1047  //
  1048  // Data stack transformation: [... bool] -> [...]
  1049  // Conditional stack transformation: [...] -> [... OpCondValue]
  1050  func opcodeIf(op *parsedOpcode, vm *Engine) error {
  1051  	condVal := OpCondFalse
  1052  	if vm.isBranchExecuting() {
  1053  		ok, err := popIfBool(vm)
  1054  		if err != nil {
  1055  			return err
  1056  		}
  1057  
  1058  		if ok {
  1059  			condVal = OpCondTrue
  1060  		}
  1061  	} else {
  1062  		condVal = OpCondSkip
  1063  	}
  1064  	vm.condStack = append(vm.condStack, condVal)
  1065  	return nil
  1066  }
  1067  
  1068  // opcodeNotIf treats the top item on the data stack as a boolean and removes
  1069  // it.
  1070  //
  1071  // An appropriate entry is added to the conditional stack depending on whether
  1072  // the boolean is true and whether this if is on an executing branch in order
  1073  // to allow proper execution of further opcodes depending on the conditional
  1074  // logic.  When the boolean is false, the first branch will be executed (unless
  1075  // this opcode is nested in a non-executed branch).
  1076  //
  1077  // <expression> notif [statements] [else [statements]] endif
  1078  //
  1079  // Note that, unlike for all non-conditional opcodes, this is executed even when
  1080  // it is on a non-executing branch so proper nesting is maintained.
  1081  //
  1082  // Data stack transformation: [... bool] -> [...]
  1083  // Conditional stack transformation: [...] -> [... OpCondValue]
  1084  func opcodeNotIf(op *parsedOpcode, vm *Engine) error {
  1085  	condVal := OpCondFalse
  1086  	if vm.isBranchExecuting() {
  1087  		ok, err := popIfBool(vm)
  1088  		if err != nil {
  1089  			return err
  1090  		}
  1091  
  1092  		if !ok {
  1093  			condVal = OpCondTrue
  1094  		}
  1095  	} else {
  1096  		condVal = OpCondSkip
  1097  	}
  1098  	vm.condStack = append(vm.condStack, condVal)
  1099  	return nil
  1100  }
  1101  
  1102  // opcodeElse inverts conditional execution for other half of if/else/endif.
  1103  //
  1104  // An error is returned if there has not already been a matching OP_IF.
  1105  //
  1106  // Conditional stack transformation: [... OpCondValue] -> [... !OpCondValue]
  1107  func opcodeElse(op *parsedOpcode, vm *Engine) error {
  1108  	if len(vm.condStack) == 0 {
  1109  		str := fmt.Sprintf("encountered opcode %s with no matching "+
  1110  			"opcode to begin conditional execution", op.opcode.name)
  1111  		return scriptError(ErrUnbalancedConditional, str)
  1112  	}
  1113  
  1114  	conditionalIdx := len(vm.condStack) - 1
  1115  	switch vm.condStack[conditionalIdx] {
  1116  	case OpCondTrue:
  1117  		vm.condStack[conditionalIdx] = OpCondFalse
  1118  	case OpCondFalse:
  1119  		vm.condStack[conditionalIdx] = OpCondTrue
  1120  	case OpCondSkip:
  1121  		// Value doesn't change in skip since it indicates this opcode
  1122  		// is nested in a non-executed branch.
  1123  	}
  1124  	return nil
  1125  }
  1126  
  1127  // opcodeEndif terminates a conditional block, removing the value from the
  1128  // conditional execution stack.
  1129  //
  1130  // An error is returned if there has not already been a matching OP_IF.
  1131  //
  1132  // Conditional stack transformation: [... OpCondValue] -> [...]
  1133  func opcodeEndif(op *parsedOpcode, vm *Engine) error {
  1134  	if len(vm.condStack) == 0 {
  1135  		str := fmt.Sprintf("encountered opcode %s with no matching "+
  1136  			"opcode to begin conditional execution", op.opcode.name)
  1137  		return scriptError(ErrUnbalancedConditional, str)
  1138  	}
  1139  
  1140  	vm.condStack = vm.condStack[:len(vm.condStack)-1]
  1141  	return nil
  1142  }
  1143  
  1144  // abstractVerify examines the top item on the data stack as a boolean value and
  1145  // verifies it evaluates to true.  An error is returned either when there is no
  1146  // item on the stack or when that item evaluates to false.  In the latter case
  1147  // where the verification fails specifically due to the top item evaluating
  1148  // to false, the returned error will use the passed error code.
  1149  func abstractVerify(op *parsedOpcode, vm *Engine, c ErrorCode) error {
  1150  	verified, err := vm.dstack.PopBool()
  1151  	if err != nil {
  1152  		return err
  1153  	}
  1154  
  1155  	if !verified {
  1156  		str := fmt.Sprintf("%s failed", op.opcode.name)
  1157  		return scriptError(c, str)
  1158  	}
  1159  	return nil
  1160  }
  1161  
  1162  // opcodeVerify examines the top item on the data stack as a boolean value and
  1163  // verifies it evaluates to true.  An error is returned if it does not.
  1164  func opcodeVerify(op *parsedOpcode, vm *Engine) error {
  1165  	return abstractVerify(op, vm, ErrVerify)
  1166  }
  1167  
  1168  // opcodeReturn returns an appropriate error since it is always an error to
  1169  // return early from a script.
  1170  func opcodeReturn(op *parsedOpcode, vm *Engine) error {
  1171  	return scriptError(ErrEarlyReturn, "script returned early")
  1172  }
  1173  
  1174  // verifyLockTime is a helper function used to validate locktimes.
  1175  func verifyLockTime(txLockTime, threshold, lockTime int64) error {
  1176  	// The lockTimes in both the script and transaction must be of the same
  1177  	// type.
  1178  	if !((txLockTime < threshold && lockTime < threshold) ||
  1179  		(txLockTime >= threshold && lockTime >= threshold)) {
  1180  		str := fmt.Sprintf("mismatched locktime types -- tx locktime "+
  1181  			"%d, stack locktime %d", txLockTime, lockTime)
  1182  		return scriptError(ErrUnsatisfiedLockTime, str)
  1183  	}
  1184  
  1185  	if lockTime > txLockTime {
  1186  		str := fmt.Sprintf("locktime requirement not satisfied -- "+
  1187  			"locktime is greater than the transaction locktime: "+
  1188  			"%d > %d", lockTime, txLockTime)
  1189  		return scriptError(ErrUnsatisfiedLockTime, str)
  1190  	}
  1191  
  1192  	return nil
  1193  }
  1194  
  1195  // opcodeCheckLockTimeVerify compares the top item on the data stack to the
  1196  // LockTime field of the transaction containing the script signature
  1197  // validating if the transaction outputs are spendable yet.  If flag
  1198  // ScriptVerifyCheckLockTimeVerify is not set, the code continues as if OP_NOP2
  1199  // were executed.
  1200  func opcodeCheckLockTimeVerify(op *parsedOpcode, vm *Engine) error {
  1201  	// If the ScriptVerifyCheckLockTimeVerify script flag is not set, treat
  1202  	// opcode as OP_NOP2 instead.
  1203  	if !vm.hasFlag(ScriptVerifyCheckLockTimeVerify) {
  1204  		if vm.hasFlag(ScriptDiscourageUpgradableNops) {
  1205  			return scriptError(ErrDiscourageUpgradableNOPs,
  1206  				"OP_NOP2 reserved for soft-fork upgrades")
  1207  		}
  1208  		return nil
  1209  	}
  1210  
  1211  	// The current transaction locktime is a uint32 resulting in a maximum
  1212  	// locktime of 2^32-1 (the year 2106).  However, scriptNums are signed
  1213  	// and therefore a standard 4-byte scriptNum would only support up to a
  1214  	// maximum of 2^31-1 (the year 2038).  Thus, a 5-byte scriptNum is used
  1215  	// here since it will support up to 2^39-1 which allows dates beyond the
  1216  	// current locktime limit.
  1217  	//
  1218  	// PeekByteArray is used here instead of PeekInt because we do not want
  1219  	// to be limited to a 4-byte integer for reasons specified above.
  1220  	so, err := vm.dstack.PeekByteArray(0)
  1221  	if err != nil {
  1222  		return err
  1223  	}
  1224  	lockTime, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5)
  1225  	if err != nil {
  1226  		return err
  1227  	}
  1228  
  1229  	// In the rare event that the argument needs to be < 0 due to some
  1230  	// arithmetic being done first, you can always use
  1231  	// 0 OP_MAX OP_CHECKLOCKTIMEVERIFY.
  1232  	if lockTime < 0 {
  1233  		str := fmt.Sprintf("negative lock time: %d", lockTime)
  1234  		return scriptError(ErrNegativeLockTime, str)
  1235  	}
  1236  
  1237  	// The lock time field of a transaction is either a block height at
  1238  	// which the transaction is finalized or a timestamp depending on if the
  1239  	// value is before the txscript.LockTimeThreshold.  When it is under the
  1240  	// threshold it is a block height.
  1241  	err = verifyLockTime(int64(vm.tx.LockTime), LockTimeThreshold,
  1242  		int64(lockTime))
  1243  	if err != nil {
  1244  		return err
  1245  	}
  1246  
  1247  	// The lock time feature can also be disabled, thereby bypassing
  1248  	// OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by
  1249  	// setting its sequence to the maximum value (wire.MaxTxInSequenceNum).  This
  1250  	// condition would result in the transaction being allowed into the blockchain
  1251  	// making the opcode ineffective.
  1252  	//
  1253  	// This condition is prevented by enforcing that the input being used by
  1254  	// the opcode is unlocked (its sequence number is less than the max
  1255  	// value).  This is sufficient to prove correctness without having to
  1256  	// check every input.
  1257  	//
  1258  	// NOTE: This implies that even if the transaction is not finalized due to
  1259  	// another input being unlocked, the opcode execution will still fail when the
  1260  	// input being used by the opcode is locked.
  1261  	if vm.tx.TxIn[vm.txIdx].Sequence == wire.MaxTxInSequenceNum {
  1262  		return scriptError(ErrUnsatisfiedLockTime,
  1263  			"transaction input is finalized")
  1264  	}
  1265  
  1266  	return nil
  1267  }
  1268  
  1269  // opcodeCheckSequenceVerify compares the top item on the data stack to the
  1270  // LockTime field of the transaction containing the script signature
  1271  // validating if the transaction outputs are spendable yet.  If flag
  1272  // ScriptVerifyCheckSequenceVerify is not set, the code continues as if OP_NOP3
  1273  // were executed.
  1274  func opcodeCheckSequenceVerify(op *parsedOpcode, vm *Engine) error {
  1275  	// If the ScriptVerifyCheckSequenceVerify script flag is not set, treat
  1276  	// opcode as OP_NOP3 instead.
  1277  	if !vm.hasFlag(ScriptVerifyCheckSequenceVerify) {
  1278  		if vm.hasFlag(ScriptDiscourageUpgradableNops) {
  1279  			return scriptError(ErrDiscourageUpgradableNOPs,
  1280  				"OP_NOP3 reserved for soft-fork upgrades")
  1281  		}
  1282  		return nil
  1283  	}
  1284  
  1285  	// The current transaction sequence is a uint32 resulting in a maximum
  1286  	// sequence of 2^32-1.  However, scriptNums are signed and therefore a
  1287  	// standard 4-byte scriptNum would only support up to a maximum of
  1288  	// 2^31-1.  Thus, a 5-byte scriptNum is used here since it will support
  1289  	// up to 2^39-1 which allows sequences beyond the current sequence
  1290  	// limit.
  1291  	//
  1292  	// PeekByteArray is used here instead of PeekInt because we do not want
  1293  	// to be limited to a 4-byte integer for reasons specified above.
  1294  	so, err := vm.dstack.PeekByteArray(0)
  1295  	if err != nil {
  1296  		return err
  1297  	}
  1298  	stackSequence, err := makeScriptNum(so, vm.dstack.verifyMinimalData, 5)
  1299  	if err != nil {
  1300  		return err
  1301  	}
  1302  
  1303  	// In the rare event that the argument needs to be < 0 due to some
  1304  	// arithmetic being done first, you can always use
  1305  	// 0 OP_MAX OP_CHECKSEQUENCEVERIFY.
  1306  	if stackSequence < 0 {
  1307  		str := fmt.Sprintf("negative sequence: %d", stackSequence)
  1308  		return scriptError(ErrNegativeLockTime, str)
  1309  	}
  1310  
  1311  	sequence := int64(stackSequence)
  1312  
  1313  	// To provide for future soft-fork extensibility, if the
  1314  	// operand has the disabled lock-time flag set,
  1315  	// CHECKSEQUENCEVERIFY behaves as a NOP.
  1316  	if sequence&int64(wire.SequenceLockTimeDisabled) != 0 {
  1317  		return nil
  1318  	}
  1319  
  1320  	// Transaction version numbers not high enough to trigger CSV rules must
  1321  	// fail.
  1322  	if vm.tx.Version < 2 {
  1323  		str := fmt.Sprintf("invalid transaction version: %d",
  1324  			vm.tx.Version)
  1325  		return scriptError(ErrUnsatisfiedLockTime, str)
  1326  	}
  1327  
  1328  	// Sequence numbers with their most significant bit set are not
  1329  	// consensus constrained. Testing that the transaction's sequence
  1330  	// number does not have this bit set prevents using this property
  1331  	// to get around a CHECKSEQUENCEVERIFY check.
  1332  	txSequence := int64(vm.tx.TxIn[vm.txIdx].Sequence)
  1333  	if txSequence&int64(wire.SequenceLockTimeDisabled) != 0 {
  1334  		str := fmt.Sprintf("transaction sequence has sequence "+
  1335  			"locktime disabled bit set: 0x%x", txSequence)
  1336  		return scriptError(ErrUnsatisfiedLockTime, str)
  1337  	}
  1338  
  1339  	// Mask off non-consensus bits before doing comparisons.
  1340  	lockTimeMask := int64(wire.SequenceLockTimeIsSeconds |
  1341  		wire.SequenceLockTimeMask)
  1342  	return verifyLockTime(txSequence&lockTimeMask,
  1343  		wire.SequenceLockTimeIsSeconds, sequence&lockTimeMask)
  1344  }
  1345  
  1346  // opcodeToAltStack removes the top item from the main data stack and pushes it
  1347  // onto the alternate data stack.
  1348  //
  1349  // Main data stack transformation: [... x1 x2 x3] -> [... x1 x2]
  1350  // Alt data stack transformation:  [... y1 y2 y3] -> [... y1 y2 y3 x3]
  1351  func opcodeToAltStack(op *parsedOpcode, vm *Engine) error {
  1352  	so, err := vm.dstack.PopByteArray()
  1353  	if err != nil {
  1354  		return err
  1355  	}
  1356  	vm.astack.PushByteArray(so)
  1357  
  1358  	return nil
  1359  }
  1360  
  1361  // opcodeFromAltStack removes the top item from the alternate data stack and
  1362  // pushes it onto the main data stack.
  1363  //
  1364  // Main data stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 y3]
  1365  // Alt data stack transformation:  [... y1 y2 y3] -> [... y1 y2]
  1366  func opcodeFromAltStack(op *parsedOpcode, vm *Engine) error {
  1367  	so, err := vm.astack.PopByteArray()
  1368  	if err != nil {
  1369  		return err
  1370  	}
  1371  	vm.dstack.PushByteArray(so)
  1372  
  1373  	return nil
  1374  }
  1375  
  1376  // opcode2Drop removes the top 2 items from the data stack.
  1377  //
  1378  // Stack transformation: [... x1 x2 x3] -> [... x1]
  1379  func opcode2Drop(op *parsedOpcode, vm *Engine) error {
  1380  	return vm.dstack.DropN(2)
  1381  }
  1382  
  1383  // opcode2Dup duplicates the top 2 items on the data stack.
  1384  //
  1385  // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x2 x3]
  1386  func opcode2Dup(op *parsedOpcode, vm *Engine) error {
  1387  	return vm.dstack.DupN(2)
  1388  }
  1389  
  1390  // opcode3Dup duplicates the top 3 items on the data stack.
  1391  //
  1392  // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x1 x2 x3]
  1393  func opcode3Dup(op *parsedOpcode, vm *Engine) error {
  1394  	return vm.dstack.DupN(3)
  1395  }
  1396  
  1397  // opcode2Over duplicates the 2 items before the top 2 items on the data stack.
  1398  //
  1399  // Stack transformation: [... x1 x2 x3 x4] -> [... x1 x2 x3 x4 x1 x2]
  1400  func opcode2Over(op *parsedOpcode, vm *Engine) error {
  1401  	return vm.dstack.OverN(2)
  1402  }
  1403  
  1404  // opcode2Rot rotates the top 6 items on the data stack to the left twice.
  1405  //
  1406  // Stack transformation: [... x1 x2 x3 x4 x5 x6] -> [... x3 x4 x5 x6 x1 x2]
  1407  func opcode2Rot(op *parsedOpcode, vm *Engine) error {
  1408  	return vm.dstack.RotN(2)
  1409  }
  1410  
  1411  // opcode2Swap swaps the top 2 items on the data stack with the 2 that come
  1412  // before them.
  1413  //
  1414  // Stack transformation: [... x1 x2 x3 x4] -> [... x3 x4 x1 x2]
  1415  func opcode2Swap(op *parsedOpcode, vm *Engine) error {
  1416  	return vm.dstack.SwapN(2)
  1417  }
  1418  
  1419  // opcodeIfDup duplicates the top item of the stack if it is not zero.
  1420  //
  1421  // Stack transformation (x1==0): [... x1] -> [... x1]
  1422  // Stack transformation (x1!=0): [... x1] -> [... x1 x1]
  1423  func opcodeIfDup(op *parsedOpcode, vm *Engine) error {
  1424  	so, err := vm.dstack.PeekByteArray(0)
  1425  	if err != nil {
  1426  		return err
  1427  	}
  1428  
  1429  	// Push copy of data iff it isn't zero
  1430  	if asBool(so) {
  1431  		vm.dstack.PushByteArray(so)
  1432  	}
  1433  
  1434  	return nil
  1435  }
  1436  
  1437  // opcodeDepth pushes the depth of the data stack prior to executing this
  1438  // opcode, encoded as a number, onto the data stack.
  1439  //
  1440  // Stack transformation: [...] -> [... <num of items on the stack>]
  1441  // Example with 2 items: [x1 x2] -> [x1 x2 2]
  1442  // Example with 3 items: [x1 x2 x3] -> [x1 x2 x3 3]
  1443  func opcodeDepth(op *parsedOpcode, vm *Engine) error {
  1444  	vm.dstack.PushInt(scriptNum(vm.dstack.Depth()))
  1445  	return nil
  1446  }
  1447  
  1448  // opcodeDrop removes the top item from the data stack.
  1449  //
  1450  // Stack transformation: [... x1 x2 x3] -> [... x1 x2]
  1451  func opcodeDrop(op *parsedOpcode, vm *Engine) error {
  1452  	return vm.dstack.DropN(1)
  1453  }
  1454  
  1455  // opcodeDup duplicates the top item on the data stack.
  1456  //
  1457  // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x3]
  1458  func opcodeDup(op *parsedOpcode, vm *Engine) error {
  1459  	return vm.dstack.DupN(1)
  1460  }
  1461  
  1462  // opcodeNip removes the item before the top item on the data stack.
  1463  //
  1464  // Stack transformation: [... x1 x2 x3] -> [... x1 x3]
  1465  func opcodeNip(op *parsedOpcode, vm *Engine) error {
  1466  	return vm.dstack.NipN(1)
  1467  }
  1468  
  1469  // opcodeOver duplicates the item before the top item on the data stack.
  1470  //
  1471  // Stack transformation: [... x1 x2 x3] -> [... x1 x2 x3 x2]
  1472  func opcodeOver(op *parsedOpcode, vm *Engine) error {
  1473  	return vm.dstack.OverN(1)
  1474  }
  1475  
  1476  // opcodePick treats the top item on the data stack as an integer and duplicates
  1477  // the item on the stack that number of items back to the top.
  1478  //
  1479  // Stack transformation: [xn ... x2 x1 x0 n] -> [xn ... x2 x1 x0 xn]
  1480  // Example with n=1: [x2 x1 x0 1] -> [x2 x1 x0 x1]
  1481  // Example with n=2: [x2 x1 x0 2] -> [x2 x1 x0 x2]
  1482  func opcodePick(op *parsedOpcode, vm *Engine) error {
  1483  	val, err := vm.dstack.PopInt()
  1484  	if err != nil {
  1485  		return err
  1486  	}
  1487  
  1488  	return vm.dstack.PickN(val.Int32())
  1489  }
  1490  
  1491  // opcodeRoll treats the top item on the data stack as an integer and moves
  1492  // the item on the stack that number of items back to the top.
  1493  //
  1494  // Stack transformation: [xn ... x2 x1 x0 n] -> [... x2 x1 x0 xn]
  1495  // Example with n=1: [x2 x1 x0 1] -> [x2 x0 x1]
  1496  // Example with n=2: [x2 x1 x0 2] -> [x1 x0 x2]
  1497  func opcodeRoll(op *parsedOpcode, vm *Engine) error {
  1498  	val, err := vm.dstack.PopInt()
  1499  	if err != nil {
  1500  		return err
  1501  	}
  1502  
  1503  	return vm.dstack.RollN(val.Int32())
  1504  }
  1505  
  1506  // opcodeRot rotates the top 3 items on the data stack to the left.
  1507  //
  1508  // Stack transformation: [... x1 x2 x3] -> [... x2 x3 x1]
  1509  func opcodeRot(op *parsedOpcode, vm *Engine) error {
  1510  	return vm.dstack.RotN(1)
  1511  }
  1512  
  1513  // opcodeSwap swaps the top two items on the stack.
  1514  //
  1515  // Stack transformation: [... x1 x2] -> [... x2 x1]
  1516  func opcodeSwap(op *parsedOpcode, vm *Engine) error {
  1517  	return vm.dstack.SwapN(1)
  1518  }
  1519  
  1520  // opcodeTuck inserts a duplicate of the top item of the data stack before the
  1521  // second-to-top item.
  1522  //
  1523  // Stack transformation: [... x1 x2] -> [... x2 x1 x2]
  1524  func opcodeTuck(op *parsedOpcode, vm *Engine) error {
  1525  	return vm.dstack.Tuck()
  1526  }
  1527  
  1528  // opcodeSize pushes the size of the top item of the data stack onto the data
  1529  // stack.
  1530  //
  1531  // Stack transformation: [... x1] -> [... x1 len(x1)]
  1532  func opcodeSize(op *parsedOpcode, vm *Engine) error {
  1533  	so, err := vm.dstack.PeekByteArray(0)
  1534  	if err != nil {
  1535  		return err
  1536  	}
  1537  
  1538  	vm.dstack.PushInt(scriptNum(len(so)))
  1539  	return nil
  1540  }
  1541  
  1542  // opcodeEqual removes the top 2 items of the data stack, compares them as raw
  1543  // bytes, and pushes the result, encoded as a boolean, back to the stack.
  1544  //
  1545  // Stack transformation: [... x1 x2] -> [... bool]
  1546  func opcodeEqual(op *parsedOpcode, vm *Engine) error {
  1547  	a, err := vm.dstack.PopByteArray()
  1548  	if err != nil {
  1549  		return err
  1550  	}
  1551  	b, err := vm.dstack.PopByteArray()
  1552  	if err != nil {
  1553  		return err
  1554  	}
  1555  
  1556  	vm.dstack.PushBool(bytes.Equal(a, b))
  1557  	return nil
  1558  }
  1559  
  1560  // opcodeEqualVerify is a combination of opcodeEqual and opcodeVerify.
  1561  // Specifically, it removes the top 2 items of the data stack, compares them,
  1562  // and pushes the result, encoded as a boolean, back to the stack.  Then, it
  1563  // examines the top item on the data stack as a boolean value and verifies it
  1564  // evaluates to true.  An error is returned if it does not.
  1565  //
  1566  // Stack transformation: [... x1 x2] -> [... bool] -> [...]
  1567  func opcodeEqualVerify(op *parsedOpcode, vm *Engine) error {
  1568  	err := opcodeEqual(op, vm)
  1569  	if err == nil {
  1570  		err = abstractVerify(op, vm, ErrEqualVerify)
  1571  	}
  1572  	return err
  1573  }
  1574  
  1575  // opcode1Add treats the top item on the data stack as an integer and replaces
  1576  // it with its incremented value (plus 1).
  1577  //
  1578  // Stack transformation: [... x1 x2] -> [... x1 x2+1]
  1579  func opcode1Add(op *parsedOpcode, vm *Engine) error {
  1580  	m, err := vm.dstack.PopInt()
  1581  	if err != nil {
  1582  		return err
  1583  	}
  1584  
  1585  	vm.dstack.PushInt(m + 1)
  1586  	return nil
  1587  }
  1588  
  1589  // opcode1Sub treats the top item on the data stack as an integer and replaces
  1590  // it with its decremented value (minus 1).
  1591  //
  1592  // Stack transformation: [... x1 x2] -> [... x1 x2-1]
  1593  func opcode1Sub(op *parsedOpcode, vm *Engine) error {
  1594  	m, err := vm.dstack.PopInt()
  1595  	if err != nil {
  1596  		return err
  1597  	}
  1598  	vm.dstack.PushInt(m - 1)
  1599  
  1600  	return nil
  1601  }
  1602  
  1603  // opcodeNegate treats the top item on the data stack as an integer and replaces
  1604  // it with its negation.
  1605  //
  1606  // Stack transformation: [... x1 x2] -> [... x1 -x2]
  1607  func opcodeNegate(op *parsedOpcode, vm *Engine) error {
  1608  	m, err := vm.dstack.PopInt()
  1609  	if err != nil {
  1610  		return err
  1611  	}
  1612  
  1613  	vm.dstack.PushInt(-m)
  1614  	return nil
  1615  }
  1616  
  1617  // opcodeAbs treats the top item on the data stack as an integer and replaces it
  1618  // it with its absolute value.
  1619  //
  1620  // Stack transformation: [... x1 x2] -> [... x1 abs(x2)]
  1621  func opcodeAbs(op *parsedOpcode, vm *Engine) error {
  1622  	m, err := vm.dstack.PopInt()
  1623  	if err != nil {
  1624  		return err
  1625  	}
  1626  
  1627  	if m < 0 {
  1628  		m = -m
  1629  	}
  1630  	vm.dstack.PushInt(m)
  1631  	return nil
  1632  }
  1633  
  1634  // opcodeNot treats the top item on the data stack as an integer and replaces
  1635  // it with its "inverted" value (0 becomes 1, non-zero becomes 0).
  1636  //
  1637  // NOTE: While it would probably make more sense to treat the top item as a
  1638  // boolean, and push the opposite, which is really what the intention of this
  1639  // opcode is, it is extremely important that is not done because integers are
  1640  // interpreted differently than booleans and the consensus rules for this opcode
  1641  // dictate the item is interpreted as an integer.
  1642  //
  1643  // Stack transformation (x2==0): [... x1 0] -> [... x1 1]
  1644  // Stack transformation (x2!=0): [... x1 1] -> [... x1 0]
  1645  // Stack transformation (x2!=0): [... x1 17] -> [... x1 0]
  1646  func opcodeNot(op *parsedOpcode, vm *Engine) error {
  1647  	m, err := vm.dstack.PopInt()
  1648  	if err != nil {
  1649  		return err
  1650  	}
  1651  
  1652  	if m == 0 {
  1653  		vm.dstack.PushInt(scriptNum(1))
  1654  	} else {
  1655  		vm.dstack.PushInt(scriptNum(0))
  1656  	}
  1657  	return nil
  1658  }
  1659  
  1660  // opcode0NotEqual treats the top item on the data stack as an integer and
  1661  // replaces it with either a 0 if it is zero, or a 1 if it is not zero.
  1662  //
  1663  // Stack transformation (x2==0): [... x1 0] -> [... x1 0]
  1664  // Stack transformation (x2!=0): [... x1 1] -> [... x1 1]
  1665  // Stack transformation (x2!=0): [... x1 17] -> [... x1 1]
  1666  func opcode0NotEqual(op *parsedOpcode, vm *Engine) error {
  1667  	m, err := vm.dstack.PopInt()
  1668  	if err != nil {
  1669  		return err
  1670  	}
  1671  
  1672  	if m != 0 {
  1673  		m = 1
  1674  	}
  1675  	vm.dstack.PushInt(m)
  1676  	return nil
  1677  }
  1678  
  1679  // opcodeAdd treats the top two items on the data stack as integers and replaces
  1680  // them with their sum.
  1681  //
  1682  // Stack transformation: [... x1 x2] -> [... x1+x2]
  1683  func opcodeAdd(op *parsedOpcode, vm *Engine) error {
  1684  	v0, err := vm.dstack.PopInt()
  1685  	if err != nil {
  1686  		return err
  1687  	}
  1688  
  1689  	v1, err := vm.dstack.PopInt()
  1690  	if err != nil {
  1691  		return err
  1692  	}
  1693  
  1694  	vm.dstack.PushInt(v0 + v1)
  1695  	return nil
  1696  }
  1697  
  1698  // opcodeSub treats the top two items on the data stack as integers and replaces
  1699  // them with the result of subtracting the top entry from the second-to-top
  1700  // entry.
  1701  //
  1702  // Stack transformation: [... x1 x2] -> [... x1-x2]
  1703  func opcodeSub(op *parsedOpcode, vm *Engine) error {
  1704  	v0, err := vm.dstack.PopInt()
  1705  	if err != nil {
  1706  		return err
  1707  	}
  1708  
  1709  	v1, err := vm.dstack.PopInt()
  1710  	if err != nil {
  1711  		return err
  1712  	}
  1713  
  1714  	vm.dstack.PushInt(v1 - v0)
  1715  	return nil
  1716  }
  1717  
  1718  // opcodeBoolAnd treats the top two items on the data stack as integers.  When
  1719  // both of them are not zero, they are replaced with a 1, otherwise a 0.
  1720  //
  1721  // Stack transformation (x1==0, x2==0): [... 0 0] -> [... 0]
  1722  // Stack transformation (x1!=0, x2==0): [... 5 0] -> [... 0]
  1723  // Stack transformation (x1==0, x2!=0): [... 0 7] -> [... 0]
  1724  // Stack transformation (x1!=0, x2!=0): [... 4 8] -> [... 1]
  1725  func opcodeBoolAnd(op *parsedOpcode, vm *Engine) error {
  1726  	v0, err := vm.dstack.PopInt()
  1727  	if err != nil {
  1728  		return err
  1729  	}
  1730  
  1731  	v1, err := vm.dstack.PopInt()
  1732  	if err != nil {
  1733  		return err
  1734  	}
  1735  
  1736  	if v0 != 0 && v1 != 0 {
  1737  		vm.dstack.PushInt(scriptNum(1))
  1738  	} else {
  1739  		vm.dstack.PushInt(scriptNum(0))
  1740  	}
  1741  
  1742  	return nil
  1743  }
  1744  
  1745  // opcodeBoolOr treats the top two items on the data stack as integers.  When
  1746  // either of them are not zero, they are replaced with a 1, otherwise a 0.
  1747  //
  1748  // Stack transformation (x1==0, x2==0): [... 0 0] -> [... 0]
  1749  // Stack transformation (x1!=0, x2==0): [... 5 0] -> [... 1]
  1750  // Stack transformation (x1==0, x2!=0): [... 0 7] -> [... 1]
  1751  // Stack transformation (x1!=0, x2!=0): [... 4 8] -> [... 1]
  1752  func opcodeBoolOr(op *parsedOpcode, vm *Engine) error {
  1753  	v0, err := vm.dstack.PopInt()
  1754  	if err != nil {
  1755  		return err
  1756  	}
  1757  
  1758  	v1, err := vm.dstack.PopInt()
  1759  	if err != nil {
  1760  		return err
  1761  	}
  1762  
  1763  	if v0 != 0 || v1 != 0 {
  1764  		vm.dstack.PushInt(scriptNum(1))
  1765  	} else {
  1766  		vm.dstack.PushInt(scriptNum(0))
  1767  	}
  1768  
  1769  	return nil
  1770  }
  1771  
  1772  // opcodeNumEqual treats the top two items on the data stack as integers.  When
  1773  // they are equal, they are replaced with a 1, otherwise a 0.
  1774  //
  1775  // Stack transformation (x1==x2): [... 5 5] -> [... 1]
  1776  // Stack transformation (x1!=x2): [... 5 7] -> [... 0]
  1777  func opcodeNumEqual(op *parsedOpcode, vm *Engine) error {
  1778  	v0, err := vm.dstack.PopInt()
  1779  	if err != nil {
  1780  		return err
  1781  	}
  1782  
  1783  	v1, err := vm.dstack.PopInt()
  1784  	if err != nil {
  1785  		return err
  1786  	}
  1787  
  1788  	if v0 == v1 {
  1789  		vm.dstack.PushInt(scriptNum(1))
  1790  	} else {
  1791  		vm.dstack.PushInt(scriptNum(0))
  1792  	}
  1793  
  1794  	return nil
  1795  }
  1796  
  1797  // opcodeNumEqualVerify is a combination of opcodeNumEqual and opcodeVerify.
  1798  //
  1799  // Specifically, treats the top two items on the data stack as integers.  When
  1800  // they are equal, they are replaced with a 1, otherwise a 0.  Then, it examines
  1801  // the top item on the data stack as a boolean value and verifies it evaluates
  1802  // to true.  An error is returned if it does not.
  1803  //
  1804  // Stack transformation: [... x1 x2] -> [... bool] -> [...]
  1805  func opcodeNumEqualVerify(op *parsedOpcode, vm *Engine) error {
  1806  	err := opcodeNumEqual(op, vm)
  1807  	if err == nil {
  1808  		err = abstractVerify(op, vm, ErrNumEqualVerify)
  1809  	}
  1810  	return err
  1811  }
  1812  
  1813  // opcodeNumNotEqual treats the top two items on the data stack as integers.
  1814  // When they are NOT equal, they are replaced with a 1, otherwise a 0.
  1815  //
  1816  // Stack transformation (x1==x2): [... 5 5] -> [... 0]
  1817  // Stack transformation (x1!=x2): [... 5 7] -> [... 1]
  1818  func opcodeNumNotEqual(op *parsedOpcode, vm *Engine) error {
  1819  	v0, err := vm.dstack.PopInt()
  1820  	if err != nil {
  1821  		return err
  1822  	}
  1823  
  1824  	v1, err := vm.dstack.PopInt()
  1825  	if err != nil {
  1826  		return err
  1827  	}
  1828  
  1829  	if v0 != v1 {
  1830  		vm.dstack.PushInt(scriptNum(1))
  1831  	} else {
  1832  		vm.dstack.PushInt(scriptNum(0))
  1833  	}
  1834  
  1835  	return nil
  1836  }
  1837  
  1838  // opcodeLessThan treats the top two items on the data stack as integers.  When
  1839  // the second-to-top item is less than the top item, they are replaced with a 1,
  1840  // otherwise a 0.
  1841  //
  1842  // Stack transformation: [... x1 x2] -> [... bool]
  1843  func opcodeLessThan(op *parsedOpcode, vm *Engine) error {
  1844  	v0, err := vm.dstack.PopInt()
  1845  	if err != nil {
  1846  		return err
  1847  	}
  1848  
  1849  	v1, err := vm.dstack.PopInt()
  1850  	if err != nil {
  1851  		return err
  1852  	}
  1853  
  1854  	if v1 < v0 {
  1855  		vm.dstack.PushInt(scriptNum(1))
  1856  	} else {
  1857  		vm.dstack.PushInt(scriptNum(0))
  1858  	}
  1859  
  1860  	return nil
  1861  }
  1862  
  1863  // opcodeGreaterThan treats the top two items on the data stack as integers.
  1864  // When the second-to-top item is greater than the top item, they are replaced
  1865  // with a 1, otherwise a 0.
  1866  //
  1867  // Stack transformation: [... x1 x2] -> [... bool]
  1868  func opcodeGreaterThan(op *parsedOpcode, vm *Engine) error {
  1869  	v0, err := vm.dstack.PopInt()
  1870  	if err != nil {
  1871  		return err
  1872  	}
  1873  
  1874  	v1, err := vm.dstack.PopInt()
  1875  	if err != nil {
  1876  		return err
  1877  	}
  1878  
  1879  	if v1 > v0 {
  1880  		vm.dstack.PushInt(scriptNum(1))
  1881  	} else {
  1882  		vm.dstack.PushInt(scriptNum(0))
  1883  	}
  1884  	return nil
  1885  }
  1886  
  1887  // opcodeLessThanOrEqual treats the top two items on the data stack as integers.
  1888  // When the second-to-top item is less than or equal to the top item, they are
  1889  // replaced with a 1, otherwise a 0.
  1890  //
  1891  // Stack transformation: [... x1 x2] -> [... bool]
  1892  func opcodeLessThanOrEqual(op *parsedOpcode, vm *Engine) error {
  1893  	v0, err := vm.dstack.PopInt()
  1894  	if err != nil {
  1895  		return err
  1896  	}
  1897  
  1898  	v1, err := vm.dstack.PopInt()
  1899  	if err != nil {
  1900  		return err
  1901  	}
  1902  
  1903  	if v1 <= v0 {
  1904  		vm.dstack.PushInt(scriptNum(1))
  1905  	} else {
  1906  		vm.dstack.PushInt(scriptNum(0))
  1907  	}
  1908  	return nil
  1909  }
  1910  
  1911  // opcodeGreaterThanOrEqual treats the top two items on the data stack as
  1912  // integers.  When the second-to-top item is greater than or equal to the top
  1913  // item, they are replaced with a 1, otherwise a 0.
  1914  //
  1915  // Stack transformation: [... x1 x2] -> [... bool]
  1916  func opcodeGreaterThanOrEqual(op *parsedOpcode, vm *Engine) error {
  1917  	v0, err := vm.dstack.PopInt()
  1918  	if err != nil {
  1919  		return err
  1920  	}
  1921  
  1922  	v1, err := vm.dstack.PopInt()
  1923  	if err != nil {
  1924  		return err
  1925  	}
  1926  
  1927  	if v1 >= v0 {
  1928  		vm.dstack.PushInt(scriptNum(1))
  1929  	} else {
  1930  		vm.dstack.PushInt(scriptNum(0))
  1931  	}
  1932  
  1933  	return nil
  1934  }
  1935  
  1936  // opcodeMin treats the top two items on the data stack as integers and replaces
  1937  // them with the minimum of the two.
  1938  //
  1939  // Stack transformation: [... x1 x2] -> [... min(x1, x2)]
  1940  func opcodeMin(op *parsedOpcode, vm *Engine) error {
  1941  	v0, err := vm.dstack.PopInt()
  1942  	if err != nil {
  1943  		return err
  1944  	}
  1945  
  1946  	v1, err := vm.dstack.PopInt()
  1947  	if err != nil {
  1948  		return err
  1949  	}
  1950  
  1951  	if v1 < v0 {
  1952  		vm.dstack.PushInt(v1)
  1953  	} else {
  1954  		vm.dstack.PushInt(v0)
  1955  	}
  1956  
  1957  	return nil
  1958  }
  1959  
  1960  // opcodeMax treats the top two items on the data stack as integers and replaces
  1961  // them with the maximum of the two.
  1962  //
  1963  // Stack transformation: [... x1 x2] -> [... max(x1, x2)]
  1964  func opcodeMax(op *parsedOpcode, vm *Engine) error {
  1965  	v0, err := vm.dstack.PopInt()
  1966  	if err != nil {
  1967  		return err
  1968  	}
  1969  
  1970  	v1, err := vm.dstack.PopInt()
  1971  	if err != nil {
  1972  		return err
  1973  	}
  1974  
  1975  	if v1 > v0 {
  1976  		vm.dstack.PushInt(v1)
  1977  	} else {
  1978  		vm.dstack.PushInt(v0)
  1979  	}
  1980  
  1981  	return nil
  1982  }
  1983  
  1984  // opcodeWithin treats the top 3 items on the data stack as integers.  When the
  1985  // value to test is within the specified range (left inclusive), they are
  1986  // replaced with a 1, otherwise a 0.
  1987  //
  1988  // The top item is the max value, the second-top-item is the minimum value, and
  1989  // the third-to-top item is the value to test.
  1990  //
  1991  // Stack transformation: [... x1 min max] -> [... bool]
  1992  func opcodeWithin(op *parsedOpcode, vm *Engine) error {
  1993  	maxVal, err := vm.dstack.PopInt()
  1994  	if err != nil {
  1995  		return err
  1996  	}
  1997  
  1998  	minVal, err := vm.dstack.PopInt()
  1999  	if err != nil {
  2000  		return err
  2001  	}
  2002  
  2003  	x, err := vm.dstack.PopInt()
  2004  	if err != nil {
  2005  		return err
  2006  	}
  2007  
  2008  	if x >= minVal && x < maxVal {
  2009  		vm.dstack.PushInt(scriptNum(1))
  2010  	} else {
  2011  		vm.dstack.PushInt(scriptNum(0))
  2012  	}
  2013  	return nil
  2014  }
  2015  
  2016  // calcHash calculates the hash of hasher over buf.
  2017  func calcHash(buf []byte, hasher hash.Hash) []byte {
  2018  	hasher.Write(buf)
  2019  	return hasher.Sum(nil)
  2020  }
  2021  
  2022  // opcodeRipemd160 treats the top item of the data stack as raw bytes and
  2023  // replaces it with ripemd160(data).
  2024  //
  2025  // Stack transformation: [... x1] -> [... ripemd160(x1)]
  2026  func opcodeRipemd160(op *parsedOpcode, vm *Engine) error {
  2027  	buf, err := vm.dstack.PopByteArray()
  2028  	if err != nil {
  2029  		return err
  2030  	}
  2031  
  2032  	vm.dstack.PushByteArray(calcHash(buf, ripemd160.New()))
  2033  	return nil
  2034  }
  2035  
  2036  // opcodeSha1 treats the top item of the data stack as raw bytes and replaces it
  2037  // with sha1(data).
  2038  //
  2039  // Stack transformation: [... x1] -> [... sha1(x1)]
  2040  func opcodeSha1(op *parsedOpcode, vm *Engine) error {
  2041  	buf, err := vm.dstack.PopByteArray()
  2042  	if err != nil {
  2043  		return err
  2044  	}
  2045  
  2046  	hash := sha1.Sum(buf)
  2047  	vm.dstack.PushByteArray(hash[:])
  2048  	return nil
  2049  }
  2050  
  2051  // opcodeSha256 treats the top item of the data stack as raw bytes and replaces
  2052  // it with sha256(data).
  2053  //
  2054  // Stack transformation: [... x1] -> [... sha256(x1)]
  2055  func opcodeSha256(op *parsedOpcode, vm *Engine) error {
  2056  	buf, err := vm.dstack.PopByteArray()
  2057  	if err != nil {
  2058  		return err
  2059  	}
  2060  
  2061  	hash := sha256.Sum256(buf)
  2062  	vm.dstack.PushByteArray(hash[:])
  2063  	return nil
  2064  }
  2065  
  2066  // opcodeHash160 treats the top item of the data stack as raw bytes and replaces
  2067  // it with ripemd160(sha256(data)).
  2068  //
  2069  // Stack transformation: [... x1] -> [... ripemd160(sha256(x1))]
  2070  func opcodeHash160(op *parsedOpcode, vm *Engine) error {
  2071  	buf, err := vm.dstack.PopByteArray()
  2072  	if err != nil {
  2073  		return err
  2074  	}
  2075  
  2076  	hash := sha256.Sum256(buf)
  2077  	vm.dstack.PushByteArray(calcHash(hash[:], ripemd160.New()))
  2078  	return nil
  2079  }
  2080  
  2081  // opcodeHash256 treats the top item of the data stack as raw bytes and replaces
  2082  // it with sha256(sha256(data)).
  2083  //
  2084  // Stack transformation: [... x1] -> [... sha256(sha256(x1))]
  2085  func opcodeHash256(op *parsedOpcode, vm *Engine) error {
  2086  	buf, err := vm.dstack.PopByteArray()
  2087  	if err != nil {
  2088  		return err
  2089  	}
  2090  
  2091  	vm.dstack.PushByteArray(chainhash.DoubleHashB(buf))
  2092  	return nil
  2093  }
  2094  
  2095  // opcodeCodeSeparator stores the current script offset as the most recently
  2096  // seen OP_CODESEPARATOR which is used during signature checking.
  2097  //
  2098  // This opcode does not change the contents of the data stack.
  2099  func opcodeCodeSeparator(op *parsedOpcode, vm *Engine) error {
  2100  	vm.lastCodeSep = vm.scriptOff
  2101  	return nil
  2102  }
  2103  
  2104  // opcodeCheckSig treats the top 2 items on the stack as a public key and a
  2105  // signature and replaces them with a bool which indicates if the signature was
  2106  // successfully verified.
  2107  //
  2108  // The process of verifying a signature requires calculating a signature hash in
  2109  // the same way the transaction signer did.  It involves hashing portions of the
  2110  // transaction based on the hash type byte (which is the final byte of the
  2111  // signature) and the portion of the script starting from the most recent
  2112  // OP_CODESEPARATOR (or the beginning of the script if there are none) to the
  2113  // end of the script (with any other OP_CODESEPARATORs removed).  Once this
  2114  // "script hash" is calculated, the signature is checked using standard
  2115  // cryptographic methods against the provided public key.
  2116  //
  2117  // Stack transformation: [... signature pubkey] -> [... bool]
  2118  func opcodeCheckSig(op *parsedOpcode, vm *Engine) error {
  2119  	pkBytes, err := vm.dstack.PopByteArray()
  2120  	if err != nil {
  2121  		return err
  2122  	}
  2123  
  2124  	fullSigBytes, err := vm.dstack.PopByteArray()
  2125  	if err != nil {
  2126  		return err
  2127  	}
  2128  
  2129  	// The signature actually needs needs to be longer than this, but at
  2130  	// least 1 byte is needed for the hash type below.  The full length is
  2131  	// checked depending on the script flags and upon parsing the signature.
  2132  	if len(fullSigBytes) < 1 {
  2133  		vm.dstack.PushBool(false)
  2134  		return nil
  2135  	}
  2136  
  2137  	// Trim off hashtype from the signature string and check if the
  2138  	// signature and pubkey conform to the strict encoding requirements
  2139  	// depending on the flags.
  2140  	//
  2141  	// NOTE: When the strict encoding flags are set, any errors in the
  2142  	// signature or public encoding here result in an immediate script error
  2143  	// (and thus no result bool is pushed to the data stack).  This differs
  2144  	// from the logic below where any errors in parsing the signature is
  2145  	// treated as the signature failure resulting in false being pushed to
  2146  	// the data stack.  This is required because the more general script
  2147  	// validation consensus rules do not have the new strict encoding
  2148  	// requirements enabled by the flags.
  2149  	hashType := SigHashType(fullSigBytes[len(fullSigBytes)-1])
  2150  	sigBytes := fullSigBytes[:len(fullSigBytes)-1]
  2151  	if err := vm.checkHashTypeEncoding(hashType); err != nil {
  2152  		return err
  2153  	}
  2154  	if err := vm.checkSignatureEncoding(sigBytes); err != nil {
  2155  		return err
  2156  	}
  2157  	if err := vm.checkPubKeyEncoding(pkBytes); err != nil {
  2158  		return err
  2159  	}
  2160  
  2161  	// Get script starting from the most recent OP_CODESEPARATOR.
  2162  	subScript := vm.subScript()
  2163  
  2164  	// Generate the signature hash based on the signature hash type.
  2165  	var hash []byte
  2166  	if vm.isWitnessVersionActive(0) {
  2167  		var sigHashes *TxSigHashes
  2168  		if vm.hashCache != nil {
  2169  			sigHashes = vm.hashCache
  2170  		} else {
  2171  			sigHashes = NewTxSigHashes(&vm.tx)
  2172  		}
  2173  
  2174  		hash, err = calcWitnessSignatureHash(subScript, sigHashes, hashType,
  2175  			&vm.tx, vm.txIdx, vm.inputAmount)
  2176  		if err != nil {
  2177  			return err
  2178  		}
  2179  	} else {
  2180  		// Remove the signature since there is no way for a signature
  2181  		// to sign itself.
  2182  		subScript = removeOpcodeByData(subScript, fullSigBytes)
  2183  
  2184  		hash = calcSignatureHash(subScript, hashType, &vm.tx, vm.txIdx)
  2185  	}
  2186  
  2187  	pubKey, err := btcec.ParsePubKey(pkBytes, btcec.S256())
  2188  	if err != nil {
  2189  		vm.dstack.PushBool(false)
  2190  		return nil
  2191  	}
  2192  
  2193  	var signature *btcec.Signature
  2194  	if vm.hasFlag(ScriptVerifyStrictEncoding) ||
  2195  		vm.hasFlag(ScriptVerifyDERSignatures) {
  2196  
  2197  		signature, err = btcec.ParseDERSignature(sigBytes, btcec.S256())
  2198  	} else {
  2199  		signature, err = btcec.ParseSignature(sigBytes, btcec.S256())
  2200  	}
  2201  	if err != nil {
  2202  		vm.dstack.PushBool(false)
  2203  		return nil
  2204  	}
  2205  
  2206  	var valid bool
  2207  	if vm.sigCache != nil {
  2208  		var sigHash chainhash.Hash
  2209  		copy(sigHash[:], hash)
  2210  
  2211  		valid = vm.sigCache.Exists(sigHash, signature, pubKey)
  2212  		if !valid && signature.Verify(hash, pubKey) {
  2213  			vm.sigCache.Add(sigHash, signature, pubKey)
  2214  			valid = true
  2215  		}
  2216  	} else {
  2217  		valid = signature.Verify(hash, pubKey)
  2218  	}
  2219  
  2220  	if !valid && vm.hasFlag(ScriptVerifyNullFail) && len(sigBytes) > 0 {
  2221  		str := "signature not empty on failed checksig"
  2222  		return scriptError(ErrNullFail, str)
  2223  	}
  2224  
  2225  	vm.dstack.PushBool(valid)
  2226  	return nil
  2227  }
  2228  
  2229  // opcodeCheckSigVerify is a combination of opcodeCheckSig and opcodeVerify.
  2230  // The opcodeCheckSig function is invoked followed by opcodeVerify.  See the
  2231  // documentation for each of those opcodes for more details.
  2232  //
  2233  // Stack transformation: signature pubkey] -> [... bool] -> [...]
  2234  func opcodeCheckSigVerify(op *parsedOpcode, vm *Engine) error {
  2235  	err := opcodeCheckSig(op, vm)
  2236  	if err == nil {
  2237  		err = abstractVerify(op, vm, ErrCheckSigVerify)
  2238  	}
  2239  	return err
  2240  }
  2241  
  2242  // parsedSigInfo houses a raw signature along with its parsed form and a flag
  2243  // for whether or not it has already been parsed.  It is used to prevent parsing
  2244  // the same signature multiple times when verifying a multisig.
  2245  type parsedSigInfo struct {
  2246  	signature       []byte
  2247  	parsedSignature *btcec.Signature
  2248  	parsed          bool
  2249  }
  2250  
  2251  // opcodeCheckMultiSig treats the top item on the stack as an integer number of
  2252  // public keys, followed by that many entries as raw data representing the public
  2253  // keys, followed by the integer number of signatures, followed by that many
  2254  // entries as raw data representing the signatures.
  2255  //
  2256  // Due to a bug in the original Satoshi client implementation, an additional
  2257  // dummy argument is also required by the consensus rules, although it is not
  2258  // used.  The dummy value SHOULD be an OP_0, although that is not required by
  2259  // the consensus rules.  When the ScriptStrictMultiSig flag is set, it must be
  2260  // OP_0.
  2261  //
  2262  // All of the aforementioned stack items are replaced with a bool which
  2263  // indicates if the requisite number of signatures were successfully verified.
  2264  //
  2265  // See the opcodeCheckSigVerify documentation for more details about the process
  2266  // for verifying each signature.
  2267  //
  2268  // Stack transformation:
  2269  // [... dummy [sig ...] numsigs [pubkey ...] numpubkeys] -> [... bool]
  2270  func opcodeCheckMultiSig(op *parsedOpcode, vm *Engine) error {
  2271  	numKeys, err := vm.dstack.PopInt()
  2272  	if err != nil {
  2273  		return err
  2274  	}
  2275  
  2276  	numPubKeys := int(numKeys.Int32())
  2277  	if numPubKeys < 0 {
  2278  		str := fmt.Sprintf("number of pubkeys %d is negative",
  2279  			numPubKeys)
  2280  		return scriptError(ErrInvalidPubKeyCount, str)
  2281  	}
  2282  	if numPubKeys > MaxPubKeysPerMultiSig {
  2283  		str := fmt.Sprintf("too many pubkeys: %d > %d",
  2284  			numPubKeys, MaxPubKeysPerMultiSig)
  2285  		return scriptError(ErrInvalidPubKeyCount, str)
  2286  	}
  2287  	vm.numOps += numPubKeys
  2288  	if vm.numOps > MaxOpsPerScript {
  2289  		str := fmt.Sprintf("exceeded max operation limit of %d",
  2290  			MaxOpsPerScript)
  2291  		return scriptError(ErrTooManyOperations, str)
  2292  	}
  2293  
  2294  	pubKeys := make([][]byte, 0, numPubKeys)
  2295  	for i := 0; i < numPubKeys; i++ {
  2296  		pubKey, err := vm.dstack.PopByteArray()
  2297  		if err != nil {
  2298  			return err
  2299  		}
  2300  		pubKeys = append(pubKeys, pubKey)
  2301  	}
  2302  
  2303  	numSigs, err := vm.dstack.PopInt()
  2304  	if err != nil {
  2305  		return err
  2306  	}
  2307  	numSignatures := int(numSigs.Int32())
  2308  	if numSignatures < 0 {
  2309  		str := fmt.Sprintf("number of signatures %d is negative",
  2310  			numSignatures)
  2311  		return scriptError(ErrInvalidSignatureCount, str)
  2312  
  2313  	}
  2314  	if numSignatures > numPubKeys {
  2315  		str := fmt.Sprintf("more signatures than pubkeys: %d > %d",
  2316  			numSignatures, numPubKeys)
  2317  		return scriptError(ErrInvalidSignatureCount, str)
  2318  	}
  2319  
  2320  	signatures := make([]*parsedSigInfo, 0, numSignatures)
  2321  	for i := 0; i < numSignatures; i++ {
  2322  		signature, err := vm.dstack.PopByteArray()
  2323  		if err != nil {
  2324  			return err
  2325  		}
  2326  		sigInfo := &parsedSigInfo{signature: signature}
  2327  		signatures = append(signatures, sigInfo)
  2328  	}
  2329  
  2330  	// A bug in the original Satoshi client implementation means one more
  2331  	// stack value than should be used must be popped.  Unfortunately, this
  2332  	// buggy behavior is now part of the consensus and a hard fork would be
  2333  	// required to fix it.
  2334  	dummy, err := vm.dstack.PopByteArray()
  2335  	if err != nil {
  2336  		return err
  2337  	}
  2338  
  2339  	// Since the dummy argument is otherwise not checked, it could be any
  2340  	// value which unfortunately provides a source of malleability.  Thus,
  2341  	// there is a script flag to force an error when the value is NOT 0.
  2342  	if vm.hasFlag(ScriptStrictMultiSig) && len(dummy) != 0 {
  2343  		str := fmt.Sprintf("multisig dummy argument has length %d "+
  2344  			"instead of 0", len(dummy))
  2345  		return scriptError(ErrSigNullDummy, str)
  2346  	}
  2347  
  2348  	// Get script starting from the most recent OP_CODESEPARATOR.
  2349  	script := vm.subScript()
  2350  
  2351  	// Remove the signature in pre version 0 segwit scripts since there is
  2352  	// no way for a signature to sign itself.
  2353  	if !vm.isWitnessVersionActive(0) {
  2354  		for _, sigInfo := range signatures {
  2355  			script = removeOpcodeByData(script, sigInfo.signature)
  2356  		}
  2357  	}
  2358  
  2359  	success := true
  2360  	numPubKeys++
  2361  	pubKeyIdx := -1
  2362  	signatureIdx := 0
  2363  	for numSignatures > 0 {
  2364  		// When there are more signatures than public keys remaining,
  2365  		// there is no way to succeed since too many signatures are
  2366  		// invalid, so exit early.
  2367  		pubKeyIdx++
  2368  		numPubKeys--
  2369  		if numSignatures > numPubKeys {
  2370  			success = false
  2371  			break
  2372  		}
  2373  
  2374  		sigInfo := signatures[signatureIdx]
  2375  		pubKey := pubKeys[pubKeyIdx]
  2376  
  2377  		// The order of the signature and public key evaluation is
  2378  		// important here since it can be distinguished by an
  2379  		// OP_CHECKMULTISIG NOT when the strict encoding flag is set.
  2380  
  2381  		rawSig := sigInfo.signature
  2382  		if len(rawSig) == 0 {
  2383  			// Skip to the next pubkey if signature is empty.
  2384  			continue
  2385  		}
  2386  
  2387  		// Split the signature into hash type and signature components.
  2388  		hashType := SigHashType(rawSig[len(rawSig)-1])
  2389  		signature := rawSig[:len(rawSig)-1]
  2390  
  2391  		// Only parse and check the signature encoding once.
  2392  		var parsedSig *btcec.Signature
  2393  		if !sigInfo.parsed {
  2394  			if err := vm.checkHashTypeEncoding(hashType); err != nil {
  2395  				return err
  2396  			}
  2397  			if err := vm.checkSignatureEncoding(signature); err != nil {
  2398  				return err
  2399  			}
  2400  
  2401  			// Parse the signature.
  2402  			var err error
  2403  			if vm.hasFlag(ScriptVerifyStrictEncoding) ||
  2404  				vm.hasFlag(ScriptVerifyDERSignatures) {
  2405  
  2406  				parsedSig, err = btcec.ParseDERSignature(signature,
  2407  					btcec.S256())
  2408  			} else {
  2409  				parsedSig, err = btcec.ParseSignature(signature,
  2410  					btcec.S256())
  2411  			}
  2412  			sigInfo.parsed = true
  2413  			if err != nil {
  2414  				continue
  2415  			}
  2416  			sigInfo.parsedSignature = parsedSig
  2417  		} else {
  2418  			// Skip to the next pubkey if the signature is invalid.
  2419  			if sigInfo.parsedSignature == nil {
  2420  				continue
  2421  			}
  2422  
  2423  			// Use the already parsed signature.
  2424  			parsedSig = sigInfo.parsedSignature
  2425  		}
  2426  
  2427  		if err := vm.checkPubKeyEncoding(pubKey); err != nil {
  2428  			return err
  2429  		}
  2430  
  2431  		// Parse the pubkey.
  2432  		parsedPubKey, err := btcec.ParsePubKey(pubKey, btcec.S256())
  2433  		if err != nil {
  2434  			continue
  2435  		}
  2436  
  2437  		// Generate the signature hash based on the signature hash type.
  2438  		var hash []byte
  2439  		if vm.isWitnessVersionActive(0) {
  2440  			var sigHashes *TxSigHashes
  2441  			if vm.hashCache != nil {
  2442  				sigHashes = vm.hashCache
  2443  			} else {
  2444  				sigHashes = NewTxSigHashes(&vm.tx)
  2445  			}
  2446  
  2447  			hash, err = calcWitnessSignatureHash(script, sigHashes, hashType,
  2448  				&vm.tx, vm.txIdx, vm.inputAmount)
  2449  			if err != nil {
  2450  				return err
  2451  			}
  2452  		} else {
  2453  			hash = calcSignatureHash(script, hashType, &vm.tx, vm.txIdx)
  2454  		}
  2455  
  2456  		var valid bool
  2457  		if vm.sigCache != nil {
  2458  			var sigHash chainhash.Hash
  2459  			copy(sigHash[:], hash)
  2460  
  2461  			valid = vm.sigCache.Exists(sigHash, parsedSig, parsedPubKey)
  2462  			if !valid && parsedSig.Verify(hash, parsedPubKey) {
  2463  				vm.sigCache.Add(sigHash, parsedSig, parsedPubKey)
  2464  				valid = true
  2465  			}
  2466  		} else {
  2467  			valid = parsedSig.Verify(hash, parsedPubKey)
  2468  		}
  2469  
  2470  		if valid {
  2471  			// PubKey verified, move on to the next signature.
  2472  			signatureIdx++
  2473  			numSignatures--
  2474  		}
  2475  	}
  2476  
  2477  	if !success && vm.hasFlag(ScriptVerifyNullFail) {
  2478  		for _, sig := range signatures {
  2479  			if len(sig.signature) > 0 {
  2480  				str := "not all signatures empty on failed checkmultisig"
  2481  				return scriptError(ErrNullFail, str)
  2482  			}
  2483  		}
  2484  	}
  2485  
  2486  	vm.dstack.PushBool(success)
  2487  	return nil
  2488  }
  2489  
  2490  // opcodeCheckMultiSigVerify is a combination of opcodeCheckMultiSig and
  2491  // opcodeVerify.  The opcodeCheckMultiSig is invoked followed by opcodeVerify.
  2492  // See the documentation for each of those opcodes for more details.
  2493  //
  2494  // Stack transformation:
  2495  // [... dummy [sig ...] numsigs [pubkey ...] numpubkeys] -> [... bool] -> [...]
  2496  func opcodeCheckMultiSigVerify(op *parsedOpcode, vm *Engine) error {
  2497  	err := opcodeCheckMultiSig(op, vm)
  2498  	if err == nil {
  2499  		err = abstractVerify(op, vm, ErrCheckMultiSigVerify)
  2500  	}
  2501  	return err
  2502  }
  2503  
  2504  // OpcodeByName is a map that can be used to lookup an opcode by its
  2505  // human-readable name (OP_CHECKMULTISIG, OP_CHECKSIG, etc).
  2506  var OpcodeByName = make(map[string]byte)
  2507  
  2508  func init() {
  2509  	// Initialize the opcode name to value map using the contents of the
  2510  	// opcode array.  Also add entries for "OP_FALSE", "OP_TRUE", and
  2511  	// "OP_NOP2" since they are aliases for "OP_0", "OP_1",
  2512  	// and "OP_CHECKLOCKTIMEVERIFY" respectively.
  2513  	for _, op := range opcodeArray {
  2514  		OpcodeByName[op.name] = op.value
  2515  	}
  2516  	OpcodeByName["OP_FALSE"] = OP_FALSE
  2517  	OpcodeByName["OP_TRUE"] = OP_TRUE
  2518  	OpcodeByName["OP_NOP2"] = OP_CHECKLOCKTIMEVERIFY
  2519  	OpcodeByName["OP_NOP3"] = OP_CHECKSEQUENCEVERIFY
  2520  }