Completed
Pull Request — master (#221)
by thomas
51:04 queued 47:55
created

PublicKeySerializer::parse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.7462
Metric Value
dl 0
loc 16
ccs 6
cts 14
cp 0.4286
rs 9.4286
cc 2
eloc 10
nc 2
nop 1
crap 2.7462
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\PublicKey;
7
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Key\PublicKeySerializerInterface;
8
use BitWasp\Buffertools\Buffer;
9
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
10
use BitWasp\Buffertools\Parser;
11
12
class PublicKeySerializer implements PublicKeySerializerInterface
13
{
14
    /**
15
     * @var EcAdapter
16
     */
17
    private $ecAdapter;
18
19
    /**
20
     * @param EcAdapter $ecAdapter
21
     */
22 393
    public function __construct(EcAdapter $ecAdapter)
23
    {
24 393
        $this->ecAdapter = $ecAdapter;
25 393
    }
26
27
    /**
28
     * @param PublicKey $publicKey
29
     * @return Buffer
30
     */
31 180
    private function doSerialize(PublicKey $publicKey)
32
    {
33 180
        $serialized = '';
34 180
        $isCompressed = $publicKey->isCompressed();
35 180
        if (!secp256k1_ec_pubkey_serialize(
36 180
            $this->ecAdapter->getContext(),
37 180
            $publicKey->getResource(),
38 180
            $isCompressed,
39
            $serialized
40 180
        )) {
41
            throw new \RuntimeException('Secp256k1: Failed to serialize public key');
42
        }
43
44 180
        return new Buffer(
45 180
            $serialized,
46 180
            $isCompressed ? PublicKey::LENGTH_COMPRESSED : PublicKey::LENGTH_UNCOMPRESSED,
47 180
            $this->ecAdapter->getMath()
48 180
        );
49
    }
50
51
    /**
52
     * @param PublicKeyInterface $publicKey
53
     * @return Buffer
54
     */
55 180
    public function serialize(PublicKeyInterface $publicKey)
56
    {
57
        /** @var PublicKey $publicKey */
58 180
        return $this->doSerialize($publicKey);
59
    }
60
61
    /**
62
     * @param \BitWasp\Buffertools\Buffer|string $data
63
     * @return PublicKey
64
     */
65 237
    public function parse($data)
66
    {
67 237
        $buffer = (new Parser($data))->getBuffer();
68 237
        $binary = $buffer->getBinary();
69 237
        $pubkey_t = '';
70
        /** @var resource $pubkey_t */
71 237
        if (!secp256k1_ec_pubkey_parse($this->ecAdapter->getContext(), $binary, $pubkey_t)) {
72 237
            throw new \RuntimeException('Secp256k1 failed to parse public key');
73
        }
74
75
        return new PublicKey(
76
            $this->ecAdapter,
77
            $pubkey_t,
78
            $buffer->getSize() === 33
79
        );
80
    }
81
}
82