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