Completed
Pull Request — master (#336)
by thomas
04:08
created

Interpreter::verify()   F

Complexity

Conditions 35
Paths 1176

Size

Total Lines 122
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 61
CRAP Score 40.443

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 35
eloc 62
c 2
b 1
f 0
nc 1176
nop 5
dl 0
loc 122
ccs 61
cts 73
cp 0.8356
crap 40.443
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
                return false; // implied flags required
318
            }
319
320
            if (count($stack) != 1) {
321 36
                return false; // Cleanstack
322
            }
323
        }
324 24
325
        if ($flags & self::VERIFY_WITNESS) {
326 234
            if (!$flags & self::VERIFY_P2SH) {
327 36
                return false; //
328
            }
329
330
            if ($program === null && !$witness->isNull()) {
331 36
                return false; // SCRIPT_ERR_WITNESS_UNEXPECTED
332
            }
333
        }
334 24
335
        return true;
336 234
    }
337
338
    /**
339
     * @param Stack $vfStack
340
     * @return bool
341
     */
342
    private function checkExec(Stack $vfStack, $value)
343 402
    {
344
        $ret = 0;
345 402
        foreach ($vfStack as $item) {
346 402
            if ($item == $value) {
347 402
                $ret++;
348
            }
349
        }
350
351
        return $ret;
352
    }
353 402
354
    /**
355
     * @param ScriptInterface $script
356
     * @param Stack $mainStack
357
     * @param int $sigVersion
358
     * @param int $flags
359
     * @param Checker $checker
360
     * @return bool
361
     */
362
    public function evaluate(ScriptInterface $script, Stack $mainStack, $sigVersion, $flags, Checker $checker)
