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