Completed
Pull Request — master (#359)
by Ruben de
14:27
created

Interpreter::checkExec()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

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