1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BitWasp\Bitcoin\Serializer\Block; |
4
|
|
|
|
5
|
|
|
use BitWasp\Bitcoin\Serializer\Types; |
6
|
|
|
use BitWasp\Buffertools\Buffer; |
7
|
|
|
use BitWasp\Buffertools\Exceptions\ParserOutOfRange; |
8
|
|
|
use BitWasp\Buffertools\Parser; |
9
|
|
|
use BitWasp\Bitcoin\Block\BlockHeader; |
10
|
|
|
use BitWasp\Bitcoin\Block\BlockHeaderInterface; |
11
|
|
|
|
12
|
|
|
class BlockHeaderSerializer |
13
|
|
|
{ |
14
|
|
|
public function __construct() |
15
|
|
|
{ |
16
|
|
|
$this->hash = Types::bytestringle(32); |
|
|
|
|
17
|
|
|
$this->uint32le = Types::uint32le(); |
|
|
|
|
18
|
1242 |
|
$this->int32le = Types::int32le(); |
|
|
|
|
19
|
|
|
} |
20
|
1242 |
|
|
21
|
1242 |
|
/** |
22
|
|
|
* @param \BitWasp\Buffertools\BufferInterface|string $string |
23
|
|
|
* @return BlockHeader |
24
|
|
|
* @throws ParserOutOfRange |
25
|
|
|
*/ |
26
|
|
|
public function parse($string) |
27
|
|
|
{ |
28
|
30 |
|
return $this->fromParser(new Parser($string)); |
29
|
|
|
} |
30
|
30 |
|
|
31
|
|
|
/** |
32
|
|
|
* @param Parser $parser |
33
|
|
|
* @return BlockHeader |
34
|
|
|
* @throws ParserOutOfRange |
35
|
|
|
*/ |
36
|
1242 |
|
public function fromParser(Parser $parser) |
37
|
|
|
{ |
38
|
1242 |
|
try { |
39
|
1242 |
|
return new BlockHeader( |
40
|
1242 |
|
$this->int32le->read($parser), |
|
|
|
|
41
|
1242 |
|
$this->hash->read($parser), |
42
|
1242 |
|
$this->hash->read($parser), |
43
|
1242 |
|
(int) $this->uint32le->read($parser), |
44
|
1242 |
|
(int) $this->uint32le->read($parser), |
45
|
1242 |
|
(int) $this->uint32le->read($parser) |
46
|
|
|
); |
47
|
|
|
} catch (ParserOutOfRange $e) { |
48
|
|
|
throw new ParserOutOfRange('Failed to extract full block header from parser'); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
108 |
|
* @param BlockHeaderInterface $header |
54
|
|
|
* @return \BitWasp\Buffertools\BufferInterface |
55
|
|
|
*/ |
56
|
|
|
public function serialize(BlockHeaderInterface $header) |
57
|
108 |
|
{ |
58
|
|
|
return new Buffer( |
59
|
90 |
|
$this->int32le->write($header->getVersion()) . |
|
|
|
|
60
|
45 |
|
$this->hash->write($header->getPrevBlock()) . |
61
|
45 |
|
$this->hash->write($header->getMerkleRoot()) . |
62
|
45 |
|
$this->uint32le->write($header->getTimestamp()) . |
63
|
45 |
|
$this->uint32le->write($header->getBits()) . |
64
|
90 |
|
$this->uint32le->write($header->getNonce()) |
65
|
|
|
); |
66
|
45 |
|
} |
67
|
|
|
} |
68
|
|
|
|
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: