Completed
Pull Request — master (#99)
by thomas
42:14 queued 39:21
created

BitcoinAddressReader::fromString()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.0466

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 6
nop 2
dl 0
loc 13
ccs 6
cts 7
cp 0.8571
crap 4.0466
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Blocktrail\SDK\Address;
4
5
use BitWasp\Bitcoin\Address\AddressInterface;
6
use BitWasp\Bitcoin\Address\Base58AddressInterface;
7
use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
8
use BitWasp\Bitcoin\Address\ScriptHashAddress;
9
use BitWasp\Bitcoin\Address\SegwitAddress;
10
use BitWasp\Bitcoin\Bitcoin;
11
use BitWasp\Bitcoin\Network\NetworkInterface;
12
use BitWasp\Bitcoin\Script\Classifier\OutputClassifier;
13
use BitWasp\Bitcoin\Script\ScriptInterface;
14
use BitWasp\Bitcoin\Script\ScriptType;
15
use BitWasp\Bitcoin\Script\WitnessProgram;
16
use BitWasp\Buffertools\BufferInterface;
17
use Blocktrail\SDK\Exceptions\BlocktrailSDKException;
18
19
class BitcoinAddressReader extends AddressReaderBase
20
{
21
    /**
22
     * @param ScriptInterface $outputScript
23
     * @return AddressInterface|PayToPubKeyHashAddress|ScriptHashAddress|SegwitAddress
24
     */
25 15
    public function fromOutputScript(ScriptInterface $outputScript) {
26 15
        $wp = null;
27 15
        if ($outputScript->isWitness($wp)) {
28
            /** @var WitnessProgram $wp */
29
            return new SegwitAddress($wp);
30
        }
31
32 15
        $decode = (new OutputClassifier())->decode($outputScript);
33 15
        switch ($decode->getType()) {
34 15
            case ScriptType::P2PKH:
35
                /** @var BufferInterface $solution */
36
                return new PayToPubKeyHashAddress($decode->getSolution());
37 15
            case ScriptType::P2SH:
38
                /** @var BufferInterface $solution */
39 15
                return new ScriptHashAddress($decode->getSolution());
40
            default:
41
                throw new \RuntimeException('Script type is not associated with an address');
42
        }
43
    }
44
45
    /**
46
     * @param string $strAddress
47
     * @param NetworkInterface|null $network
48
     * @return Base58AddressInterface|SegwitAddress|null
49
     * @throws BlocktrailSDKException
50
     */
51 30
    public function fromString($strAddress, NetworkInterface $network = null) {
52 30
        $network = $network ?: Bitcoin::getNetwork();
53
54 30
        if (($base58Address = $this->readBase58($strAddress, $network))) {
55 20
            return $base58Address;
56
        }
57
58 11
        if (($bech32Address = $this->readBech32($strAddress, $network))) {
59 11
            return $bech32Address;
60
        }
61
62
        throw new BlocktrailSDKException("Address not recognized");
63
    }
64
}
65