1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Serializer\Signature; |
4
|
|
|
|
5
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Adapter\EcAdapter; |
6
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Signature\SchnorrSignature; |
7
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Signature\SchnorrSignatureSerializerInterface; |
8
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Signature\SchnorrSignatureInterface; |
9
|
|
|
use BitWasp\Buffertools\Buffer; |
10
|
|
|
use BitWasp\Buffertools\BufferInterface; |
11
|
|
|
|
12
|
|
|
class SchnorrSignatureSerializer implements SchnorrSignatureSerializerInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var EcAdapter |
16
|
|
|
*/ |
17
|
|
|
private $ecAdapter; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param EcAdapter $ecAdapter |
21
|
|
|
*/ |
22
|
2447 |
|
public function __construct(EcAdapter $ecAdapter) |
23
|
|
|
{ |
24
|
2447 |
|
$this->ecAdapter = $ecAdapter; |
25
|
2447 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param SchnorrSignature $signature |
29
|
|
|
* @return BufferInterface |
30
|
|
|
*/ |
31
|
|
|
private function doSerialize(SchnorrSignature $signature): BufferInterface |
32
|
|
|
{ |
33
|
|
|
$sigOut = ''; |
34
|
|
|
if (!secp256k1_schnorrsig_serialize($this->ecAdapter->getContext(), $sigOut, $signature->getResource())) { |
|
|
|
|
35
|
|
|
throw new \RuntimeException('Secp256k1 serialize compact failure'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return new Buffer($sigOut, 64); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param SchnorrSignatureInterface $signature |
43
|
|
|
* @return BufferInterface |
44
|
|
|
*/ |
45
|
|
|
public function serialize(SchnorrSignatureInterface $signature): BufferInterface |
46
|
|
|
{ |
47
|
|
|
/** @var SchnorrSignature $signature */ |
48
|
|
|
return $this->doSerialize($signature); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param BufferInterface $sig |
53
|
|
|
* @return SchnorrSignatureInterface |
54
|
|
|
* @throws \Exception |
55
|
|
|
*/ |
56
|
|
|
public function parse(BufferInterface $sig): SchnorrSignatureInterface |
57
|
|
|
{ |
58
|
|
|
if ($sig->getSize() !== 64) { |
59
|
|
|
throw new \RuntimeException('Compact Sig must be 65 bytes'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$sig_t = null; |
63
|
|
|
if (!secp256k1_schnorrsig_parse($this->ecAdapter->getContext(), $sig_t, $sig->getBinary())) { |
|
|
|
|
64
|
|
|
throw new \RuntimeException('Unable to parse compact signature'); |
65
|
|
|
} |
66
|
|
|
/** @var resource $sig_t */ |
67
|
|
|
return new SchnorrSignature($this->ecAdapter, $sig_t); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|