1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Serializer\Key; |
4
|
|
|
|
5
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Adapter\EcAdapter; |
6
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Key\PrivateKeySerializerInterface; |
7
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey; |
8
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface; |
9
|
|
|
use BitWasp\Buffertools\Buffer; |
10
|
|
|
use BitWasp\Buffertools\BufferInterface; |
11
|
|
|
use BitWasp\Buffertools\Parser; |
12
|
|
|
|
13
|
|
|
class PrivateKeySerializer implements PrivateKeySerializerInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var EcAdapter |
17
|
|
|
*/ |
18
|
|
|
private $ecAdapter; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var bool |
22
|
|
|
*/ |
23
|
|
|
private $haveNextCompressed = false; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param EcAdapter $ecAdapter |
27
|
|
|
*/ |
28
|
55 |
|
public function __construct(EcAdapter $ecAdapter) |
29
|
|
|
{ |
30
|
55 |
|
$this->ecAdapter = $ecAdapter; |
31
|
55 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param PrivateKeyInterface $privateKey |
35
|
|
|
* @return BufferInterface |
36
|
|
|
*/ |
37
|
35 |
|
public function serialize(PrivateKeyInterface $privateKey) |
38
|
|
|
{ |
39
|
35 |
|
return Buffer::int( |
40
|
35 |
|
gmp_strval($privateKey->getSecret(), 10), |
41
|
35 |
|
32, |
42
|
35 |
|
$this->ecAdapter->getMath() |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
|
|
public function setNextCompressed() |
50
|
|
|
{ |
51
|
|
|
$this->haveNextCompressed = true; |
52
|
|
|
return $this; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param Parser $parser |
57
|
|
|
* @return PrivateKey |
58
|
|
|
*/ |
59
|
28 |
|
public function fromParser(Parser $parser) |
60
|
|
|
{ |
61
|
28 |
|
$compressed = $this->haveNextCompressed; |
62
|
28 |
|
$this->haveNextCompressed = false; |
63
|
28 |
|
$int = gmp_init($parser->readBytes(32)->getHex(), 16); |
64
|
28 |
|
return $this->ecAdapter->getPrivateKey($int, $compressed); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param BufferInterface|string $string |
69
|
|
|
* @return PrivateKey |
70
|
|
|
*/ |
71
|
28 |
|
public function parse($string) |
72
|
|
|
{ |
73
|
28 |
|
return $this->fromParser(new Parser($string)); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|