Completed
Pull Request — master (#476)
by thomas
23:29
created

WitnessScript::getWitnessProgram()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
1
<?php
2
3
namespace BitWasp\Bitcoin\Script;
4
5
use BitWasp\Bitcoin\Exceptions\WitnessScriptException;
6
7
class WitnessScript extends Script
8
{
9
10
    /**
11
     * @var ScriptInterface
12
     */
13
    private $outputScript;
14
15
    /**
16
     * @var WitnessProgram|null
17
     */
18
    private $witnessProgram;
19
20
    /**
21
     * WitnessScript constructor.
22
     * @param ScriptInterface $script
23
     * @param Opcodes|null $opcodes
24
     * @throws WitnessScriptException
25
     */
26 8
    public function __construct(ScriptInterface $script, Opcodes $opcodes = null)
27
    {
28 8
        if ($script instanceof self) {
29 2
            throw new WitnessScriptException("Cannot nest V0 P2WSH scripts.");
30 6
        } else if ($script instanceof P2shScript) {
31 2
            throw new WitnessScriptException("Cannot embed a P2SH script in a V2 P2WSH script.");
32
        }
33
34 4
        parent::__construct($script->getBuffer(), $opcodes);
35
36 4
        $this->witnessScriptHash = $script->getWitnessScriptHash();
37 4
        $this->outputScript = ScriptFactory::scriptPubKey()->p2wsh($this->witnessScriptHash);
38 4
    }
39
40
    /**
41
     * @return WitnessProgram
42
     */
43 6
    public function getWitnessProgram()
44
    {
45 6
        if (null === $this->witnessProgram) {
46 4
            $this->witnessProgram = WitnessProgram::v0($this->witnessScriptHash);
0 ignored issues
show
Bug introduced by
It seems like $this->witnessScriptHash can be null; however, v0() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
47
        }
48
49 6
        return $this->witnessProgram;
50
    }
51
52
    /**
53
     * @return ScriptInterface
54
     */
55 6
    public function getOutputScript()
56
    {
57 6
        return $this->getWitnessProgram()->getScript();
58
    }
59
}
60