Completed
Pull Request — master (#591)
by thomas
32:28 queued 30:02
created

PrivateKeySerializer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A doSerialize() 0 4 1
A serialize() 0 5 1
A fromParser() 0 4 1
A parse() 0 4 1
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 135
    public function __construct(EcAdapter $ecAdapter)
29
    {
30 135
        $this->ecAdapter = $ecAdapter;
31 135
    }
32
33
    /**
34
     * @param PrivateKey $privateKey
35
     * @return BufferInterface
36
     */
37 120
    private function doSerialize(PrivateKey $privateKey): BufferInterface
38
    {
39 120
        return new Buffer($privateKey->getSecretBinary(), 32, $this->ecAdapter->getMath());
40
    }
41
42
    /**
43
     * @param PrivateKeyInterface $privateKey
44
     * @return BufferInterface
45
     */
46 120
    public function serialize(PrivateKeyInterface $privateKey): BufferInterface
47
    {
48
        /** @var PrivateKey $privateKey */
49 120
        return $this->doSerialize($privateKey);
50
    }
51
52
    /**
53
     * @param Parser $parser
54
     * @return PrivateKeyInterface
55
     * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange
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 \BitWasp\Buffertools\BufferInterface|string $data
64
     * @return PrivateKeyInterface
65
     */
66 59
    public function parse($data): PrivateKeyInterface
67
    {
68 59
        return $this->fromParser(new Parser($data, $this->ecAdapter->getMath()));
69
    }
70
}
71