Completed
Pull Request — master (#371)
by Ruben de
21:14
created

PrivateKeySerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 4
cp 0.75
crap 1.0156
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Serializer\Key;
4
5
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Adapter\EcAdapter;
6
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Key\PrivateKey;
7
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface;
8
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Key\PrivateKeySerializerInterface;
9
use BitWasp\Buffertools\Buffer;
10
use BitWasp\Buffertools\BufferInterface;
11
use BitWasp\Buffertools\Parser;
12
13
/**
14
 * Private Key Serializer - specific to secp256k1
15
 */
16
class PrivateKeySerializer implements PrivateKeySerializerInterface
17
{
18
    /**
19
     * @var bool
20
     */
21
    private $haveNextCompressed = false;
22
23
    /**
24
     * @var EcAdapter
25
     */
26
    private $ecAdapter;
27
28
    /**
29
     * @param EcAdapter $ecAdapter
30
     */
31 252
    public function __construct(EcAdapter $ecAdapter)
32
    {
33 252
        $this->ecAdapter = $ecAdapter;
34 252
    }
35
36
    /**
37
     * @param PrivateKey $privateKey
38
     * @return BufferInterface
39
     */
40 228
    private function doSerialize(PrivateKey $privateKey)
41
    {
42 228
        return new Buffer($privateKey->getSecretBinary(), 32, $this->ecAdapter->getMath());
43
    }
44
45
    /**
46
     * @param PrivateKeyInterface $privateKey
47
     * @return BufferInterface
48
     */
49 228
    public function serialize(PrivateKeyInterface $privateKey)
50
    {
51
        /** @var PrivateKey $privateKey */
52 228
        return $this->doSerialize($privateKey);
53
    }
54
55
    /**
56
     * Tells the serializer the next key to be parsed should be compressed.
57
     *
58
     * @return $this
59
     */
60
    public function setNextCompressed()
61
    {
62
        $this->haveNextCompressed = true;
63
        return $this;
64
    }
65
66
    /**
67
     * @param Parser $parser
68
     * @return PrivateKey
69
     * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange
70
     */
71 108
    public function fromParser(Parser $parser)
72
    {
73 108
        $compressed = $this->haveNextCompressed;
74 108
        $this->haveNextCompressed = false;
75
76 108
        return $this->ecAdapter->getPrivateKey(
77 108
            gmp_init($parser->readBytes(32)->getHex(), 16),
78
            $compressed
79 54
        );
80
    }
81
82
    /**
83
     * @param \BitWasp\Buffertools\BufferInterface|string $data
84
     * @return PrivateKey
85
     */
86 108
    public function parse($data)
87
    {
88 108
        return $this->fromParser(new Parser($data, $this->ecAdapter->getMath()));
89
    }
90
}
91