Completed
Pull Request — master (#335)
by thomas
04:22
created

Interpreter::checkMinimalPush()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9

Importance

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