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