363
    {
364 405
        $hashStartPos = 0;
365
        $opCount = 0;
366 405
        $altStack = new Stack();
367 405
        $vfStack = new Stack();
368 405
        $minimal = ($flags & self::VERIFY_MINIMALDATA) != 0;
369 405
        $parser = $script->getScriptParser();
370 405
371 405
        if ($script->getBuffer()->getSize() > 10000) {
372
            return false;
373 405
        }
374
375
        try {
376
            foreach ($parser as $operation) {
377
                $opCode = $operation->getOp();
378 405
                $pushData = $operation->getData();
379 402
                $fExec = !$this->checkExec($vfStack, false);
380 402
381 402
                // If pushdata was written to
382
                if ($operation->isPush() && $operation->getDataSize() > InterpreterInterface::MAX_SCRIPT_ELEMENT_SIZE) {
383
                    throw new \RuntimeException('Error - push size');
384 402
                }
385 3
386
                // OP_RESERVED should not count towards opCount
387
                if ($opCode > Opcodes::OP_16 && ++$opCount) {
388
                    $this->checkOpcodeCount($opCount);
389 399
                }
390 387
391 258
                if (in_array($opCode, $this->disabledOps, true)) {
392
                    throw new \RuntimeException('Disabled Opcode');
393 399
                }
394 6
395
                if ($fExec && $operation->isPush()) {
396
                    // In range of a pushdata opcode
397 399
                    if ($minimal && !$this->checkMinimalPush($opCode, $pushData)) {
398
                        throw new ScriptRuntimeException(self::VERIFY_MINIMALDATA, 'Minimal pushdata required');
399 252
                    }
400 3
401
                    $mainStack->push($pushData);
402
                    // echo " - [pushed '" . $pushData->getHex() . "']\n";
403 249
                } elseif ($fExec || (Opcodes::OP_IF <= $opCode && $opCode <= Opcodes::OP_ENDIF)) {
404
                    // echo "OPCODE - " . $script->getOpcodes()->getOp($opCode) . "\n";
405 392
                    switch ($opCode) {
406
                        case Opcodes::OP_1NEGATE:
407
                        case Opcodes::OP_1:
408 384
                        case Opcodes::OP_2:
409 384
                        case Opcodes::OP_3:
410 384
                        case Opcodes::OP_4:
411 384
                        case Opcodes::OP_5:
412 384
                        case Opcodes::OP_6:
413 384
                        case Opcodes::OP_7:
414 384
                        case Opcodes::OP_8:
415 384
                        case Opcodes::OP_9:
416 384
                        case Opcodes::OP_10:
417 384
                        case Opcodes::OP_11:
418 384
                        case Opcodes::OP_12:
419 384
                        case Opcodes::OP_13:
420 384
                        case Opcodes::OP_14:
421 384
                        case Opcodes::OP_15:
422 384
                        case Opcodes::OP_16:
423 384
                            $num = \BitWasp\Bitcoin\Script\decodeOpN($opCode);
424 384
                            $mainStack->push(Number::int($num)->getBuffer());
425 120
                            break;
426 120
427 120
                        case Opcodes::OP_CHECKLOCKTIMEVERIFY:
428
                            if (!($flags & self::VERIFY_CHECKLOCKTIMEVERIFY)) {
429 384
                                if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
430
                                    throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
431
                                }
432
                                break;
433
                            }
434
435
                            if ($mainStack->isEmpty()) {
436
                                throw new \RuntimeException('Invalid stack operation - CLTV');
437
                            }
438
439
                            $lockTime = Number::buffer($mainStack[-1], $minimal, 5, $this->math);
440
                            if (!$checker->checkLockTime($lockTime)) {
441
                                throw new ScriptRuntimeException(self::VERIFY_CHECKLOCKTIMEVERIFY, 'Unsatisfied locktime');
442
                            }
443
444
                            break;
445
446
                        case Opcodes::OP_CHECKSEQUENCEVERIFY:
447
                            if (!($flags & self::VERIFY_CHECKSEQUENCEVERIFY)) {
448 384
                                if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
449
                                    throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
450
                                }
451
                                break;
452
                            }
453
454
                            if ($mainStack->isEmpty()) {
455
                                throw new \RuntimeException('Invalid stack operation - CSV');
456
                            }
457
458
                            $sequence = Number::buffer($mainStack[-1], $minimal, 5, $this->math);
459
                            $nSequence = $sequence->getGmp();
460
                            if ($this->math->cmp($nSequence, gmp_init(0)) < 0) {
461
                                throw new ScriptRuntimeException(self::VERIFY_CHECKSEQUENCEVERIFY, 'Negative locktime');
462
                            }
463
464
                            if ($this->math->cmp($this->math->bitwiseAnd($nSequence, gmp_init(TransactionInputInterface::SEQUENCE_LOCKTIME_DISABLE_FLAG, 10)), gmp_init(0)) !== 0) {
465
                                break;
466
                            }
467
468
                            if (!$checker->checkSequence($sequence)) {
469
                                throw new ScriptRuntimeException(self::VERIFY_CHECKSEQUENCEVERIFY, 'Unsatisfied sequence');
470
                            }
471
                            break;
472
473
                        case Opcodes::OP_NOP1:
474
                        case Opcodes::OP_NOP4:
475 384
                        case Opcodes::OP_NOP5:
476 383
                        case Opcodes::OP_NOP6:
477 383
                        case Opcodes::OP_NOP7:
478 383
                        case Opcodes::OP_NOP8:
479 383
                        case Opcodes::OP_NOP9:
480 383
                        case Opcodes::OP_NOP10:
481 383
                            if ($flags & self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
482 383
                                throw new ScriptRuntimeException(self::VERIFY_DISCOURAGE_UPGRADABLE_NOPS, 'Upgradable NOP found - this is discouraged');
483 3
                            }
484 3
                            break;
485
486
                        case Opcodes::OP_NOP:
487
                            break;
488 381
489 6
                        case Opcodes::OP_IF:
490
                        case Opcodes::OP_NOTIF:
491 375
                            // <expression> if [statements] [else [statements]] endif
492 374
                            $value = false;
493
                            if ($fExec) {
494 3
                                if ($mainStack->isEmpty()) {
495 3
                                    throw new \RuntimeException('Unbalanced conditional');
496 3
                                }
497 3
498
                                $buffer = Number::buffer($mainStack->pop(), $minimal)->getBuffer();
499
                                $value = $this->castToBool($buffer);
500
                                if ($opCode === Opcodes::OP_NOTIF) {
501
                                    $value = !$value;
502
                                }
503
                            }
504
                            $vfStack->push($value);
505
                            break;
506
507
                        case Opcodes::OP_ELSE:
508
                            if ($vfStack->isEmpty()) {
509
                                throw new \RuntimeException('Unbalanced conditional');
510 372
                            }
511 3
                            $vfStack->push(!$vfStack->pop());
512 3
                            break;
513
514
                        case Opcodes::OP_ENDIF:
515
                            if ($vfStack->isEmpty()) {
516
                                throw new \RuntimeException('Unbalanced conditional');
517 369
                            }
518 3
                            $vfStack->pop();
519 3
                            break;
520
521
                        case Opcodes::OP_VERIFY:
522
                            if ($mainStack->isEmpty()) {
523 366
                                throw new \RuntimeException('Invalid stack operation');
524 12
                            }
525 3
                            $value = $this->castToBool($mainStack[-1]);
526
                            if (!$value) {
527 9
                                throw new \RuntimeException('Error: verify');
528 9
                            }
529 3
                            $mainStack->pop();
530
                            break;
531 6
532 6
                        case Opcodes::OP_TOALTSTACK:
533
                            if ($mainStack->isEmpty()) {
534 354
                                throw new \RuntimeException('Invalid stack operation OP_TOALTSTACK');
535 9
                            }
536 3
                            $altStack->push($mainStack->pop());
537
                            break;
538 6
539 6
                        case Opcodes::OP_FROMALTSTACK:
540
                            if ($altStack->isEmpty()) {
541 351
                                throw new \RuntimeException('Invalid alt-stack operation OP_FROMALTSTACK');
542 6
                            }
543 3
                            $mainStack->push($altStack->pop());
544
                            break;
545 3
546 3
                        case Opcodes::OP_IFDUP:
547
                            // If top value not zero, duplicate it.
548 348
                            if ($mainStack->isEmpty()) {
549
                                throw new \RuntimeException('Invalid stack operation OP_IFDUP');
550 6
                            }
551 3
                            $vch = $mainStack[-1];
552
                            if ($this->castToBool($vch)) {
553 3
                                $mainStack->push($vch);
554 3
                            }
555 3
                            break;
556 2
557 3
                        case Opcodes::OP_DEPTH:
558
                            $num = count($mainStack);
559 345
                            $depth = Number::int($num)->getBuffer();
560 42
                            $mainStack->push($depth);
561 42
                            break;
562 42
563 42
                        case Opcodes::OP_DROP:
564
                            if ($mainStack->isEmpty()) {
565 342
                                throw new \RuntimeException('Invalid stack operation OP_DROP');
566 3
                            }
567 3
                            $mainStack->pop();
568
                            break;
569
570
                        case Opcodes::OP_DUP:
571
                            if ($mainStack->isEmpty()) {
572 339
                                throw new \RuntimeException('Invalid stack operation OP_DUP');
573 21
                            }
574 3
                            $vch = $mainStack[-1];
575
                            $mainStack->push($vch);
576 18
                            break;
577 18
578 18
                        case Opcodes::OP_NIP:
579
                            if (count($mainStack) < 2) {
580 336
                                throw new \RuntimeException('Invalid stack operation OP_NIP');
581 9
                            }
582 3
                            unset($mainStack[-2]);
583
                            break;
584 6
585 6
                        case Opcodes::OP_OVER:
586
                            if (count($mainStack) < 2) {
587 333
                                throw new \RuntimeException('Invalid stack operation OP_OVER');
588 9
                            }
589 3
                            $vch = $mainStack[-2];
590
                            $mainStack->push($vch);
591 6
                            break;
592 6
593 6
                        case Opcodes::OP_ROT:
594
                            if (count($mainStack) < 3) {
595 330
                                throw new \RuntimeException('Invalid stack operation OP_ROT');
596 6
                            }
597 3
                            $mainStack->swap(-3, -2);
598
                            $mainStack->swap(-2, -1);
599 3
                            break;
600 3
601 3
                        case Opcodes::OP_SWAP:
602
                            if (count($mainStack) < 2) {
603 327
                                throw new \RuntimeException('Invalid stack operation OP_SWAP');
604 6
                            }
605 3
                            $mainStack->swap(-2, -1);
606
                            break;
607 3
608 3
                        case Opcodes::OP_TUCK:
609
                            if (count($mainStack) < 2) {
610 324
                                throw new \RuntimeException('Invalid stack operation OP_TUCK');
611 6
                            }
612 3
                            $vch = $mainStack[-1];
613
                            $mainStack->add(- 2, $vch);
614 3
                            break;
615 3
616
                        case Opcodes::OP_PICK:
617
                        case Opcodes::OP_ROLL:
618 318
                            if (count($mainStack) < 2) {
619 316
                                throw new \RuntimeException('Invalid stack operation OP_PICK');
620 12
                            }
621 3
622
                            $n = Number::buffer($mainStack[-1], $minimal, 4)->getGmp();
623
                            $mainStack->pop();
624 9
                            if ($this->math->cmp($n, gmp_init(0)) < 0 || $this->math->cmp($n, gmp_init(count($mainStack))) >= 0) {
625 9
                                throw new \RuntimeException('Invalid stack operation OP_PICK');
626 9
                            }
627 3
628
                            $pos = (int) gmp_strval($this->math->sub($this->math->sub(gmp_init(0), $n), gmp_init(1)), 10);
629
                            $vch = $mainStack[$pos];
630 6
                            if ($opCode === Opcodes::OP_ROLL) {
631 6
                                unset($mainStack[$pos]);
632 6
                            }
633 3
                            $mainStack->push($vch);
634 2
                            break;
635 6
636 6
                        case Opcodes::OP_2DROP:
637
                            if (count($mainStack) < 2) {
638 312
                                throw new \RuntimeException('Invalid stack operation OP_2DROP');
639 6
                            }
640 3
                            $mainStack->pop();
641
                            $mainStack->pop();
642 3
                            break;
643 3
644 3
                        case Opcodes::OP_2DUP:
645
                            if (count($mainStack) < 2) {
646 309
                                throw new \RuntimeException('Invalid stack operation OP_2DUP');
647 9
                            }
648 3
                            $string1 = $mainStack[-2];
649
                            $string2 = $mainStack[-1];
650 6
                            $mainStack->push($string1);
651 6
                            $mainStack->push($string2);
652 6
                            break;
653 6
654 6
                        case Opcodes::OP_3DUP:
655
                            if (count($mainStack) < 3) {
656 306
                                throw new \RuntimeException('Invalid stack operation OP_3DUP');
657 9
                            }
658 3
                            $string1 = $mainStack[-3];
659
                            $string2 = $mainStack[-2];
660 6
                            $string3 = $mainStack[-1];
661 6
                            $mainStack->push($string1);
662 6
                            $mainStack->push($string2);
663 6
                            $mainStack->push($string3);
664 6
                            break;
665 6
666 6
                        case Opcodes::OP_2OVER:
667
                            if (count($mainStack) < 4) {
668 303
                                throw new \RuntimeException('Invalid stack operation OP_2OVER');
669 9
                            }
670 3
                            $string1 = $mainStack[-4];
671
                            $string2 = $mainStack[-3];
672 6
                            $mainStack->push($string1);
673 6
                            $mainStack->push($string2);
674 6
                            break;
675 6
676 6
                        case Opcodes::OP_2ROT:
677
                            if (count($mainStack) < 6) {
678 300
                                throw new \RuntimeException('Invalid stack operation OP_2ROT');
679 6
                            }
680 3
                            $string1 = $mainStack[-6];
681
                            $string2 = $mainStack[-5];
682 3
                            unset($mainStack[-6], $mainStack[-5]);
683 3
                            $mainStack->push($string1);
684 3
                            $mainStack->push($string2);
685 3
                            break;
686 3
687 3
                        case Opcodes::OP_2SWAP:
688
                            if (count($mainStack) < 4) {
689 297
                                throw new \RuntimeException('Invalid stack operation OP_2SWAP');
690 6
                            }
691 3
                            $mainStack->swap(-3, -1);
692
                            $mainStack->swap(-4, -2);
693 3
                            break;
694 3
695 3
                        case Opcodes::OP_SIZE:
696
                            if ($mainStack->isEmpty()) {
697 294
                                throw new \RuntimeException('Invalid stack operation OP_SIZE');
698 6
                            }
699 3
                            $size = Number::int($mainStack[-1]->getSize());
700
                            $mainStack->push($size->getBuffer());
701 3
                            break;
702 3
703 3
                        case Opcodes::OP_EQUAL:
704
                        case Opcodes::OP_EQUALVERIFY:
705 291
                            if (count($mainStack) < 2) {
706 277
                                throw new \RuntimeException('Invalid stack operation OP_EQUAL');
707 222
                            }
708 3
709
                            $equal = $mainStack[-2]->equals($mainStack[-1]);
710
                            $mainStack->pop();
711 219
                            $mainStack->pop();
712 219
                            $mainStack->push($equal ? $this->vchTrue : $this->vchFalse);
713 219
                            if ($opCode === Opcodes::OP_EQUALVERIFY) {
714 219
                                if ($equal) {
715 219
                                    $mainStack->pop();
716 69
                                } else {
717 63
                                    throw new \RuntimeException('Error EQUALVERIFY');
718 42
                                }
719 6
                            }
720
721 42
                            break;
722
723 213
                        // Arithmetic operations
724
                        case $opCode >= Opcodes::OP_1ADD && $opCode <= Opcodes::OP_0NOTEQUAL:
725
                            if ($mainStack->isEmpty()) {
726 198
                                throw new \Exception('Invalid stack operation 1ADD-OP_0NOTEQUAL');
727 24
                            }
728 3
729
                            $num = Number::buffer($mainStack[-1], $minimal)->getGmp();
730
731 21
                            if ($opCode === Opcodes::OP_1ADD) {
732
                                $num = $this->math->add($num, gmp_init(1));
733 21
                            } elseif ($opCode === Opcodes::OP_1SUB) {
734 3
                                $num = $this->math->sub($num, gmp_init(1));
735 20
                            } elseif ($opCode === Opcodes::OP_2MUL) {
736 3
                                $num = $this->math->mul(gmp_init(2), $num);
737 17
                            } elseif ($opCode === Opcodes::OP_NEGATE) {
738
                                $num = $this->math->sub(gmp_init(0), $num);
739 15
                            } elseif ($opCode === Opcodes::OP_ABS) {
740
                                if ($this->math->cmp($num, gmp_init(0)) < 0) {
741 15
                                    $num = $this->math->sub(gmp_init(0), $num);
742
                                }
743
                            } elseif ($opCode === Opcodes::OP_NOT) {
744
                                $num = gmp_init($this->math->cmp($num, gmp_init(0)) == 0 ? 1 : 0);
745 15
                            } else {
746 9
                                // is OP_0NOTEQUAL
747 6
                                $num = gmp_init($this->math->cmp($num, gmp_init(0)) != 0 ? 1 : 0);
748
                            }
749 6
750
                            $mainStack->pop();
751
752 21
                            $buffer = Number::int(gmp_strval($num, 10))->getBuffer();
753
754 21
                            $mainStack->push($buffer);
755
                            break;
756 21
757 21
                        case $opCode >= Opcodes::OP_ADD && $opCode <= Opcodes::OP_MAX:
758
                            if (count($mainStack) < 2) {
759 174
                                throw new \Exception('Invalid stack operation (OP_ADD - OP_MAX)');
760 75
                            }
761 12
762
                            $num1 = Number::buffer($mainStack[-2], $minimal)->getGmp();
763
                            $num2 = Number::buffer($mainStack[-1], $minimal)->getGmp();
764 63
765 63
                            if ($opCode === Opcodes::OP_ADD) {
766
                                $num = $this->math->add($num1, $num2);
767 63
                            } else if ($opCode === Opcodes::OP_SUB) {
768 3
                                $num = $this->math->sub($num1, $num2);
769 62
                            } else if ($opCode === Opcodes::OP_BOOLAND) {
770 3
                                $num = $this->math->cmp($num1, gmp_init(0)) !== 0 && $this->math->cmp($num2, gmp_init(0)) !== 0;
771 59
                            } else if ($opCode === Opcodes::OP_BOOLOR) {
772 6
                                $num = $this->math->cmp($num1, gmp_init(0)) !== 0 || $this->math->cmp($num2, gmp_init(0)) !== 0;
773 55
                            } elseif ($opCode === Opcodes::OP_NUMEQUAL) {
774 9
                                $num = $this->math->cmp($num1, $num2) === 0;
775 48
                            } elseif ($opCode === Opcodes::OP_NUMEQUALVERIFY) {
776 9
                                $num = $this->math->cmp($num1, $num2) === 0;
777 39
                            } elseif ($opCode === Opcodes::OP_NUMNOTEQUAL) {
778
                                $num = $this->math->cmp($num1, $num2) !== 0;
779 33
                            } elseif ($opCode === Opcodes::OP_LESSTHAN) {
780 3
                                $num = $this->math->cmp($num1, $num2) < 0;
781 32
                            } elseif ($opCode === Opcodes::OP_GREATERTHAN) {
782 6
                                $num = $this->math->cmp($num1, $num2) > 0;
783 28
                            } elseif ($opCode === Opcodes::OP_LESSTHANOREQUAL) {
784 6
                                $num = $this->math->cmp($num1, $num2) <= 0;
785 22
                            } elseif ($opCode === Opcodes::OP_GREATERTHANOREQUAL) {
786 6
                                $num = $this->math->cmp($num1, $num2) >= 0;
787 16
                            } elseif ($opCode === Opcodes::OP_MIN) {
788 6
                                $num = ($this->math->cmp($num1, $num2) <= 0) ? $num1 : $num2;
789 10
                            } else {
790 3
                                $num = ($this->math->cmp($num1, $num2) >= 0) ? $num1 : $num2;
791 2
                            }
792 3
793
                            $mainStack->pop();
794
                            $mainStack->pop();
795 63
                            $buffer = Number::int(gmp_strval($num, 10))->getBuffer();
796 63
                            $mainStack->push($buffer);
797 63
798 63
                            if ($opCode === Opcodes::OP_NUMEQUALVERIFY) {
799
                                if ($this->castToBool($mainStack[-1])) {
800 63
                                    $mainStack->pop();
801
                                } else {
802
                                    throw new \RuntimeException('NUM EQUAL VERIFY error');
803
                                }
804
                            }
805
                            break;
806
807 63
                        case Opcodes::OP_WITHIN:
808
                            if (count($mainStack) < 3) {
809 99
                                throw new \RuntimeException('Invalid stack operation');
810 6
                            }
811 3
812
                            $num1 = Number::buffer($mainStack[-3], $minimal)->getGmp();
813
                            $num2 = Number::buffer($mainStack[-2], $minimal)->getGmp();
814 3
                            $num3 = Number::buffer($mainStack[-1], $minimal)->getGmp();
815 3
816 3
                            $value = $this->math->cmp($num2, $num1) <= 0 && $this->math->cmp($num1, $num3) < 0;
817
                            $mainStack->pop();
818 3
                            $mainStack->pop();
819 3
                            $mainStack->pop();
820 3
                            $mainStack->push($value ? $this->vchTrue : $this->vchFalse);
821 3
                            break;
822 3
823 3
                        // Hash operation
824
                        case Opcodes::OP_RIPEMD160:
825
                        case Opcodes::OP_SHA1:
826 93
                        case Opcodes::OP_SHA256:
827 91
                        case Opcodes::OP_HASH160:
828 90
                        case Opcodes::OP_HASH256:
829 89
                            if ($mainStack->isEmpty()) {
830 86
                                throw new \RuntimeException('Invalid stack operation');
831 51
                            }
832 6
833
                            $buffer = $mainStack[-1];
834
                            if ($opCode === Opcodes::OP_RIPEMD160) {
835 45
                                $hash = Hash::ripemd160($buffer);
836 45
                            } elseif ($opCode === Opcodes::OP_SHA1) {
837 3
                                $hash = Hash::sha1($buffer);
838 44
                            } elseif ($opCode === Opcodes::OP_SHA256) {
839 3
                                $hash = Hash::sha256($buffer);
840 41
                            } elseif ($opCode === Opcodes::OP_HASH160) {
841 3
                                $hash = Hash::sha256ripe160($buffer);
842 38
                            } else {
843 33
                                $hash = Hash::sha256d($buffer);
844 22
                            }
845 3
846
                            $mainStack->pop();
847
                            $mainStack->push($hash);
848 45
                            break;
849 45
850 45
                        case Opcodes::OP_CODESEPARATOR:
851
                            $hashStartPos = $parser->getPosition();
852 69
                            break;
853
854
                        case Opcodes::OP_CHECKSIG:
855
                        case Opcodes::OP_CHECKSIGVERIFY:
856 69
                            if (count($mainStack) < 2) {
857 60
                                throw new \RuntimeException('Invalid stack operation');
858 27
                            }
859 3
860
                            $vchPubKey = $mainStack[-1];
861
                            $vchSig = $mainStack[-2];
862 24
863 24
                            $scriptCode = new Script($script->getBuffer()->slice($hashStartPos));
864
865 24
                            $success = $checker->checkSig($scriptCode, $vchSig, $vchPubKey, $sigVersion, $flags);
866
867 24
                            $mainStack->pop();
868
                            $mainStack->pop();
869 21
                            $mainStack->push($success ? $this->vchTrue : $this->vchFalse);
870 21
871 21
                            if ($opCode === Opcodes::OP_CHECKSIGVERIFY) {
872
                                if ($success) {
873 21
                                    $mainStack->pop();
874
                                } else {
875
                                    throw new \RuntimeException('Checksig verify');
876
                                }
877
                            }
878
                            break;
879
880 21
                        case Opcodes::OP_CHECKMULTISIG:
881
                        case Opcodes::OP_CHECKMULTISIGVERIFY:
882 42
                            $i = 1;
883 37
                            if (count($mainStack) < $i) {
884 15
                                throw new \RuntimeException('Invalid stack operation');
885 15
                            }
886
887
                            $keyCount = Number::buffer($mainStack[-$i], $minimal)->getInt();
888
                            if ($keyCount < 0 || $keyCount > 20) {
889 15
                                throw new \RuntimeException('OP_CHECKMULTISIG: Public key count exceeds 20');
890 15
                            }
891
892
                            $opCount += $keyCount;
893
                            $this->checkOpcodeCount($opCount);
894 15
895 15
                            // Extract positions of the keys, and signatures, from the stack.
896
                            $ikey = ++$i;
897
                            $i += $keyCount; /** @var int $i */
898 15
                            if (count($mainStack) < $i) {
899 15
                                throw new \RuntimeException('Invalid stack operation');
900 15
                            }
901
902
                            $sigCount = Number::buffer($mainStack[-$i], $minimal)->getInt();
903
                            if ($sigCount < 0 || $sigCount > $keyCount) {
904 15
                                throw new \RuntimeException('Invalid Signature count');
905 15
                            }
906
907
                            $isig = ++$i;
908
                            $i += $sigCount;
909 15
910 15
                            // Extract the script since the last OP_CODESEPARATOR
911
                            $scriptCode = new Script($script->getBuffer()->slice($hashStartPos));
912
913 15
                            $fSuccess = true;
914
                            while ($fSuccess && $sigCount > 0) {
915 15
                                // Fetch the signature and public key
916 15
                                $sig = $mainStack[-$isig];
917
                                $pubkey = $mainStack[-$ikey];
918 15
919 15
                                if ($checker->checkSig($scriptCode, $sig, $pubkey, $sigVersion, $flags)) {
920
                                    $isig++;
921 15
                                    $sigCount--;
922 15
                                }
923 15
924 10
                                $ikey++;
925
                                $keyCount--;
926 15
927 15
                                // If there are more signatures left than keys left,
928
                                // then too many signatures have failed. Exit early,
929
                                // without checking any further signatures.
930
                                if ($sigCount > $keyCount) {
931
                                    $fSuccess = false;
932 15
                                }
933
                            }
934
935 10
                            while ($i-- > 1) {
936
                                $mainStack->pop();
937 15
                            }
938 15
939 10
                            // A bug causes CHECKMULTISIG to consume one extra argument
940
                            // whose contents were not checked in any way.
941
                            //
942
                            // Unfortunately this is a potential source of mutability,
943
                            // so optionally verify it is exactly equal to zero prior
944
                            // to removing it from the stack.
945
                            if ($mainStack->isEmpty()) {
946
                                throw new \RuntimeException('Invalid stack operation');
947 15
                            }
948
949
                            if ($flags & self::VERIFY_NULL_DUMMY && $mainStack[-1]->getSize() !== 0) {
950
                                throw new ScriptRuntimeException(self::VERIFY_NULL_DUMMY, 'Extra P2SH stack value should be OP_0');
951 15
                            }
952
953
                            $mainStack->pop();
954
                            $mainStack->push($fSuccess ? $this->vchTrue : $this->vchFalse);
955 15
956 15
                            if ($opCode === Opcodes::OP_CHECKMULTISIGVERIFY) {
957
                                if ($fSuccess) {
958 15
                                    $mainStack->pop();
959
                                } else {
960
                                    throw new \RuntimeException('OP_CHECKMULTISIG verify');
961
                                }
962
                            }
963
                            break;
964
965 15
                        default:
966
                            throw new \RuntimeException('Opcode not found');
967 18
                    }
968 27
969 18
                    if (count($mainStack) + count($altStack) > 1000) {
970
                        throw new \RuntimeException('Invalid stack size, exceeds 1000');
971 252
                    }
972 101
                }
973
            }
974 168
975 268
            if (count($vfStack) !== 0) {
976
                throw new \RuntimeException('Unbalanced conditional at script end');
977 402
            }
978
979
            return true;
980
        } catch (ScriptRuntimeException $e) {
981 402
            // echo "\n Runtime: " . $e->getMessage() . "\n" . $e->getTraceAsString() . PHP_EOL;
982 159
            // Failure due to script tags, can access flag: $e->getFailureFlag()
983
            return false;
984
        } catch (\Exception $e) {
985 9
            // echo "\n General: " . $e->getMessage()  . PHP_EOL . $e->getTraceAsString() . PHP_EOL;
986 150
            return false;
987
        }
988 150
    }
989
}
990