1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BitWasp\Trezor\Bridge\Codec\CallMessage; |
6
|
|
|
|
7
|
|
|
use BitWasp\Trezor\Bridge\Exception\InvalidMessageException; |
8
|
|
|
use BitWasp\Trezor\Bridge\Util\StreamUtil; |
9
|
|
|
use Psr\Http\Message\StreamInterface; |
10
|
|
|
|
11
|
|
|
class HexCodec |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var StreamUtil |
15
|
|
|
*/ |
16
|
|
|
private $stream; |
17
|
|
|
|
18
|
30 |
|
public function __construct() |
19
|
|
|
{ |
20
|
30 |
|
$this->stream = new StreamUtil(); |
21
|
30 |
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Implement integer comparison |
25
|
|
|
* Returns: 0 if $a === $b |
26
|
|
|
* -1 if $a < $b |
27
|
|
|
* +1 if $a > $b |
28
|
|
|
* |
29
|
|
|
* @param int $a |
30
|
|
|
* @param int $b |
31
|
|
|
* @return int |
32
|
|
|
*/ |
33
|
4 |
|
private function intcmp(int $a, int $b): int |
34
|
|
|
{ |
35
|
4 |
|
return ($a < $b) ? -1 : (($a > $b) ? 1 : 0); |
36
|
|
|
} |
37
|
|
|
|
38
|
10 |
|
public function parsePayload(StreamInterface $stream): array |
39
|
|
|
{ |
40
|
10 |
|
if ($stream->getSize() < 12) { |
41
|
6 |
|
throw new InvalidMessageException("Malformed data (size too small)"); |
42
|
|
|
} |
43
|
|
|
|
44
|
4 |
|
$stream = $this->stream->hex2bin($stream); |
45
|
4 |
|
list ($type) = array_values(unpack('n', $stream->read(2))); |
46
|
4 |
|
$stream->seek(2); |
47
|
|
|
|
48
|
4 |
|
list ($size) = array_values(unpack('N', $stream->read(4))); |
49
|
4 |
|
$stream->seek(6); |
50
|
|
|
|
51
|
4 |
|
$lCmp = $this->intcmp($stream->getSize() - 6, $size); |
52
|
4 |
|
if ($lCmp < 0) { |
53
|
1 |
|
throw new InvalidMessageException("Malformed data (not enough data)"); |
54
|
3 |
|
} else if ($lCmp > 0) { |
55
|
1 |
|
throw new InvalidMessageException("Malformed data (too much data)"); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
return [$type, $this->stream->createStream($stream->read($size))]; |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
public function encode(int $messageType, \Protobuf\Message $protobuf): string |
62
|
|
|
{ |
63
|
2 |
|
$stream = $protobuf->toStream(); |
64
|
2 |
|
return unpack( |
65
|
2 |
|
'H*', |
66
|
2 |
|
sprintf( |
67
|
2 |
|
"%s%s", |
68
|
2 |
|
pack('nN', $messageType, $stream->getSize()), |
69
|
2 |
|
$stream->getContents() |
70
|
|
|
) |
71
|
2 |
|
)[1]; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|