Completed
Pull Request — master (#591)
by thomas
22:54 queued 09:12
created

PrivateKeySerializer::fromParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Serializer\Key;
6
7
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Adapter\EcAdapter;
8
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Key\PrivateKey;
9
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface;
10
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Key\PrivateKeySerializerInterface;
11
use BitWasp\Buffertools\Buffer;
12
use BitWasp\Buffertools\BufferInterface;
13
use BitWasp\Buffertools\Parser;
14
15
/**
16
 * Private Key Serializer - specific to secp256k1
17
 */
18
class PrivateKeySerializer implements PrivateKeySerializerInterface
19
{
20
    /**
21
     * @var EcAdapter
22
     */
23
    private $ecAdapter;
24
25
    /**
26
     * @param EcAdapter $ecAdapter
27
     */
28 105
    public function __construct(EcAdapter $ecAdapter)
29
    {
30 105
        $this->ecAdapter = $ecAdapter;
31 105
    }
32
33
    /**
34
     * @param PrivateKey $privateKey
35
     * @return BufferInterface
36
     */
37 90
    private function doSerialize(PrivateKey $privateKey): BufferInterface
38
    {
39 90
        return new Buffer($privateKey->getSecretBinary(), 32);
40
    }
41
42
    /**
43
     * @param PrivateKeyInterface $privateKey
44
     * @return BufferInterface
45
     */
46 90
    public function serialize(PrivateKeyInterface $privateKey): BufferInterface
47
    {
48
        /** @var PrivateKey $privateKey */
49 90
        return $this->doSerialize($privateKey);
50
    }
51
52
    /**
53
     * @param Parser $parser
54
     * @return PrivateKeyInterface
55
     * @throws \Exception
56
     */
57 59
    public function fromParser(Parser $parser): PrivateKeyInterface
58
    {
59 59
        return $this->ecAdapter->getPrivateKey($parser->readBytes(32)->getGmp());
60
    }
61
62
    /**
63
     * @param BufferInterface $data
64
     * @return PrivateKeyInterface
65
     * @throws \Exception
66
     */
67 59
    public function parse(BufferInterface $data): PrivateKeyInterface
68
    {
69 59
        return $this->fromParser(new Parser($data));
70
    }
71
}
72