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

PrivateKeySerializer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

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

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 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