1 | <?php |
||
12 | class BitcoindBlockSerializer |
||
13 | { |
||
14 | /** |
||
15 | * @var NetworkInterface |
||
16 | */ |
||
17 | private $network; |
||
18 | |||
19 | /** |
||
20 | * @var BlockSerializer |
||
21 | */ |
||
22 | private $blockSerializer; |
||
23 | |||
24 | /** |
||
25 | * @param NetworkInterface $network |
||
26 | * @param BlockSerializer $blockSerializer |
||
27 | */ |
||
28 | 6 | public function __construct(NetworkInterface $network, BlockSerializer $blockSerializer) |
|
29 | { |
||
30 | 6 | $this->blockSerializer = $blockSerializer; |
|
31 | 6 | $this->magic = Types::bytestringle(4); |
|
|
|||
32 | 6 | $this->size = Types::uint32le(); |
|
33 | 6 | $this->network = $network; |
|
34 | 6 | } |
|
35 | |||
36 | /** |
||
37 | * @param BlockInterface $block |
||
38 | * @return \BitWasp\Buffertools\BufferInterface |
||
39 | */ |
||
40 | 2 | public function serialize(BlockInterface $block) |
|
41 | { |
||
42 | 2 | $buffer = $this->blockSerializer->serialize($block); |
|
43 | 2 | $size = $buffer->getSize(); |
|
44 | 2 | return new Buffer( |
|
45 | 2 | Buffertools::flipBytes(pack("H*", $this->network->getNetMagicBytes())) . |
|
46 | 2 | $this->size->write($size) . |
|
47 | 2 | $buffer->getBinary() |
|
48 | ); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * @param Parser $parser |
||
53 | * @return BlockInterface |
||
54 | * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange |
||
55 | */ |
||
56 | 6 | public function fromParser(Parser $parser) |
|
57 | { |
||
58 | /** @var Buffer $bytes */ |
||
59 | /** @var int|string $blockSize */ |
||
60 | 6 | list ($bytes, $blockSize) = [$this->magic->read($parser), $this->size->read($parser)]; |
|
61 | 6 | if ($bytes->getHex() !== $this->network->getNetMagicBytes()) { |
|
62 | 2 | throw new \RuntimeException('Block version bytes did not match network'); |
|
63 | } |
||
64 | |||
65 | 4 | return $this->blockSerializer->fromParser(new Parser($parser->readBytes($blockSize))); |
|
66 | } |
||
67 | |||
68 | /** |
||
69 | * @param \BitWasp\Buffertools\BufferInterface|string $data |
||
70 | * @return BlockInterface |
||
71 | */ |
||
72 | 2 | public function parse($data) |
|
76 | } |
||
77 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: