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