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