1
|
|
|
<?php declare(strict_types=1); |
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\Impl\Secp256k1\Key\XOnlyPublicKey; |
8
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\XOnlyPubKeyInterface; |
9
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Key\XOnlyPublicKeySerializerInterface; |
10
|
|
|
use BitWasp\Buffertools\Buffer; |
11
|
|
|
use BitWasp\Buffertools\BufferInterface; |
12
|
|
|
|
13
|
|
|
class XOnlyPublicKeySerializer implements XOnlyPublicKeySerializerInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var EcAdapter |
17
|
|
|
*/ |
18
|
|
|
private $ecAdapter; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param EcAdapter $ecAdapter |
22
|
|
|
*/ |
23
|
2447 |
|
public function __construct(EcAdapter $ecAdapter) |
24
|
|
|
{ |
25
|
2447 |
|
$this->ecAdapter = $ecAdapter; |
26
|
2447 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param PublicKey $publicKey |
30
|
|
|
* @return BufferInterface |
31
|
|
|
*/ |
32
|
|
|
private function doSerialize(XOnlyPublicKey $publicKey) |
33
|
|
|
{ |
34
|
|
|
$serialized = ''; |
35
|
|
|
if (!secp256k1_xonly_pubkey_serialize( |
|
|
|
|
36
|
|
|
$this->ecAdapter->getContext(), |
37
|
|
|
$serialized, |
38
|
|
|
$publicKey->getResource() |
|
|
|
|
39
|
|
|
)) { |
40
|
|
|
throw new \RuntimeException('Secp256k1: Failed to serialize xonly public key'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return new Buffer($serialized, 32); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param XOnlyPubKeyInterface $publicKey |
48
|
|
|
* @return BufferInterface |
49
|
|
|
*/ |
50
|
|
|
public function serialize(XOnlyPubKeyInterface $publicKey): BufferInterface |
51
|
|
|
{ |
52
|
|
|
/** @var PublicKey $publicKey */ |
53
|
|
|
return $this->doSerialize($publicKey); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param BufferInterface $buffer |
58
|
|
|
* @return XOnlyPubKeyInterface |
59
|
|
|
*/ |
60
|
|
|
public function parse(BufferInterface $buffer): XOnlyPubKeyInterface |
61
|
|
|
{ |
62
|
|
|
$binary = $buffer->getBinary(); |
63
|
|
|
$xonlyPubkey = null; |
64
|
|
|
if (!secp256k1_xonly_pubkey_parse($this->ecAdapter->getContext(), $xonlyPubkey, $binary)) { |
|
|
|
|
65
|
|
|
throw new \RuntimeException('Secp256k1 failed to parse xonly public key'); |
66
|
|
|
} |
67
|
|
|
/** @var resource $xonlyPubkey */ |
68
|
|
|
return new XOnlyPublicKey( |
69
|
|
|
$this->ecAdapter->getContext(), |
70
|
|
|
$xonlyPubkey |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|