1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BitWasp\Bitcoin\Serializer\Chain; |
4
|
|
|
|
5
|
|
|
use BitWasp\Bitcoin\Chain\BlockLocator; |
6
|
|
|
use BitWasp\Bitcoin\Serializer\Types; |
7
|
|
|
use BitWasp\Buffertools\Buffer; |
8
|
|
|
use BitWasp\Buffertools\BufferInterface; |
9
|
|
|
use BitWasp\Buffertools\Buffertools; |
10
|
|
|
use BitWasp\Buffertools\Parser; |
11
|
|
|
use BitWasp\Buffertools\Template; |
12
|
|
|
|
13
|
|
|
class BlockLocatorSerializer |
14
|
|
|
{ |
15
|
6 |
|
|
16
|
|
|
/** |
17
|
6 |
|
* @var Template |
18
|
6 |
|
*/ |
19
|
6 |
|
private $template; |
20
|
6 |
|
|
21
|
6 |
|
public function __construct() |
22
|
6 |
|
{ |
23
|
|
|
$this->varint = Types::varint(); |
|
|
|
|
24
|
|
|
$this->bytestring32 = $bytestring32 = Types::bytestringle(32); |
|
|
|
|
25
|
|
|
$this->template = new Template([ |
26
|
|
|
Types::vector(function (Parser $parser) use ($bytestring32) { |
27
|
|
|
return $bytestring32->read($parser); |
28
|
|
|
}), |
29
|
6 |
|
$bytestring32 |
30
|
|
|
]); |
31
|
6 |
|
} |
32
|
|
|
|
33
|
6 |
|
/** |
34
|
3 |
|
* @param Parser $parser |
35
|
|
|
* @return BlockLocator |
36
|
3 |
|
*/ |
37
|
|
|
public function fromParser(Parser $parser) |
38
|
|
|
{ |
39
|
|
|
$numHashes = $this->varint->read($parser); |
40
|
|
|
$hashes = []; |
41
|
|
|
for ($i = 0; $i < $numHashes; $i++) { |
42
|
|
|
$hashes[] = $this->bytestring32->read($parser); |
43
|
6 |
|
} |
44
|
|
|
|
45
|
6 |
|
$hashStop = $this->bytestring32->read($parser); |
46
|
|
|
|
47
|
|
|
return new BlockLocator($hashes, $hashStop); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param BufferInterface|string $data |
52
|
6 |
|
* @return BlockLocator |
53
|
|
|
*/ |
54
|
6 |
|
public function parse($data) |
55
|
6 |
|
{ |
56
|
6 |
|
return $this->fromParser(new Parser($data)); |
57
|
3 |
|
} |
58
|
|
|
|
59
|
6 |
|
/** |
60
|
6 |
|
* @param BlockLocator $blockLocator |
61
|
6 |
|
* @return \BitWasp\Buffertools\BufferInterface |
62
|
3 |
|
*/ |
63
|
|
|
public function serialize(BlockLocator $blockLocator) |
64
|
|
|
{ |
65
|
|
|
$binary = Buffertools::numToVarInt(count($blockLocator->getHashes()))->getBinary(); |
66
|
|
|
foreach ($blockLocator->getHashes() as $hash) { |
67
|
|
|
$binary .= Buffertools::flipBytes($hash->getBinary()); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$binary .= $blockLocator->getHashStop()->getBinary(); |
71
|
|
|
return new Buffer($binary); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
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: