Completed
Push — master ( 8ee677...9f7fbd )
by thomas
74:58 queued 72:17
created

PrivateKeySerializer::fromParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0876

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 10
ccs 5
cts 9
cp 0.5556
crap 1.0876
rs 9.4285
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 126
    public function __construct(EcAdapter $ecAdapter)
32
    {
33 126
        $this->ecAdapter = $ecAdapter;
34 126
    }
35
36
    /**
37
     * @param PrivateKey $privateKey
38
     * @return BufferInterface
39
     */
40 114
    private function doSerialize(PrivateKey $privateKey)
41
    {
42 114
        return new Buffer($privateKey->getSecretBinary(), 32, $this->ecAdapter->getMath());
43
    }
44
45
    /**
46
     * @param PrivateKeyInterface $privateKey
47
     * @return BufferInterface
48
     */
49 114
    public function serialize(PrivateKeyInterface $privateKey)
50
    {
51
        /** @var PrivateKey $privateKey */
52 114
        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 54
    public function fromParser(Parser $parser)
72
    {
73 54
        $compressed = $this->haveNextCompressed;
74 54
        $this->haveNextCompressed = false;
75
76 54
        return $this->ecAdapter->getPrivateKey(
77 54
            gmp_init($parser->readBytes(32)->getHex(), 16),
78
            $compressed
79
        );
80
    }
81
82
    /**
83
     * @param \BitWasp\Buffertools\BufferInterface|string $data
84
     * @return PrivateKey
85
     */
86 54
    public function parse($data)
87
    {
88 54
        return $this->fromParser(new Parser($data, $this->ecAdapter->getMath()));
89
    }
90
}
91