1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BitWasp\Bitcoin\Networking\Serializer\Structure; |
6
|
|
|
|
7
|
|
|
use BitWasp\Bitcoin\Networking\Structure\Header; |
8
|
|
|
use BitWasp\Bitcoin\Serializer\Types; |
9
|
|
|
use BitWasp\Buffertools\Buffer; |
10
|
|
|
use BitWasp\Buffertools\BufferInterface; |
11
|
|
|
use BitWasp\Buffertools\Parser; |
12
|
|
|
|
13
|
|
|
class HeaderSerializer |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var \BitWasp\Buffertools\Types\ByteString |
17
|
|
|
*/ |
18
|
|
|
private $bytestring12; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var \BitWasp\Buffertools\Types\ByteString |
22
|
|
|
*/ |
23
|
|
|
private $bytestring4; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var \BitWasp\Buffertools\Types\Uint32 |
27
|
|
|
*/ |
28
|
|
|
private $uint32; |
29
|
|
|
|
30
|
|
|
public function __construct() |
31
|
|
|
{ |
32
|
|
|
$this->bytestring12 = Types::bytestring(12); |
33
|
|
|
$this->bytestring4 = Types::bytestring(4); |
34
|
|
|
$this->uint32 = Types::uint32le(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param Header $header |
39
|
|
|
* @return Buffer |
40
|
|
|
*/ |
41
|
|
|
public function serialize(Header $header): BufferInterface |
42
|
|
|
{ |
43
|
|
|
$command = new Buffer(str_pad($header->getCommand(), 12, "\x00", STR_PAD_RIGHT)); |
44
|
|
|
|
45
|
|
|
return new Buffer( |
46
|
|
|
$this->bytestring12->write($command). |
47
|
|
|
$this->uint32->write($header->getLength()). |
48
|
|
|
$this->bytestring4->write($header->getChecksum()) |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param BufferInterface $data |
54
|
|
|
* @return Header |
55
|
|
|
*/ |
56
|
|
|
public function parse(BufferInterface $data): Header |
57
|
|
|
{ |
58
|
|
|
return $this->fromParser(new Parser($data)); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param Parser $parser |
63
|
|
|
* @return Header |
64
|
|
|
*/ |
65
|
|
|
public function fromParser(Parser $parser): Header |
66
|
|
|
{ |
67
|
|
|
return new Header( |
68
|
|
|
trim($this->bytestring12->read($parser)->getBinary()), |
69
|
|
|
(int) $this->uint32->read($parser), |
70
|
|
|
$this->bytestring4->read($parser) |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|