Completed
Pull Request — master (#285)
by thomas
21:56
created

Multisig::classification()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace BitWasp\Bitcoin\Script\ScriptInfo;
4
5
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
6
use BitWasp\Bitcoin\Key\PublicKeyFactory;
7
use BitWasp\Bitcoin\Script\Classifier\OutputClassifier;
8
use BitWasp\Bitcoin\Script\ScriptInterface;
9
10
class Multisig implements ScriptInfoInterface
11
{
12
    /**
13
     * @var int
14
     */
15
    private $m;
16
17
    /**
18
     * @var int
19
     */
20
    private $n;
21
22
    /**
23
     * @var PublicKeyInterface[]
24
     */
25
    private $keys = [];
26
27
    /**
28
     * @param ScriptInterface $script
29
     */
30 36
    public function __construct(ScriptInterface $script)
31
    {
32 36
        $publicKeys = [];
33 36
        $parse = $script->getScriptParser()->decode();
34 36
        if (count($parse) < 4) {
35
            throw new \InvalidArgumentException('Malformed multisig script');
36
        }
37
38 36
        $mCode = $parse[0]->getOp();
39 36
        $nCode = $parse[count($parse) - 2]->getOp();
40
41 36
        $this->m = (int) \BitWasp\Bitcoin\Script\decodeOpN($mCode);
42 36
        foreach (array_slice($parse, 1, -2) as $key) {
43
            /** @var \BitWasp\Bitcoin\Script\Parser\Operation $key */
44 36
            if (!$key->isPush()) {
45
                throw new \RuntimeException('Malformed multisig script');
46
            }
47
48 36
            $publicKeys[] = PublicKeyFactory::fromHex($key->getData());
49 36
        }
50
51 36
        $n = \BitWasp\Bitcoin\Script\decodeOpN($nCode);
52 36
        $this->n = count($publicKeys);
53 36
        if ($this->n === 0 || $this->n !== $n) {
54
            throw new \LogicException('No public keys found in script');
55
        }
56
57 36
        $this->keys = $publicKeys;
58 36
    }
59
60
    /**
61
     * @return int
62
     */
63 24
    public function getRequiredSigCount()
64
    {
65 24
        return $this->m;
66
    }
67
68
    /**
69
     * @return int
70
     */
71 30
    public function getKeyCount()
72
    {
73 30
        return $this->n;
74
    }
75
76
    /**
77
     * @param PublicKeyInterface $publicKey
78
     * @return bool
79
     */
80
    public function checkInvolvesKey(PublicKeyInterface $publicKey)
81
    {
82
        $binary = $publicKey->getBinary();
83
        foreach ($this->keys as $key) {
84
            if ($key->getBinary() === $binary) {
85
                return true;
86
            }
87
        }
88
89
        return false;
90
    }
91
92
    /**
93
     * @return \BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface[]
94
     */
95 36
    public function getKeys()
96
    {
97 36
        return $this->keys;
98
    }
99
}
100