Completed
Pull Request — master (#538)
by thomas
69:50
created

CheckLocktimeVerify::isLockedToBlock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace BitWasp\Bitcoin\Transaction\Factory\ScriptInfo;
4
5
use BitWasp\Bitcoin\Locktime;
6
use BitWasp\Bitcoin\Script\Interpreter\Number;
7
use BitWasp\Bitcoin\Script\Opcodes;
8
use BitWasp\Bitcoin\Script\Parser\Operation;
9
use BitWasp\Bitcoin\Script\ScriptInterface;
10
11
class CheckLocktimeVerify
12
{
13
    /**
14
     * @var int
15
     */
16
    private $nLockTime;
17
18
    /**
19
     * @var bool
20
     */
21
    private $toBlock;
22
23
    /**
24
     * CheckLocktimeVerify constructor.
25
     * @param int $nLockTime
26
     */
27
    public function __construct($nLockTime)
28
    {
29
        if ($nLockTime < 0) {
30
            throw new \RuntimeException("locktime cannot be negative");
31
        }
32
33
        if ($nLockTime > Locktime::INT_MAX) {
34
            throw new \RuntimeException("nLockTime exceeds maximum value");
35
        }
36
37
        $this->nLockTime = $nLockTime;
38
        $this->toBlock = (new Locktime())->isLockedToBlock($nLockTime);
39
    }
40
41
    /**
42
     * @param Operation[] $chunks
43
     * @param bool $fMinimal
44
     * @return static
45
     */
46
    public static function fromDecodedScript(array $chunks, $fMinimal = false)
47
    {
48
        if (count($chunks) !== 3) {
49
            throw new \RuntimeException("Invalid number of items for CLTV");
50
        }
51
52
        if (!$chunks[0]->isPush()) {
53
            throw new \InvalidArgumentException('CLTV script had invalid value for time');
54
        }
55
56
        if ($chunks[1]->getOp() !== Opcodes::OP_CHECKLOCKTIMEVERIFY) {
57
            throw new \InvalidArgumentException('CLTV script invalid opcode');
58
        }
59
60
        if ($chunks[2]->getOp() !== Opcodes::OP_DROP) {
61
            throw new \InvalidArgumentException('CLTV script invalid opcode');
62
        }
63
64
        $numLockTime = Number::buffer($chunks[0]->getData(), $fMinimal, 5);
65
66
        return new static($numLockTime->getInt());
67
    }
68
69
    /**
70
     * @param ScriptInterface $script
71
     * @return CheckLocktimeVerify
72
     */
73
    public static function fromScript(ScriptInterface $script)
74
    {
75
        return static::fromDecodedScript($script->getScriptParser()->decode());
76
    }
77
78
    /**
79
     * @return int
80
     */
81
    public function getLocktime()
82
    {
83
        return $this->nLockTime;
84
    }
85
86
    /**
87
     * @return bool
88
     */
89
    public function isLockedToBlock()
90
    {
91
        return $this->toBlock;
92
    }
93
}
94