Completed
Pull Request — master (#392)
by thomas
24:31
created

Interpreter::isValidSignatureEncoding()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
ccs 0
cts 5
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace BitWasp\Bitcoin\Script\Interpreter;
4
5
use BitWasp\Bitcoin\Bitcoin;
6
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface;
7
use BitWasp\Bitcoin\Crypto\Hash;
8
use BitWasp\Bitcoin\Exceptions\SignatureNotCanonical;
9
use BitWasp\Bitcoin\Exceptions\ScriptRuntimeException;
10
use BitWasp\Bitcoin\Script\Classifier\OutputClassifier;
11
use BitWasp\Bitcoin\Script\Opcodes;
12
use BitWasp\Bitcoin\Script\Script;
13
use BitWasp\Bitcoin\Script\ScriptFactory;
14
use BitWasp\Bitcoin\Script\ScriptInterface;
15
use BitWasp\Bitcoin\Script\ScriptWitness;
16
use BitWasp\Bitcoin\Script\ScriptWitnessInterface;
17
use BitWasp\Bitcoin\Script\WitnessProgram;
18
use BitWasp\Bitcoin\Signature\TransactionSignature;
19
use BitWasp\Bitcoin\Transaction\SignatureHash\SigHash;
20
use BitWasp\Bitcoin\Transaction\TransactionInputInterface;
21
use BitWasp\Buffertools\Buffer;
22
use BitWasp\Buffertools\BufferInterface;
23
24
class Interpreter implements InterpreterInterface
25
{
26
27
    /**
28
     * @var \BitWasp\Bitcoin\Math\Math
29
     */
30
    private $math;
31
32
    /**
33
     * @var BufferInterface
34
     */
35
    private $vchFalse;
36
37
    /**
38
     * @var BufferInterface
39
     */
40
    private $vchTrue;
41
42
    /**
43
     * @var array
44
     */
45
    private $disabledOps = [
46
        Opcodes::OP_CAT,    Opcodes::OP_SUBSTR, Opcodes::OP_LEFT,  Opcodes::OP_RIGHT,
47
        Opcodes::OP_INVERT, Opcodes::OP_AND,    Opcodes::OP_OR,    Opcodes::OP_XOR,
48
        Opcodes::OP_2MUL,   Opcodes::OP_2DIV,   Opcodes::OP_MUL,   Opcodes::OP_DIV,
49
        Opcodes::OP_MOD,    Opcodes::OP_LSHIFT, Opcodes::OP_RSHIFT
50
    ];
51
52
    /**
53
     * @param EcAdapterInterface $ecAdapter
54
     */
55 138
    public function __construct(EcAdapterInterface $ecAdapter = null)
56
    {
57 138
        $ecAdapter = $ecAdapter ?: Bitcoin::getEcAdapter();
58 138
        $this->math = $ecAdapter->getMath();
59 138
        $this->vchFalse = new Buffer("", 0, $this->math);
60 138
        $this->vchTrue = new Buffer("\x01", 1, $this->math);
61 138
    }
62
63
    /**
64
     * Cast the value to a boolean
65
     *
66
     * @param BufferInterface $value
67
     * @return bool
68
     */
69 1692
    public function castToBool(BufferInterface $value)
70
    {
71 1692
        $val = $value->getBinary();
72 1692
        for ($i = 0, $size = strlen($val); $i < $size; $i++) {
73 1550
            $chr = ord($val[$i]);
74 1550
            if ($chr != 0) {
75 1544
                if (($i == ($size - 1)) && $chr == 0x80) {
76
                    return false;
77
                }
78 1544
                return true;
79
            }
80 2
        }
81 404
        return false;
82
    }
83
84
    /**
85
     * @param BufferInterface $signature
86
     * @return bool
87
     */
88
    public function isValidSignatureEncoding(BufferInterface $signature)
89
    {
90
        try {
91
            TransactionSignature::isDERSignature($signature);
92
            return true;
93
        } catch (SignatureNotCanonical $e) {
94
            /* In any case, we will return false outside this block */
95
        }
96
97
        return false;
98
    }
99
100
    /**
101
     * @param int $opCode
102
     * @param BufferInterface $pushData
103
     * @return bool
104
     * @throws \Exception
105
     */
106 236
    public function checkMinimalPush($opCode, BufferInterface $pushData)
107
    {
108 236
        $pushSize = $pushData->getSize();
109 236
        $binary = $pushData->getBinary();
110
111 236
        if ($pushSize === 0) {
112 114
            return $opCode === Opcodes::OP_0;
113 194
        } elseif ($pushSize === 1) {
114 50
            $first = ord($binary[0]);
115
116 50
            if ($first >= 1 && $first <= 16) {
117 38
                return $opCode === (Opcodes::OP_1 + ($first - 1));
118 18
            } elseif ($first === 0x81) {
119 18
                return $opCode === Opcodes::OP_1NEGATE;
120
            }
121 150
        } elseif ($pushSize <= 75) {
122 146
            return $opCode === $pushSize;
123 10
        } elseif ($pushSize <= 255) {
124 8
            return $opCode === Opcodes::OP_PUSHDATA1;
125 8
        } elseif ($pushSize <= 65535) {
126 8
            return $opCode === Opcodes::OP_PUSHDATA2;
127
        }
128
129 16
        return true;
130
    }
131
132
    /**
133
     * @param int $count
134
     * @return $this
135
     */
136 2246
    private function checkOpcodeCount($count)
137
    {
138 2246
        if ($count > 201) {
139 10
            throw new \RuntimeException('Error: Script op code count');
140
        }
141
142 2246
        return $this;
143
    }
144
145
    /**
146
     * @param WitnessProgram $witnessProgram
147
     * @param ScriptWitnessInterface $scriptWitness
148
     * @param int $flags
149
     * @param Checker $checker
150
     * @return bool
151
     */
152 53
    private function verifyWitnessProgram(WitnessProgram $witnessProgram, ScriptWitnessInterface $scriptWitness, $flags, Checker $checker)
153
    {
154 53
        $witnessCount = count($scriptWitness);
155
156 53
        if ($witnessProgram->getVersion() == 0) {
157 51
            $buffer = $witnessProgram->getProgram();
158 51
            if ($buffer->getSize() === 32) {
159
                // Version 0 segregated witness program: SHA256(Script) in program, Script + inputs in witness
160 29
                if ($witnessCount === 0) {
161
                    // Must contain script at least
162 2
                    return false;
163
                }
164
165 27
                $scriptPubKey = new Script($scriptWitness[$witnessCount - 1]);
166 27
                $stackValues = $scriptWitness->slice(0, -1);
167 27
                $hashScriptPubKey = Hash::sha256($scriptPubKey->getBuffer());
168
169 27
                if (!$hashScriptPubKey->equals($buffer)) {
0 ignored issues
show
Documentation introduced by
$buffer is of type object<BitWasp\Buffertools\BufferInterface>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
170 24
                    return false;
171
                }
172 25
            } elseif ($buffer->getSize() === 20) {
173
                // Version 0 special case for pay-to-pubkeyhash
174 20
                if ($witnessCount !== 2) {
175
                    // 2 items in witness - <signature> <pubkey>
176 2
                    return false;
177
                }
178
179 18
                $scriptPubKey = ScriptFactory::scriptPubKey()->payToPubKeyHash($buffer);
180 18
                $stackValues = $scriptWitness;
181 2
            } else {
182 38
                return false;
183
            }
184 7
        } elseif ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
185 2
            return false;
186
        } else {
187
            return false;
188
        }
189
190 41
        $mainStack = new Stack();
191 41
        foreach ($stackValues as $value) {
192 39
            $mainStack->push($value);
193 5
        }
194
195 41
        if (!$this->evaluate($scriptPubKey, $mainStack, SigHash::V1, $flags, $checker)) {
196
            return false;
197
        }
198
199 41
        if ($mainStack->count() !== 1) {
200
            return false;
201
        }
202
203 41
        if (!$this->castToBool($mainStack->bottom())) {
204 18
            return false;
205
        }
206
207 23
        return true;
208
    }
209
210
    /**
211
     * @param ScriptInterface $scriptSig
212
     * @param ScriptInterface $scriptPubKey
213
     * @param int $flags
214
     * @param Checker $checker
215
     * @param ScriptWitnessInterface|null $witness
216
     * @return bool
217
     */
218 2374
    public function verify(ScriptInterface $scriptSig, ScriptInterface $scriptPubKey, $flags, Checker $checker, ScriptWitnessInterface $witness = null)
219
    {
220 2374
        static $emptyWitness = null;
221 2374
        if ($emptyWitness === null) {
222 6
            $emptyWitness = new ScriptWitness([]);
223 2
        }
224
225 2374
        $witness = is_null($witness) ? $emptyWitness : $witness;
226
227 2374
        if (($flags & self::VERIFY_SIGPUSHONLY) != 0 && !$scriptSig->isPushOnly()) {
228 4
            return false;
229
        }
230
231 2370
        $stack = new Stack();
232 2370
        if (!$this->evaluate($scriptSig, $stack, SigHash::V0, $flags, $checker)) {
233 116
            return false;
234
        }
235
236 2254
        $backup = [];
237 2254
        if ($flags & self::VERIFY_P2SH) {
238 1579
            foreach ($stack as $s) {
239 1278
                $backup[] = $s;
240 21
            }
241 21
        }
242
243 2254
        if (!$this->evaluate($scriptPubKey, $stack, SigHash::V0, $flags, $checker)) {
244 762
            return false;
245
        }
246
247 1492
        if ($stack->isEmpty()) {
248 26
            return false;
249
        }
250
251 1466
        if (false === $this->castToBool($stack[-1])) {
252 106
            return false;
253
        }
254
255 1360
        $program = null;
256 1360
        if ($flags & self::VERIFY_WITNESS) {
257 89
            if ($scriptPubKey->isWitness($program)) {
258
                /** @var WitnessProgram $program */
259 37
                if ($scriptSig->getBuffer()->getSize() !== 0) {
260 2
                    return false;
261
                }
262
263 35
                if (!$this->verifyWitnessProgram($program, $witness, $flags, $checker)) {
264 22
                    return false;
265
                }
266
267 13
                $stack->resize(1);
268 3
            }
269 15
        }
270
271 1336
        if ($flags & self::VERIFY_P2SH && (new OutputClassifier())->isPayToScriptHash($scriptPubKey)) {
272 77
            if (!$scriptSig->isPushOnly()) {
273 12
                return false;
274
            }
275
276 65
            $stack = new Stack();
277 65
            foreach ($backup as $i) {
278 65
                $stack->push($i);
279 7
            }
280
281
            // Restore mainStack to how it was after evaluating scriptSig
282 65
            if ($stack->isEmpty()) {
283
                return false;
284
            }
285
286
            // Load redeemscript as the scriptPubKey
287 65
            $scriptPubKey = new Script($stack->bottom());
288 65
            $stack->pop();
289
290 65
            if (!$this->evaluate($scriptPubKey, $stack, 0, $flags, $checker)) {
291 14
                return false;
292
            }
293
294 51
            if ($stack->isEmpty()) {
295
                return false;
296
            }
297
298 51
            if (!$this->castToBool($stack->bottom())) {
299 2
                return false;
300
            }
301
302 49
            if ($flags & self::VERIFY_WITNESS) {
303 29
                if ($scriptPubKey->isWitness($program)) {
304
                    /** @var WitnessProgram $program */
305 20
                    if (!$scriptSig->equals(ScriptFactory::sequence([$scriptPubKey->getBuffer()]))) {
306 2
                        return false; // SCRIPT_ERR_WITNESS_MALLEATED_P2SH
307
                    }
308
309 18
                    if (!$this->verifyWitnessProgram($program, $witness, $flags, $checker)) {
310 8
                        return false;
311
                    }
312
313 10
                    $stack->resize(1);
314 2
                }
315 5
            }
316 5
        }
317
318 1298
        if ($flags & self::VERIFY_CLEAN_STACK) {
319 24
            if (!($flags & self::VERIFY_P2SH != 0) && ($flags & self::VERIFY_WITNESS != 0)) {
320
                return false; // implied flags required
321
            }
322
323 24
            if (count($stack) != 1) {
324 4
                return false; // Cleanstack
325
            }
326 6
        }
327
328 1294
        if ($flags & self::VERIFY_WITNESS) {
329 55
            if (!$flags & self::VERIFY_P2SH) {
330
                return false; //
331
            }
332
333 55
            if ($program === null && !$witness->isNull()) {
334 2
                return false; // SCRIPT_ERR_WITNESS_UNEXPECTED
335
            }
336 15
        }
337
338 1292
        return true;
339
    }
340
341
    /**
342
     * @param Stack $vfStack
343
     * @param bool $value
344
     * @return bool
345
     */
346 2374
    private function checkExec(Stack $vfStack, $value)
347
    {
348 2374
        $ret = 0;
349 2374
        foreach ($vfStack as $item) {
350 484
            if ($item == $value) {
351 484
                $ret++;
352
            }
353 90
        }
354
355 2374
        return $ret;
356
    }
357
358
    /**
359
     * @param ScriptInterface $script
360
     * @param Stack $mainStack
361
     * @param int $sigVersion
362
     * @param int $flags
363
     * @param Checker $checker
364
     * @return bool
365
     */
366 2400
    public function evaluate(ScriptInterface $script, Stack $mainStack, $sigVersion, $flags, Checker $checker)
367
    {
368 2400
        $hashStartPos = 0;
369 2400
        $opCount = 0;
370 2400
        $altStack = new Stack();
371 2400
        $vfStack = new Stack();
372 2400
        $minimal = ($flags & self::VERIFY_MINIMALDATA) != 0;
373 2400
        $parser = $script->getScriptParser();
374
375 2400
        if ($script->getBuffer()->getSize() > 10000) {
376 2
            return false;
377
        }
378
379
        try {
380 2400
            foreach ($parser as $operation) {
381 2374
                $opCode = $operation->getOp();
382 2374
                $pushData = $operation->getData();
383 2374
                $fExec = !$this->checkExec($vfStack, false);
384
385
                // If pushdata was written to
386 2374
                if ($operation->isPush() && $operation->getDataSize() > InterpreterInterface::MAX_SCRIPT_ELEMENT_SIZE) {
387 10
                    throw new \RuntimeException('Error - push size');
388
                }
389
390
                // OP_RESERVED should not count towards opCount
391 2368
                if ($opCode > Opcodes::OP_16 && ++$opCount) {
392 2246
                    $this->checkOpcodeCount($opCount);
393 86
                }
394
395 2368
                if (in_array($opCode, $this->disabledOps, true)) {
396 48
                    throw new \RuntimeException('Disabled Opcode');
397
                }
398
399 2368
                if ($fExec && $operation->isPush()) {
400
                    // In range of a pushdata opcode
401 1768
                    if ($minimal && !$this->checkMinimalPush($opCode, $pushData)) {
402 42
                        throw new ScriptRuntimeException(self::VERIFY_MINIMALDATA, 'Minimal pushdata required');
403
                    }
404
405 1726
                    $mainStack->push($pushData);
406
                    // echo " - [pushed '" . $pushData->getHex() . "']\n";
407 2294
                } elseif ($fExec || (Opcodes::OP_IF <= $opCode && $opCode <= Opcodes::OP_ENDIF)) {
408
                    // echo "OPCODE - " . $script->getOpcodes()->getOp($opCode) . "\n";
409
                    switch ($opCode) {
410 2292
                        case Opcodes::OP_1NEGATE:
411 2292
                        case Opcodes::OP_1:
412 2248
                        case Opcodes::OP_2:
413 2240
                        case Opcodes::OP_3:
414 2240
                        case Opcodes::OP_4:
415 2240
                        case Opcodes::OP_5:
416 2240
                        case Opcodes::OP_6:
417 2240
                        case Opcodes::OP_7:
418 2238
                        case Opcodes::OP_8:
419 2238
                        case Opcodes::OP_9:
420 2238
                        case Opcodes::OP_10:
421 2238
                        case Opcodes::OP_11:
422 2236
                        case Opcodes::OP_12:
423 2236
                        case Opcodes::OP_13:
424 2236
                        case Opcodes::OP_14:
425 2236
                        case Opcodes::OP_15:
426 2236
                        case Opcodes::OP_16:
427 1374
                            $num = \BitWasp\Bitcoin\Script\decodeOpN($opCode);
428 1374
                            $mainStack->push(Number::int($num)->getBuffer());
429 1374
                            break;
430
431 2236
                        case Opcodes::OP_CHECKLOCKTIMEVERIFY:
432 12
                            if (!($flags & self::VERIFY_CHECKLOCKTIMEVERIFY)) {
433 12
                                if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
434 2
                                    throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
435
                                }
436 10
                                break;
437
                            }
438
439
                            if ($mainStack->isEmpty()) {
440
                                throw new \RuntimeException('Invalid stack operation - CLTV');
441
                            }
442
443
                            $lockTime = Number::buffer($mainStack[-1], $minimal, 5, $this->math);
444
                            if (!$checker->checkLockTime($lockTime)) {
445
                                throw new ScriptRuntimeException(self::VERIFY_CHECKLOCKTIMEVERIFY, 'Unsatisfied locktime');
446
                            }
447
448
                            break;
449
450 2234
                        case Opcodes::OP_CHECKSEQUENCEVERIFY:
451 24
                            if (!($flags & self::VERIFY_CHECKSEQUENCEVERIFY)) {
452 12
                                if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
453 2
                                    throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
454
                                }
455 10
                                break;
456
                            }
457
458 12
                            if ($mainStack->isEmpty()) {
459 2
                                throw new \RuntimeException('Invalid stack operation - CSV');
460
                            }
461
462 10
                            $sequence = Number::buffer($mainStack[-1], $minimal, 5, $this->math);
463 8
                            $nSequence = $sequence->getGmp();
464 8
                            if ($this->math->cmp($nSequence, gmp_init(0)) < 0) {
465 2
                                throw new ScriptRuntimeException(self::VERIFY_CHECKSEQUENCEVERIFY, 'Negative locktime');
466
                            }
467
468 6
                            if ($this->math->cmp($this->math->bitwiseAnd($nSequence, gmp_init(TransactionInputInterface::SEQUENCE_LOCKTIME_DISABLE_FLAG, 10)), gmp_init(0)) !== 0) {
469 2
                                break;
470
                            }
471
472 4
                            if (!$checker->checkSequence($sequence)) {
473 4
                                throw new ScriptRuntimeException(self::VERIFY_CHECKSEQUENCEVERIFY, 'Unsatisfied sequence');
474
                            }
475
                            break;
476
477 2220
                        case Opcodes::OP_NOP1:
478 2218
                        case Opcodes::OP_NOP4:
479 2216
                        case Opcodes::OP_NOP5:
480 2214
                        case Opcodes::OP_NOP6:
481 2212
                        case Opcodes::OP_NOP7:
482 2210
                        case Opcodes::OP_NOP8:
483 2208
                        case Opcodes::OP_NOP9:
484 2206
                        case Opcodes::OP_NOP10:
485 54
                            if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
486 20
                                throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
487
                            }
488 34
                            break;
489
490 2200
                        case Opcodes::OP_NOP:
491 168
                            break;
492
493 2154
                        case Opcodes::OP_IF:
494 2110
                        case Opcodes::OP_NOTIF:
495
                            // <expression> if [statements] [else [statements]] endif
496 494
                            $value = false;
497 494
                            if ($fExec) {
498 494
                                if ($mainStack->isEmpty()) {
499 4
                                    throw new \RuntimeException('Unbalanced conditional');
500
                                }
501
502 490
                                $buffer = Number::buffer($mainStack->pop(), $minimal)->getBuffer();
503 490
                                $value = $this->castToBool($buffer);
504 490
                                if ($opCode === Opcodes::OP_NOTIF) {
505 34
                                    $value = !$value;
506
                                }
507
                            }
508 490
                            $vfStack->push($value);
509 490
                            break;
510
511 2106
                        case Opcodes::OP_ELSE:
512 230
                            if ($vfStack->isEmpty()) {
513 8
                                throw new \RuntimeException('Unbalanced conditional');
514
                            }
515 226
                            $vfStack->push(!$vfStack->pop());
516 226
                            break;
517
518 2100
                        case Opcodes::OP_ENDIF:
519 294
                            if ($vfStack->isEmpty()) {
520 14
                                throw new \RuntimeException('Unbalanced conditional');
521
                            }
522 286
                            $vfStack->pop();
523 286
                            break;
524
525 1828
                        case Opcodes::OP_VERIFY:
526 60
                            if ($mainStack->isEmpty()) {
527 2
                                throw new \RuntimeException('Invalid stack operation');
528
                            }
529 58
                            $value = $this->castToBool($mainStack[-1]);
530 58
                            if (!$value) {
531 2
                                throw new \RuntimeException('Error: verify');
532
                            }
533 56
                            $mainStack->pop();
534 56
                            break;
535
536 1814
                        case Opcodes::OP_TOALTSTACK:
537 16
                            if ($mainStack->isEmpty()) {
538 2
                                throw new \RuntimeException('Invalid stack operation OP_TOALTSTACK');
539
                            }
540 14
                            $altStack->push($mainStack->pop());
541 14
                            break;
542
543 1810
                        case Opcodes::OP_FROMALTSTACK:
544 10
                            if ($altStack->isEmpty()) {
545 4
                                throw new \RuntimeException('Invalid alt-stack operation OP_FROMALTSTACK');
546
                            }
547 6
                            $mainStack->push($altStack->pop());
548 6
                            break;
549
550 1804
                        case Opcodes::OP_IFDUP:
551
                            // If top value not zero, duplicate it.
552 12
                            if ($mainStack->isEmpty()) {
553 4
                                throw new \RuntimeException('Invalid stack operation OP_IFDUP');
554
                            }
555 8
                            $vch = $mainStack[-1];
556 8
                            if ($this->castToBool($vch)) {
557 6
                                $mainStack->push($vch);
558
                            }
559 8
                            break;
560
561 1798
                        case Opcodes::OP_DEPTH:
562 156
                            $num = count($mainStack);
563 156
                            $depth = Number::int($num)->getBuffer();
564 156
                            $mainStack->push($depth);
565 156
                            break;
566
567 1780
                        case Opcodes::OP_DROP:
568 96
                            if ($mainStack->isEmpty()) {
569 4
                                throw new \RuntimeException('Invalid stack operation OP_DROP');
570
                            }
571 92
                            $mainStack->pop();
572 92
                            break;
573
574 1774
                        case Opcodes::OP_DUP:
575 86
                            if ($mainStack->isEmpty()) {
576 4
                                throw new \RuntimeException('Invalid stack operation OP_DUP');
577
                            }
578 82
                            $vch = $mainStack[-1];
579 82
                            $mainStack->push($vch);
580 82
                            break;
581
582 1756
                        case Opcodes::OP_NIP:
583 12
                            if (count($mainStack) < 2) {
584 6
                                throw new \RuntimeException('Invalid stack operation OP_NIP');
585
                            }
586 6
                            unset($mainStack[-2]);
587 6
                            break;
588
589 1744
                        case Opcodes::OP_OVER:
590 12
                            if (count($mainStack) < 2) {
591 6
                                throw new \RuntimeException('Invalid stack operation OP_OVER');
592
                            }
593 6
                            $vch = $mainStack[-2];
594 6
                            $mainStack->push($vch);
595 6
                            break;
596
597 1736
                        case Opcodes::OP_ROT:
598 24
                            if (count($mainStack) < 3) {
599 8
                                throw new \RuntimeException('Invalid stack operation OP_ROT');
600
                            }
601 16
                            $mainStack->swap(-3, -2);
602 16
                            $mainStack->swap(-2, -1);
603 16
                            break;
604
605 1724
                        case Opcodes::OP_SWAP:
606 20
                            if (count($mainStack) < 2) {
607 6
                                throw new \RuntimeException('Invalid stack operation OP_SWAP');
608
                            }
609 14
                            $mainStack->swap(-2, -1);
610 14
                            break;
611
612 1716
                        case Opcodes::OP_TUCK:
613 12
                            if (count($mainStack) < 2) {
614 6
                                throw new \RuntimeException('Invalid stack operation OP_TUCK');
615
                            }
616 6
                            $vch = $mainStack[-1];
617 6
                            $mainStack->add(- 2, $vch);
618 6
                            break;
619
620 1708
                        case Opcodes::OP_PICK:
621 1690
                        case Opcodes::OP_ROLL:
622 58
                            if (count($mainStack) < 2) {
623 8
                                throw new \RuntimeException('Invalid stack operation OP_PICK');
624
                            }
625
626 50
                            $n = Number::buffer($mainStack[-1], $minimal, 4)->getGmp();
627 46
                            $mainStack->pop();
628 46
                            if ($this->math->cmp($n, gmp_init(0)) < 0 || $this->math->cmp($n, gmp_init(count($mainStack))) >= 0) {
629 10
                                throw new \RuntimeException('Invalid stack operation OP_PICK');
630
                            }
631
632 36
                            $pos = (int) gmp_strval($this->math->sub($this->math->sub(gmp_init(0), $n), gmp_init(1)), 10);
633 36
                            $vch = $mainStack[$pos];
634 36
                            if ($opCode === Opcodes::OP_ROLL) {
635 18
                                unset($mainStack[$pos]);
636
                            }
637 36
                            $mainStack->push($vch);
638 36
                            break;
639
640 1674
                        case Opcodes::OP_2DROP:
641 18
                            if (count($mainStack) < 2) {
642 2
                                throw new \RuntimeException('Invalid stack operation OP_2DROP');
643
                            }
644 16
                            $mainStack->pop();
645 16
                            $mainStack->pop();
646 16
                            break;
647
648 1670
                        case Opcodes::OP_2DUP:
649 12
                            if (count($mainStack) < 2) {
650 6
                                throw new \RuntimeException('Invalid stack operation OP_2DUP');
651
                            }
652 6
                            $string1 = $mainStack[-2];
653 6
                            $string2 = $mainStack[-1];
654 6
                            $mainStack->push($string1);
655 6
                            $mainStack->push($string2);
656 6
                            break;
657
658 1662
                        case Opcodes::OP_3DUP:
659 22
                            if (count($mainStack) < 3) {
660 8
                                throw new \RuntimeException('Invalid stack operation OP_3DUP');
661
                            }
662 14
                            $string1 = $mainStack[-3];
663 14
                            $string2 = $mainStack[-2];
664 14
                            $string3 = $mainStack[-1];
665 14
                            $mainStack->push($string1);
666 14
                            $mainStack->push($string2);
667 14
                            $mainStack->push($string3);
668 14
                            break;
669
670 1642
                        case Opcodes::OP_2OVER:
671 10
                            if (count($mainStack) < 4) {
672 6
                                throw new \RuntimeException('Invalid stack operation OP_2OVER');
673
                            }
674 4
                            $string1 = $mainStack[-4];
675 4
                            $string2 = $mainStack[-3];
676 4
                            $mainStack->push($string1);
677 4
                            $mainStack->push($string2);
678 4
                            break;
679
680 1634
                        case Opcodes::OP_2ROT:
681 20
                            if (count($mainStack) < 6) {
682 2
                                throw new \RuntimeException('Invalid stack operation OP_2ROT');
683
                            }
684 18
                            $string1 = $mainStack[-6];
685 18
                            $string2 = $mainStack[-5];
686 18
                            unset($mainStack[-6], $mainStack[-5]);
687 18
                            $mainStack->push($string1);
688 18
                            $mainStack->push($string2);
689 18
                            break;
690
691 1630
                        case Opcodes::OP_2SWAP:
692 10
                            if (count($mainStack) < 4) {
693 6
                                throw new \RuntimeException('Invalid stack operation OP_2SWAP');
694
                            }
695 4
                            $mainStack->swap(-3, -1);
696 4
                            $mainStack->swap(-4, -2);
697 4
                            break;
698
699 1622
                        case Opcodes::OP_SIZE:
700 62
                            if ($mainStack->isEmpty()) {
701 4
                                throw new \RuntimeException('Invalid stack operation OP_SIZE');
702
                            }
703 58
                            $size = Number::int($mainStack[-1]->getSize());
704 58
                            $mainStack->push($size->getBuffer());
705 58
                            break;
706
707 1616
                        case Opcodes::OP_EQUAL:
708 1394
                        case Opcodes::OP_EQUALVERIFY:
709 616
                            if (count($mainStack) < 2) {
710 8
                                throw new \RuntimeException('Invalid stack operation OP_EQUAL');
711
                            }
712
713 608
                            $equal = $mainStack[-2]->equals($mainStack[-1]);
714 608
                            $mainStack->pop();
715 608
                            $mainStack->pop();
716 608
                            $mainStack->push($equal ? $this->vchTrue : $this->vchFalse);
717 608
                            if ($opCode === Opcodes::OP_EQUALVERIFY) {
718 120
                                if ($equal) {
719 102
                                    $mainStack->pop();
720 10
                                } else {
721 18
                                    throw new \RuntimeException('Error EQUALVERIFY');
722
                                }
723 10
                            }
724
725 592
                            break;
726
727
                        // Arithmetic operations
728 1332
                        case $opCode >= Opcodes::OP_1ADD && $opCode <= Opcodes::OP_0NOTEQUAL:
729 216
                            if ($mainStack->isEmpty()) {
730 12
                                throw new \Exception('Invalid stack operation 1ADD-OP_0NOTEQUAL');
731
                            }
732
733 204
                            $num = Number::buffer($mainStack[-1], $minimal)->getGmp();
734
735 158
                            if ($opCode === Opcodes::OP_1ADD) {
736 14
                                $num = $this->math->add($num, gmp_init(1));
737 144
                            } elseif ($opCode === Opcodes::OP_1SUB) {
738 6
                                $num = $this->math->sub($num, gmp_init(1));
739 138
                            } elseif ($opCode === Opcodes::OP_2MUL) {
740
                                $num = $this->math->mul(gmp_init(2), $num);
741 138
                            } elseif ($opCode === Opcodes::OP_NEGATE) {
742 8
                                $num = $this->math->sub(gmp_init(0), $num);
743 132
                            } elseif ($opCode === Opcodes::OP_ABS) {
744 10
                                if ($this->math->cmp($num, gmp_init(0)) < 0) {
745 10
                                    $num = $this->math->sub(gmp_init(0), $num);
746
                                }
747 122
                            } elseif ($opCode === Opcodes::OP_NOT) {
748 110
                                $num = gmp_init($this->math->cmp($num, gmp_init(0)) == 0 ? 1 : 0);
749 4
                            } else {
750
                                // is OP_0NOTEQUAL
751 12
                                $num = gmp_init($this->math->cmp($num, gmp_init(0)) != 0 ? 1 : 0);
752
                            }
753
754 158
                            $mainStack->pop();
755
756 158
                            $buffer = Number::int(gmp_strval($num, 10))->getBuffer();
757
758 158
                            $mainStack->push($buffer);
759 158
                            break;
760
761 1214
                        case $opCode >= Opcodes::OP_ADD && $opCode <= Opcodes::OP_MAX:
762 328
                            if (count($mainStack) < 2) {
763 26
                                throw new \Exception('Invalid stack operation (OP_ADD - OP_MAX)');
764
                            }
765
766 302
                            $num1 = Number::buffer($mainStack[-2], $minimal)->getGmp();
767 268
                            $num2 = Number::buffer($mainStack[-1], $minimal)->getGmp();
768
769 242
                            if ($opCode === Opcodes::OP_ADD) {
770 60
                                $num = $this->math->add($num1, $num2);
771 194
                            } else if ($opCode === Opcodes::OP_SUB) {
772 12
                                $num = $this->math->sub($num1, $num2);
773 182
                            } else if ($opCode === Opcodes::OP_BOOLAND) {
774 16
                                $num = $this->math->cmp($num1, gmp_init(0)) !== 0 && $this->math->cmp($num2, gmp_init(0)) !== 0;
775 166
                            } else if ($opCode === Opcodes::OP_BOOLOR) {
776 16
                                $num = $this->math->cmp($num1, gmp_init(0)) !== 0 || $this->math->cmp($num2, gmp_init(0)) !== 0;
777 150
                            } elseif ($opCode === Opcodes::OP_NUMEQUAL) {
778 56
                                $num = $this->math->cmp($num1, $num2) === 0;
779 110
                            } elseif ($opCode === Opcodes::OP_NUMEQUALVERIFY) {
780 8
                                $num = $this->math->cmp($num1, $num2) === 0;
781 102
                            } elseif ($opCode === Opcodes::OP_NUMNOTEQUAL) {
782 10
                                $num = $this->math->cmp($num1, $num2) !== 0;
783 92
                            } elseif ($opCode === Opcodes::OP_LESSTHAN) {
784 16
                                $num = $this->math->cmp($num1, $num2) < 0;
785 76
                            } elseif ($opCode === Opcodes::OP_GREATERTHAN) {
786 16
                                $num = $this->math->cmp($num1, $num2) > 0;
787 60
                            } elseif ($opCode === Opcodes::OP_LESSTHANOREQUAL) {
788 16
                                $num = $this->math->cmp($num1, $num2) <= 0;
789 44
                            } elseif ($opCode === Opcodes::OP_GREATERTHANOREQUAL) {
790 16
                                $num = $this->math->cmp($num1, $num2) >= 0;
791 28
                            } elseif ($opCode === Opcodes::OP_MIN) {
792 14
                                $num = ($this->math->cmp($num1, $num2) <= 0) ? $num1 : $num2;
793
                            } else {
794 14
                                $num = ($this->math->cmp($num1, $num2) >= 0) ? $num1 : $num2;
795
                            }
796
797 242
                            $mainStack->pop();
798 242
                            $mainStack->pop();
799 242
                            $buffer = Number::int(gmp_strval($num, 10))->getBuffer();
800 242
                            $mainStack->push($buffer);
801
802 242
                            if ($opCode === Opcodes::OP_NUMEQUALVERIFY) {
803 8
                                if ($this->castToBool($mainStack[-1])) {
804 8
                                    $mainStack->pop();
805
                                } else {
806
                                    throw new \RuntimeException('NUM EQUAL VERIFY error');
807
                                }
808
                            }
809 242
                            break;
810
811 886
                        case Opcodes::OP_WITHIN:
812 30
                            if (count($mainStack) < 3) {
813 2
                                throw new \RuntimeException('Invalid stack operation');
814
                            }
815
816 28
                            $num1 = Number::buffer($mainStack[-3], $minimal)->getGmp();
817 26
                            $num2 = Number::buffer($mainStack[-2], $minimal)->getGmp();
818 24
                            $num3 = Number::buffer($mainStack[-1], $minimal)->getGmp();
819
820 22
                            $value = $this->math->cmp($num2, $num1) <= 0 && $this->math->cmp($num1, $num3) < 0;
821 22
                            $mainStack->pop();
822 22
                            $mainStack->pop();
823 22
                            $mainStack->pop();
824 22
                            $mainStack->push($value ? $this->vchTrue : $this->vchFalse);
825 22
                            break;
826
827
                        // Hash operation
828 856
                        case Opcodes::OP_RIPEMD160:
829 844
                        case Opcodes::OP_SHA1:
830 828
                        case Opcodes::OP_SHA256:
831 816
                        case Opcodes::OP_HASH160:
832 766
                        case Opcodes::OP_HASH256:
833 200
                            if ($mainStack->isEmpty()) {
834 26
                                throw new \RuntimeException('Invalid stack operation');
835
                            }
836
837 174
                            $buffer = $mainStack[-1];
838 174
                            if ($opCode === Opcodes::OP_RIPEMD160) {
839 10
                                $hash = Hash::ripemd160($buffer);
840 166
                            } elseif ($opCode === Opcodes::OP_SHA1) {
841 12
                                $hash = Hash::sha1($buffer);
842 154
                            } elseif ($opCode === Opcodes::OP_SHA256) {
843 12
                                $hash = Hash::sha256($buffer);
844 146
                            } elseif ($opCode === Opcodes::OP_HASH160) {
845 136
                                $hash = Hash::sha256ripe160($buffer);
846 20
                            } else {
847 10
                                $hash = Hash::sha256d($buffer);
848
                            }
849
850 174
                            $mainStack->pop();
851 174
                            $mainStack->push($hash);
852 174
                            break;
853
854 748
                        case Opcodes::OP_CODESEPARATOR:
855 2
                            $hashStartPos = $parser->getPosition();
856 2
                            break;
857
858 746
                        case Opcodes::OP_CHECKSIG:
859 516
                        case Opcodes::OP_CHECKSIGVERIFY:
860 284
                            if (count($mainStack) < 2) {
861 4
                                throw new \RuntimeException('Invalid stack operation');
862
                            }
863
864 280
                            $vchPubKey = $mainStack[-1];
865 280
                            $vchSig = $mainStack[-2];
866
867 280
                            $scriptCode = new Script($script->getBuffer()->slice($hashStartPos));
868
869 280
                            $success = $checker->checkSig($scriptCode, $vchSig, $vchPubKey, $sigVersion, $flags);
870
871 160
                            $mainStack->pop();
872 160
                            $mainStack->pop();
873 160
                            $mainStack->push($success ? $this->vchTrue : $this->vchFalse);
874
875 160
                            if ($opCode === Opcodes::OP_CHECKSIGVERIFY) {
876
                                if ($success) {
877
                                    $mainStack->pop();
878
                                } else {
879
                                    throw new \RuntimeException('Checksig verify');
880
                                }
881
                            }
882 160
                            break;
883
884 462
                        case Opcodes::OP_CHECKMULTISIG:
885 286
                        case Opcodes::OP_CHECKMULTISIGVERIFY:
886 262
                            $i = 1;
887 262
                            if (count($mainStack) < $i) {
888 2
                                throw new \RuntimeException('Invalid stack operation');
889
                            }
890
891 260
                            $keyCount = Number::buffer($mainStack[-$i], $minimal)->getInt();
892 256
                            if ($keyCount < 0 || $keyCount > 20) {
893 4
                                throw new \RuntimeException('OP_CHECKMULTISIG: Public key count exceeds 20');
894
                            }
895
896 252
                            $opCount += $keyCount;
897 252
                            $this->checkOpcodeCount($opCount);
898
899
                            // Extract positions of the keys, and signatures, from the stack.
900 252
                            $ikey = ++$i;
901 252
                            $i += $keyCount; /** @var int $i */
902 252
                            if (count($mainStack) < $i) {
903 2
                                throw new \RuntimeException('Invalid stack operation');
904
                            }
905
906 250
                            $sigCount = Number::buffer($mainStack[-$i], $minimal)->getInt();
907 244
                            if ($sigCount < 0 || $sigCount > $keyCount) {
908 4
                                throw new \RuntimeException('Invalid Signature count');
909
                            }
910
911 240
                            $isig = ++$i;
912 240
                            $i += $sigCount;
913
914
                            // Extract the script since the last OP_CODESEPARATOR
915 240
                            $scriptCode = new Script($script->getBuffer()->slice($hashStartPos));
916
917 240
                            $fSuccess = true;
918 240
                            while ($fSuccess && $sigCount > 0) {
919
                                // Fetch the signature and public key
920 120
                                $sig = $mainStack[-$isig];
921 118
                                $pubkey = $mainStack[-$ikey];
922
923 118
                                if ($checker->checkSig($scriptCode, $sig, $pubkey, $sigVersion, $flags)) {
924 66
                                    $isig++;
925 66
                                    $sigCount--;
926 14
                                }
927
928 98
                                $ikey++;
929 98
                                $keyCount--;
930
931
                                // If there are more signatures left than keys left,
932
                                // then too many signatures have failed. Exit early,
933
                                // without checking any further signatures.
934 98
                                if ($sigCount > $keyCount) {
935 36
                                    $fSuccess = false;
936 4
                                }
937 18
                            }
938
939 206
                            while ($i-- > 1) {
940 206
                                $mainStack->pop();
941 14
                            }
942
943
                            // A bug causes CHECKMULTISIG to consume one extra argument
944
                            // whose contents were not checked in any way.
945
                            //
946
                            // Unfortunately this is a potential source of mutability,
947
                            // so optionally verify it is exactly equal to zero prior
948
                            // to removing it from the stack.
949 206
                            if ($mainStack->isEmpty()) {
950 2
                                throw new \RuntimeException('Invalid stack operation');
951
                            }
952
953 206
                            if ($flags & self::VERIFY_NULL_DUMMY && $mainStack[-1]->getSize() !== 0) {
954 4
                                throw new ScriptRuntimeException(self::VERIFY_NULL_DUMMY, 'Extra P2SH stack value should be OP_0');
955
                            }
956
957 202
                            $mainStack->pop();
958 202
                            $mainStack->push($fSuccess ? $this->vchTrue : $this->vchFalse);
959
960 202
                            if ($opCode === Opcodes::OP_CHECKMULTISIGVERIFY) {
961 60
                                if ($fSuccess) {
962 60
                                    $mainStack->pop();
963
                                } else {
964
                                    throw new \RuntimeException('OP_CHECKMULTISIG verify');
965
                                }
966
                            }
967 202
                            break;
968
969 6
                        default:
970 200
                            throw new \RuntimeException('Opcode not found');
971 6
                    }
972
973 2010
                    if (count($mainStack) + count($altStack) > 1000) {
974 2212
                        throw new \RuntimeException('Invalid stack size, exceeds 1000');
975
                    }
976 48
                }
977 94
            }
978
979 2294
            if (count($vfStack) !== 0) {
980 12
                throw new \RuntimeException('Unbalanced conditional at script end');
981
            }
982
983 2284
            return true;
984 896
        } catch (ScriptRuntimeException $e) {
985
            // echo "\n Runtime: " . $e->getMessage() . "\n" . $e->getTraceAsString() . PHP_EOL;
986
            // Failure due to script tags, can access flag: $e->getFailureFlag()
987 228
            return false;
988 668
        } catch (\Exception $e) {
989
            // echo "\n General: " . $e->getMessage()  . PHP_EOL . $e->getTraceAsString() . PHP_EOL;
990 668
            return false;
991
        }
992
    }
993
}
994