github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/txscript/opcode.go (about)

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