|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace BitWasp\Trezor\Bridge\Codec\CallMessage; |
|
6
|
|
|
|
|
7
|
|
|
use GuzzleHttp\Psr7\Stream; |
|
8
|
|
|
use Psr\Http\Message\StreamInterface; |
|
9
|
|
|
|
|
10
|
|
|
class HexCodec |
|
11
|
|
|
{ |
|
12
|
1 |
|
private function stringToStream(string $stringToConvert) |
|
13
|
|
|
{ |
|
14
|
1 |
|
$stream = fopen('php://memory', 'w+'); |
|
15
|
1 |
|
if (!is_resource($stream)) { |
|
16
|
|
|
throw new \RuntimeException("Failed to create stream"); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
1 |
|
$wrote = fwrite($stream, $stringToConvert); |
|
20
|
1 |
|
if ($wrote !== strlen($stringToConvert)) { |
|
21
|
|
|
throw new \RuntimeException("Failed to write to stream"); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
1 |
|
rewind($stream); |
|
25
|
1 |
|
return $stream; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
1 |
|
public function convertHexPayloadToBinary(StreamInterface $hexStream): StreamInterface |
|
29
|
|
|
{ |
|
30
|
1 |
|
if ($hexStream->getSize() < 12) { |
|
31
|
|
|
throw new \Exception("Malformed data (size too small)"); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
return new Stream($this->stringToStream(pack("H*", $hexStream->getContents()))); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
1 |
|
public function parsePayload(StreamInterface $stream): array |
|
38
|
|
|
{ |
|
39
|
1 |
|
list ($type) = array_values(unpack('n', $stream->read(2))); |
|
40
|
1 |
|
$stream->seek(2); |
|
41
|
|
|
|
|
42
|
1 |
|
list ($size) = array_values(unpack('N', $stream->read(4))); |
|
43
|
1 |
|
$stream->seek(6); |
|
44
|
|
|
|
|
45
|
1 |
|
if ($size > ($stream->getSize() - 6)) { |
|
46
|
|
|
throw new \Exception("Malformed data (sent more than size)"); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1 |
|
return [$type, $this->stringToStream($stream->read($size))]; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
public function encode(int $messageType, \Protobuf\Message $protobuf): string |
|
53
|
|
|
{ |
|
54
|
1 |
|
$stream = $protobuf->toStream(); |
|
55
|
1 |
|
return unpack( |
|
56
|
1 |
|
'H*', |
|
57
|
1 |
|
sprintf( |
|
58
|
1 |
|
"%s%s", |
|
59
|
1 |
|
pack('nN', $messageType, $stream->getSize()), |
|
60
|
1 |
|
$stream->getContents() |
|
61
|
|
|
) |
|
62
|
1 |
|
)[1]; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|