opcode.go raw

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