meshcoredecoder 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli.py +249 -0
- index.py +66 -0
- meshcoredecoder/__init__.py +8 -0
- meshcoredecoder/crypto/__init__.py +6 -0
- meshcoredecoder/crypto/channel_crypto.py +113 -0
- meshcoredecoder/crypto/ed25519_verifier.py +136 -0
- meshcoredecoder/crypto/key_manager.py +71 -0
- meshcoredecoder/decoder/__init__.py +26 -0
- meshcoredecoder/decoder/packet_decoder.py +500 -0
- meshcoredecoder/decoder/payload_decoders/__init__.py +22 -0
- meshcoredecoder/decoder/payload_decoders/ack.py +91 -0
- meshcoredecoder/decoder/payload_decoders/advert.py +281 -0
- meshcoredecoder/decoder/payload_decoders/anon_request.py +137 -0
- meshcoredecoder/decoder/payload_decoders/group_text.py +130 -0
- meshcoredecoder/decoder/payload_decoders/path.py +89 -0
- meshcoredecoder/decoder/payload_decoders/request.py +143 -0
- meshcoredecoder/decoder/payload_decoders/response.py +133 -0
- meshcoredecoder/decoder/payload_decoders/text_message.py +70 -0
- meshcoredecoder/decoder/payload_decoders/trace.py +156 -0
- meshcoredecoder/types/__init__.py +15 -0
- meshcoredecoder/types/crypto.py +67 -0
- meshcoredecoder/types/enums.py +60 -0
- meshcoredecoder/types/packet.py +139 -0
- meshcoredecoder/types/payloads.py +244 -0
- meshcoredecoder/utils/__init__.py +18 -0
- meshcoredecoder/utils/auth_token.py +234 -0
- meshcoredecoder/utils/enum_names.py +58 -0
- meshcoredecoder/utils/hex.py +38 -0
- meshcoredecoder-0.1.0.dist-info/METADATA +332 -0
- meshcoredecoder-0.1.0.dist-info/RECORD +34 -0
- meshcoredecoder-0.1.0.dist-info/WHEEL +5 -0
- meshcoredecoder-0.1.0.dist-info/entry_points.txt +2 -0
- meshcoredecoder-0.1.0.dist-info/licenses/LICENSE +21 -0
- meshcoredecoder-0.1.0.dist-info/top_level.txt +3 -0
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Main packet decoder - orchestrates all payload decoders
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional, Dict, Any, List, Tuple
|
|
9
|
+
from ..types.packet import DecodedPacket, PacketStructure, PacketSegment, PayloadSegment, HeaderBreakdown
|
|
10
|
+
from ..types.enums import RouteType, PayloadType, PayloadVersion
|
|
11
|
+
from ..utils.hex import hex_to_bytes, byte_to_hex, bytes_to_hex, number_to_hex
|
|
12
|
+
from ..utils.enum_names import get_route_type_name, get_payload_type_name
|
|
13
|
+
from ..types.crypto import DecryptionOptions, ValidationResult, CryptoKeyStore
|
|
14
|
+
from ..crypto.key_manager import MeshCoreKeyStore
|
|
15
|
+
|
|
16
|
+
from .payload_decoders.ack import AckPayloadDecoder
|
|
17
|
+
from .payload_decoders.trace import TracePayloadDecoder
|
|
18
|
+
from .payload_decoders.path import PathPayloadDecoder
|
|
19
|
+
from .payload_decoders.advert import AdvertPayloadDecoder
|
|
20
|
+
from .payload_decoders.group_text import GroupTextPayloadDecoder
|
|
21
|
+
from .payload_decoders.request import RequestPayloadDecoder
|
|
22
|
+
from .payload_decoders.response import ResponsePayloadDecoder
|
|
23
|
+
from .payload_decoders.anon_request import AnonRequestPayloadDecoder
|
|
24
|
+
from .payload_decoders.text_message import TextMessagePayloadDecoder
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MeshCorePacketDecoder:
|
|
28
|
+
"""Main packet decoder for MeshCore packets"""
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def decode(hex_data: str, options: Optional[DecryptionOptions] = None) -> DecodedPacket:
|
|
32
|
+
"""Decode a raw packet from hex string"""
|
|
33
|
+
result = MeshCorePacketDecoder._parse_internal(hex_data, False, options)
|
|
34
|
+
return result['packet']
|
|
35
|
+
|
|
36
|
+
@staticmethod
|
|
37
|
+
async def decode_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> DecodedPacket:
|
|
38
|
+
"""Decode a raw packet from hex string with signature verification for advertisements"""
|
|
39
|
+
result = await MeshCorePacketDecoder._parse_internal_async(hex_data, False, options)
|
|
40
|
+
return result['packet']
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def analyze_structure(hex_data: str, options: Optional[DecryptionOptions] = None) -> PacketStructure:
|
|
44
|
+
"""Analyze packet structure for detailed breakdown"""
|
|
45
|
+
result = MeshCorePacketDecoder._parse_internal(hex_data, True, options)
|
|
46
|
+
return result['structure']
|
|
47
|
+
|
|
48
|
+
@staticmethod
|
|
49
|
+
async def analyze_structure_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> PacketStructure:
|
|
50
|
+
"""Analyze packet structure with signature verification for advertisements"""
|
|
51
|
+
result = await MeshCorePacketDecoder._parse_internal_async(hex_data, True, options)
|
|
52
|
+
return result['structure']
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _parse_internal(hex_data: str, include_structure: bool, options: Optional[DecryptionOptions]) -> Dict[str, Any]:
|
|
56
|
+
"""Internal unified parsing method"""
|
|
57
|
+
bytes_data = hex_to_bytes(hex_data)
|
|
58
|
+
segments: List[PacketSegment] = []
|
|
59
|
+
|
|
60
|
+
if len(bytes_data) < 2:
|
|
61
|
+
error_packet = DecodedPacket(
|
|
62
|
+
message_hash='',
|
|
63
|
+
route_type=RouteType.Flood,
|
|
64
|
+
payload_type=PayloadType.RawCustom,
|
|
65
|
+
payload_version=PayloadVersion.Version1,
|
|
66
|
+
path_length=0,
|
|
67
|
+
path=None,
|
|
68
|
+
payload={'raw': '', 'decoded': None},
|
|
69
|
+
total_bytes=len(bytes_data),
|
|
70
|
+
is_valid=False,
|
|
71
|
+
errors=['Packet too short (minimum 2 bytes required)']
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
error_structure = PacketStructure(
|
|
75
|
+
segments=[],
|
|
76
|
+
total_bytes=len(bytes_data),
|
|
77
|
+
raw_hex=hex_data.upper(),
|
|
78
|
+
message_hash='',
|
|
79
|
+
payload={
|
|
80
|
+
'segments': [],
|
|
81
|
+
'hex': '',
|
|
82
|
+
'start_byte': 0,
|
|
83
|
+
'type': 'Unknown'
|
|
84
|
+
}
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
return {'packet': error_packet, 'structure': error_structure}
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
offset = 0
|
|
91
|
+
|
|
92
|
+
# Parse header
|
|
93
|
+
header = bytes_data[0]
|
|
94
|
+
route_type = RouteType(header & 0x03)
|
|
95
|
+
payload_type = PayloadType((header >> 2) & 0x0F)
|
|
96
|
+
payload_version = PayloadVersion((header >> 6) & 0x03)
|
|
97
|
+
|
|
98
|
+
if include_structure:
|
|
99
|
+
segments.append(PacketSegment(
|
|
100
|
+
name='Header',
|
|
101
|
+
description='Header byte breakdown',
|
|
102
|
+
start_byte=0,
|
|
103
|
+
end_byte=0,
|
|
104
|
+
value=f'0x{header:02x}',
|
|
105
|
+
header_breakdown={
|
|
106
|
+
'full_binary': f'{header:08b}',
|
|
107
|
+
'fields': [
|
|
108
|
+
{
|
|
109
|
+
'bits': '0-1',
|
|
110
|
+
'field': 'Route Type',
|
|
111
|
+
'value': get_route_type_name(route_type),
|
|
112
|
+
'binary': f'{header & 0x03:02b}'
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
'bits': '2-5',
|
|
116
|
+
'field': 'Payload Type',
|
|
117
|
+
'value': get_payload_type_name(payload_type),
|
|
118
|
+
'binary': f'{(header >> 2) & 0x0F:04b}'
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
'bits': '6-7',
|
|
122
|
+
'field': 'Version',
|
|
123
|
+
'value': str(payload_version.value),
|
|
124
|
+
'binary': f'{(header >> 6) & 0x03:02b}'
|
|
125
|
+
}
|
|
126
|
+
]
|
|
127
|
+
}
|
|
128
|
+
))
|
|
129
|
+
offset = 1
|
|
130
|
+
|
|
131
|
+
# Handle transport codes
|
|
132
|
+
transport_codes: Optional[Tuple[int, int]] = None
|
|
133
|
+
if route_type in (RouteType.TransportFlood, RouteType.TransportDirect):
|
|
134
|
+
if len(bytes_data) < offset + 4:
|
|
135
|
+
raise ValueError('Packet too short for transport codes')
|
|
136
|
+
code1 = bytes_data[offset] | (bytes_data[offset + 1] << 8)
|
|
137
|
+
code2 = bytes_data[offset + 2] | (bytes_data[offset + 3] << 8)
|
|
138
|
+
transport_codes = (code1, code2)
|
|
139
|
+
|
|
140
|
+
if include_structure:
|
|
141
|
+
transport_code = (bytes_data[offset] |
|
|
142
|
+
(bytes_data[offset + 1] << 8) |
|
|
143
|
+
(bytes_data[offset + 2] << 16) |
|
|
144
|
+
(bytes_data[offset + 3] << 24))
|
|
145
|
+
segments.append(PacketSegment(
|
|
146
|
+
name='Transport Code',
|
|
147
|
+
description='Used for Direct/Response routing',
|
|
148
|
+
start_byte=offset,
|
|
149
|
+
end_byte=offset + 3,
|
|
150
|
+
value=f'0x{transport_code:08x}'
|
|
151
|
+
))
|
|
152
|
+
offset += 4
|
|
153
|
+
|
|
154
|
+
# Parse path
|
|
155
|
+
if len(bytes_data) < offset + 1:
|
|
156
|
+
raise ValueError('Packet too short for path length')
|
|
157
|
+
path_length = bytes_data[offset]
|
|
158
|
+
|
|
159
|
+
if include_structure:
|
|
160
|
+
if route_type in (RouteType.Direct, RouteType.TransportDirect):
|
|
161
|
+
path_length_description = f'For "Direct" packets, this contains routing instructions. {path_length} bytes of routing instructions (decreases as packet travels)'
|
|
162
|
+
elif route_type in (RouteType.Flood, RouteType.TransportFlood):
|
|
163
|
+
path_length_description = f'{path_length} bytes showing route taken (increases as packet floods)'
|
|
164
|
+
else:
|
|
165
|
+
path_length_description = f'Path contains {path_length} bytes'
|
|
166
|
+
|
|
167
|
+
segments.append(PacketSegment(
|
|
168
|
+
name='Path Length',
|
|
169
|
+
description=path_length_description,
|
|
170
|
+
start_byte=offset,
|
|
171
|
+
end_byte=offset,
|
|
172
|
+
value=f'0x{path_length:02x}'
|
|
173
|
+
))
|
|
174
|
+
offset += 1
|
|
175
|
+
|
|
176
|
+
if len(bytes_data) < offset + path_length:
|
|
177
|
+
raise ValueError('Packet too short for path data')
|
|
178
|
+
|
|
179
|
+
# Convert path data to hex strings
|
|
180
|
+
path_bytes = bytes_data[offset:offset + path_length]
|
|
181
|
+
path: Optional[List[str]] = [byte_to_hex(b) for b in path_bytes] if path_length > 0 else None
|
|
182
|
+
|
|
183
|
+
if include_structure and path_length > 0:
|
|
184
|
+
if payload_type == PayloadType.Trace:
|
|
185
|
+
# TRACE packets have SNR values in path
|
|
186
|
+
snr_values = []
|
|
187
|
+
for i in range(path_length):
|
|
188
|
+
snr_raw = bytes_data[offset + i]
|
|
189
|
+
snr_signed = snr_raw - 256 if snr_raw > 127 else snr_raw
|
|
190
|
+
snr_db = snr_signed / 4.0
|
|
191
|
+
snr_values.append(f'{snr_db:.2f}dB (0x{snr_raw:02x})')
|
|
192
|
+
segments.append(PacketSegment(
|
|
193
|
+
name='Path SNR Data',
|
|
194
|
+
description=f'SNR values collected during trace: {", ".join(snr_values)}',
|
|
195
|
+
start_byte=offset,
|
|
196
|
+
end_byte=offset + path_length - 1,
|
|
197
|
+
value=bytes_to_hex(bytes_data[offset:offset + path_length])
|
|
198
|
+
))
|
|
199
|
+
else:
|
|
200
|
+
if route_type in (RouteType.Direct, RouteType.TransportDirect):
|
|
201
|
+
path_description = 'Routing instructions (bytes are stripped at each hop as packet travels to destination)'
|
|
202
|
+
elif route_type in (RouteType.Flood, RouteType.TransportFlood):
|
|
203
|
+
path_description = 'Historical route taken (bytes are added as packet floods through network)'
|
|
204
|
+
else:
|
|
205
|
+
path_description = 'Routing path information'
|
|
206
|
+
|
|
207
|
+
segments.append(PacketSegment(
|
|
208
|
+
name='Path Data',
|
|
209
|
+
description=path_description,
|
|
210
|
+
start_byte=offset,
|
|
211
|
+
end_byte=offset + path_length - 1,
|
|
212
|
+
value=bytes_to_hex(bytes_data[offset:offset + path_length])
|
|
213
|
+
))
|
|
214
|
+
offset += path_length
|
|
215
|
+
|
|
216
|
+
# Extract payload
|
|
217
|
+
payload_bytes = bytes_data[offset:]
|
|
218
|
+
payload_hex = bytes_to_hex(payload_bytes)
|
|
219
|
+
|
|
220
|
+
if include_structure and len(bytes_data) > offset:
|
|
221
|
+
segments.append(PacketSegment(
|
|
222
|
+
name='Payload',
|
|
223
|
+
description=f'{get_payload_type_name(payload_type)} payload data',
|
|
224
|
+
start_byte=offset,
|
|
225
|
+
end_byte=len(bytes_data) - 1,
|
|
226
|
+
value=bytes_to_hex(bytes_data[offset:])
|
|
227
|
+
))
|
|
228
|
+
|
|
229
|
+
# Decode payload based on type
|
|
230
|
+
decoded_payload = None
|
|
231
|
+
payload_segments: List[PayloadSegment] = []
|
|
232
|
+
|
|
233
|
+
if payload_type == PayloadType.Advert:
|
|
234
|
+
result = AdvertPayloadDecoder.decode(payload_bytes, {'include_segments': include_structure, 'segment_offset': 0})
|
|
235
|
+
decoded_payload = result
|
|
236
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
237
|
+
payload_segments.extend(result.segments)
|
|
238
|
+
elif payload_type == PayloadType.Trace:
|
|
239
|
+
result = TracePayloadDecoder.decode(payload_bytes, path, {'include_segments': include_structure, 'segment_offset': 0})
|
|
240
|
+
decoded_payload = result
|
|
241
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
242
|
+
payload_segments.extend(result.segments)
|
|
243
|
+
elif payload_type == PayloadType.GroupText:
|
|
244
|
+
decoder_options = options.__dict__ if options else {}
|
|
245
|
+
decoder_options['include_segments'] = include_structure
|
|
246
|
+
decoder_options['segment_offset'] = 0
|
|
247
|
+
result = GroupTextPayloadDecoder.decode(payload_bytes, options)
|
|
248
|
+
decoded_payload = result
|
|
249
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
250
|
+
payload_segments.extend(result.segments)
|
|
251
|
+
elif payload_type == PayloadType.Request:
|
|
252
|
+
result = RequestPayloadDecoder.decode(payload_bytes, {'include_segments': include_structure, 'segment_offset': 0})
|
|
253
|
+
decoded_payload = result
|
|
254
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
255
|
+
payload_segments.extend(result.segments)
|
|
256
|
+
elif payload_type == PayloadType.Response:
|
|
257
|
+
result = ResponsePayloadDecoder.decode(payload_bytes, {'include_segments': include_structure, 'segment_offset': 0})
|
|
258
|
+
decoded_payload = result
|
|
259
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
260
|
+
payload_segments.extend(result.segments)
|
|
261
|
+
elif payload_type == PayloadType.AnonRequest:
|
|
262
|
+
result = AnonRequestPayloadDecoder.decode(payload_bytes, {'include_segments': include_structure, 'segment_offset': 0})
|
|
263
|
+
decoded_payload = result
|
|
264
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
265
|
+
payload_segments.extend(result.segments)
|
|
266
|
+
elif payload_type == PayloadType.Ack:
|
|
267
|
+
result = AckPayloadDecoder.decode(payload_bytes, {'include_segments': include_structure, 'segment_offset': 0})
|
|
268
|
+
decoded_payload = result
|
|
269
|
+
if result and hasattr(result, 'segments') and result.segments:
|
|
270
|
+
payload_segments.extend(result.segments)
|
|
271
|
+
elif payload_type == PayloadType.Path:
|
|
272
|
+
decoded_payload = PathPayloadDecoder.decode(payload_bytes)
|
|
273
|
+
elif payload_type == PayloadType.TextMessage:
|
|
274
|
+
decoded_payload = TextMessagePayloadDecoder.decode(payload_bytes)
|
|
275
|
+
|
|
276
|
+
# If no segments were generated and we need structure, show basic payload info
|
|
277
|
+
if include_structure and len(payload_segments) == 0 and len(bytes_data) > offset:
|
|
278
|
+
payload_segments.append(PayloadSegment(
|
|
279
|
+
name=f'{get_payload_type_name(payload_type)} Payload',
|
|
280
|
+
description=f'Raw {get_payload_type_name(payload_type)} payload data ({len(payload_bytes)} bytes)',
|
|
281
|
+
start_byte=0,
|
|
282
|
+
end_byte=len(payload_bytes) - 1,
|
|
283
|
+
value=bytes_to_hex(payload_bytes)
|
|
284
|
+
))
|
|
285
|
+
|
|
286
|
+
# Calculate message hash
|
|
287
|
+
message_hash = MeshCorePacketDecoder._calculate_message_hash(bytes_data, route_type, payload_type, payload_version)
|
|
288
|
+
|
|
289
|
+
packet = DecodedPacket(
|
|
290
|
+
message_hash=message_hash,
|
|
291
|
+
route_type=route_type,
|
|
292
|
+
payload_type=payload_type,
|
|
293
|
+
payload_version=payload_version,
|
|
294
|
+
transport_codes=transport_codes,
|
|
295
|
+
path_length=path_length,
|
|
296
|
+
path=path,
|
|
297
|
+
payload={'raw': payload_hex, 'decoded': decoded_payload},
|
|
298
|
+
total_bytes=len(bytes_data),
|
|
299
|
+
is_valid=True
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
structure = PacketStructure(
|
|
303
|
+
segments=segments,
|
|
304
|
+
total_bytes=len(bytes_data),
|
|
305
|
+
raw_hex=hex_data.upper(),
|
|
306
|
+
message_hash=message_hash,
|
|
307
|
+
payload={
|
|
308
|
+
'segments': payload_segments,
|
|
309
|
+
'hex': payload_hex,
|
|
310
|
+
'start_byte': offset,
|
|
311
|
+
'type': get_payload_type_name(payload_type)
|
|
312
|
+
}
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
return {'packet': packet, 'structure': structure}
|
|
316
|
+
|
|
317
|
+
except Exception as error:
|
|
318
|
+
error_packet = DecodedPacket(
|
|
319
|
+
message_hash='',
|
|
320
|
+
route_type=RouteType.Flood,
|
|
321
|
+
payload_type=PayloadType.RawCustom,
|
|
322
|
+
payload_version=PayloadVersion.Version1,
|
|
323
|
+
path_length=0,
|
|
324
|
+
path=None,
|
|
325
|
+
payload={'raw': '', 'decoded': None},
|
|
326
|
+
total_bytes=len(bytes_data),
|
|
327
|
+
is_valid=False,
|
|
328
|
+
errors=[str(error)]
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
error_structure = PacketStructure(
|
|
332
|
+
segments=[],
|
|
333
|
+
total_bytes=len(bytes_data),
|
|
334
|
+
raw_hex=hex_data.upper(),
|
|
335
|
+
message_hash='',
|
|
336
|
+
payload={
|
|
337
|
+
'segments': [],
|
|
338
|
+
'hex': '',
|
|
339
|
+
'start_byte': 0,
|
|
340
|
+
'type': 'Unknown'
|
|
341
|
+
}
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
return {'packet': error_packet, 'structure': error_structure}
|
|
345
|
+
|
|
346
|
+
@staticmethod
|
|
347
|
+
async def _parse_internal_async(hex_data: str, include_structure: bool, options: Optional[DecryptionOptions]) -> Dict[str, Any]:
|
|
348
|
+
"""Internal unified parsing method with signature verification for advertisements"""
|
|
349
|
+
# First do the regular parsing
|
|
350
|
+
result = MeshCorePacketDecoder._parse_internal(hex_data, include_structure, options)
|
|
351
|
+
|
|
352
|
+
# If it's an advertisement, verify the signature
|
|
353
|
+
if result['packet'].payload_type == PayloadType.Advert and result['packet'].payload['decoded']:
|
|
354
|
+
try:
|
|
355
|
+
advert_payload = result['packet'].payload['decoded']
|
|
356
|
+
bytes_data = hex_to_bytes(hex_data)
|
|
357
|
+
|
|
358
|
+
# Calculate payload start offset
|
|
359
|
+
offset = 1 # Skip header
|
|
360
|
+
|
|
361
|
+
# Skip transport codes if present
|
|
362
|
+
route_type = result['packet'].route_type
|
|
363
|
+
if route_type in (RouteType.TransportFlood, RouteType.TransportDirect):
|
|
364
|
+
offset += 4
|
|
365
|
+
|
|
366
|
+
# Skip path data
|
|
367
|
+
if len(bytes_data) > offset:
|
|
368
|
+
path_length = bytes_data[offset]
|
|
369
|
+
offset += 1 + path_length
|
|
370
|
+
|
|
371
|
+
# Get the payload bytes
|
|
372
|
+
payload_bytes = bytes_data[offset:]
|
|
373
|
+
|
|
374
|
+
# Decode with verification
|
|
375
|
+
verified_advert = await AdvertPayloadDecoder.decode_with_verification(
|
|
376
|
+
payload_bytes,
|
|
377
|
+
{'include_segments': include_structure, 'segment_offset': 0}
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
if verified_advert:
|
|
381
|
+
# Update the payload with verification results
|
|
382
|
+
result['packet'].payload['decoded'] = verified_advert
|
|
383
|
+
|
|
384
|
+
# If the advertisement signature is invalid, mark the whole packet as invalid
|
|
385
|
+
if not verified_advert.is_valid:
|
|
386
|
+
result['packet'].is_valid = False
|
|
387
|
+
result['packet'].errors = verified_advert.errors or ['Invalid advertisement signature']
|
|
388
|
+
|
|
389
|
+
# Update structure segments if needed
|
|
390
|
+
if include_structure and hasattr(verified_advert, 'segments') and verified_advert.segments:
|
|
391
|
+
result['structure'].payload['segments'] = verified_advert.segments
|
|
392
|
+
except Exception as error:
|
|
393
|
+
print(f'Signature verification failed: {error}')
|
|
394
|
+
|
|
395
|
+
return result
|
|
396
|
+
|
|
397
|
+
@staticmethod
|
|
398
|
+
def validate(hex_data: str) -> ValidationResult:
|
|
399
|
+
"""Validate packet format without full decoding"""
|
|
400
|
+
bytes_data = hex_to_bytes(hex_data)
|
|
401
|
+
errors: List[str] = []
|
|
402
|
+
|
|
403
|
+
if len(bytes_data) < 2:
|
|
404
|
+
errors.append('Packet too short (minimum 2 bytes required)')
|
|
405
|
+
return ValidationResult(is_valid=False, errors=errors)
|
|
406
|
+
|
|
407
|
+
try:
|
|
408
|
+
offset = 1 # Skip header
|
|
409
|
+
|
|
410
|
+
# Check transport codes
|
|
411
|
+
header = bytes_data[0]
|
|
412
|
+
route_type = RouteType(header & 0x03)
|
|
413
|
+
if route_type in (RouteType.TransportFlood, RouteType.TransportDirect):
|
|
414
|
+
if len(bytes_data) < offset + 4:
|
|
415
|
+
errors.append('Packet too short for transport codes')
|
|
416
|
+
offset += 4
|
|
417
|
+
|
|
418
|
+
# Check path length
|
|
419
|
+
if len(bytes_data) < offset + 1:
|
|
420
|
+
errors.append('Packet too short for path length')
|
|
421
|
+
else:
|
|
422
|
+
path_length = bytes_data[offset]
|
|
423
|
+
offset += 1
|
|
424
|
+
|
|
425
|
+
if len(bytes_data) < offset + path_length:
|
|
426
|
+
errors.append('Packet too short for path data')
|
|
427
|
+
offset += path_length
|
|
428
|
+
|
|
429
|
+
# Check if we have payload data
|
|
430
|
+
if offset >= len(bytes_data):
|
|
431
|
+
errors.append('No payload data found')
|
|
432
|
+
|
|
433
|
+
except Exception as error:
|
|
434
|
+
errors.append(str(error))
|
|
435
|
+
|
|
436
|
+
return ValidationResult(is_valid=len(errors) == 0, errors=errors if errors else None)
|
|
437
|
+
|
|
438
|
+
@staticmethod
|
|
439
|
+
def _calculate_message_hash(bytes_data: bytes, route_type: RouteType, payload_type: PayloadType, payload_version: PayloadVersion) -> str:
|
|
440
|
+
"""Calculate message hash for a packet"""
|
|
441
|
+
# For TRACE packets, use the trace tag as hash
|
|
442
|
+
if payload_type == PayloadType.Trace and len(bytes_data) >= 13:
|
|
443
|
+
offset = 1
|
|
444
|
+
|
|
445
|
+
# Skip transport codes if present
|
|
446
|
+
if route_type in (RouteType.TransportFlood, RouteType.TransportDirect):
|
|
447
|
+
offset += 4
|
|
448
|
+
|
|
449
|
+
# Skip path data
|
|
450
|
+
if len(bytes_data) > offset:
|
|
451
|
+
path_len = bytes_data[offset]
|
|
452
|
+
offset += 1 + path_len
|
|
453
|
+
|
|
454
|
+
# Extract trace tag
|
|
455
|
+
if len(bytes_data) >= offset + 4:
|
|
456
|
+
trace_tag = (bytes_data[offset] |
|
|
457
|
+
(bytes_data[offset + 1] << 8) |
|
|
458
|
+
(bytes_data[offset + 2] << 16) |
|
|
459
|
+
(bytes_data[offset + 3] << 24))
|
|
460
|
+
return number_to_hex(trace_tag, 8)
|
|
461
|
+
|
|
462
|
+
# For other packets, create hash from constant parts
|
|
463
|
+
constant_header = (payload_type.value << 2) | (payload_version.value << 6)
|
|
464
|
+
offset = 1
|
|
465
|
+
|
|
466
|
+
# Skip transport codes if present
|
|
467
|
+
if route_type in (RouteType.TransportFlood, RouteType.TransportDirect):
|
|
468
|
+
offset += 4
|
|
469
|
+
|
|
470
|
+
# Skip path data
|
|
471
|
+
if len(bytes_data) > offset:
|
|
472
|
+
path_len = bytes_data[offset]
|
|
473
|
+
offset += 1 + path_len
|
|
474
|
+
|
|
475
|
+
payload_data = bytes_data[offset:]
|
|
476
|
+
hash_input = [constant_header] + list(payload_data)
|
|
477
|
+
|
|
478
|
+
# Generate hash
|
|
479
|
+
hash_value = 0
|
|
480
|
+
for byte in hash_input:
|
|
481
|
+
hash_value = ((hash_value << 5) - hash_value + byte) & 0xffffffff
|
|
482
|
+
|
|
483
|
+
return number_to_hex(hash_value, 8)
|
|
484
|
+
|
|
485
|
+
@staticmethod
|
|
486
|
+
def create_key_store(initial_keys: Optional[Dict[str, Any]] = None) -> CryptoKeyStore:
|
|
487
|
+
"""Create a key store for decryption"""
|
|
488
|
+
return MeshCoreKeyStore(initial_keys)
|
|
489
|
+
|
|
490
|
+
@staticmethod
|
|
491
|
+
def decode_to_json(hex_data: str, options: Optional[DecryptionOptions] = None) -> str:
|
|
492
|
+
"""
|
|
493
|
+
Decode packet and return as JSON string
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
JSON string representation of the decoded packet
|
|
497
|
+
"""
|
|
498
|
+
import json
|
|
499
|
+
packet = MeshCorePacketDecoder.decode(hex_data, options)
|
|
500
|
+
return json.dumps(packet.to_dict(), indent=2)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Payload decoder modules"""
|
|
2
|
+
from .ack import AckPayloadDecoder
|
|
3
|
+
from .trace import TracePayloadDecoder
|
|
4
|
+
from .path import PathPayloadDecoder
|
|
5
|
+
from .advert import AdvertPayloadDecoder
|
|
6
|
+
from .group_text import GroupTextPayloadDecoder
|
|
7
|
+
from .request import RequestPayloadDecoder
|
|
8
|
+
from .response import ResponsePayloadDecoder
|
|
9
|
+
from .anon_request import AnonRequestPayloadDecoder
|
|
10
|
+
from .text_message import TextMessagePayloadDecoder
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
'AckPayloadDecoder',
|
|
14
|
+
'TracePayloadDecoder',
|
|
15
|
+
'PathPayloadDecoder',
|
|
16
|
+
'AdvertPayloadDecoder',
|
|
17
|
+
'GroupTextPayloadDecoder',
|
|
18
|
+
'RequestPayloadDecoder',
|
|
19
|
+
'ResponsePayloadDecoder',
|
|
20
|
+
'AnonRequestPayloadDecoder',
|
|
21
|
+
'TextMessagePayloadDecoder',
|
|
22
|
+
]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Ack payload decoder
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional, Dict, Any, List
|
|
9
|
+
from ...types.payloads import AckPayload
|
|
10
|
+
from ...types.packet import PayloadSegment
|
|
11
|
+
from ...types.enums import PayloadType, PayloadVersion
|
|
12
|
+
from ...utils.hex import bytes_to_hex
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AckPayloadDecoder:
|
|
16
|
+
@staticmethod
|
|
17
|
+
def decode(
|
|
18
|
+
payload: bytes,
|
|
19
|
+
options: Optional[Dict[str, Any]] = None
|
|
20
|
+
) -> Optional[AckPayload]:
|
|
21
|
+
"""Decode an Ack payload"""
|
|
22
|
+
if options is None:
|
|
23
|
+
options = {}
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
# Based on MeshCore payloads.md - Ack payload structure:
|
|
27
|
+
# - checksum (4 bytes) - CRC checksum of message timestamp, text, and sender pubkey
|
|
28
|
+
|
|
29
|
+
if len(payload) < 4:
|
|
30
|
+
result = AckPayload(
|
|
31
|
+
payload_type=PayloadType.Ack,
|
|
32
|
+
version=PayloadVersion.Version1,
|
|
33
|
+
is_valid=False,
|
|
34
|
+
errors=['Ack payload too short (minimum 4 bytes for checksum)'],
|
|
35
|
+
checksum=''
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if options.get('include_segments'):
|
|
39
|
+
result.segments = [PayloadSegment(
|
|
40
|
+
name='Invalid Ack Data',
|
|
41
|
+
description='Ack payload too short (minimum 4 bytes required for checksum)',
|
|
42
|
+
start_byte=options.get('segment_offset', 0),
|
|
43
|
+
end_byte=(options.get('segment_offset', 0) + len(payload) - 1),
|
|
44
|
+
value=bytes_to_hex(payload)
|
|
45
|
+
)]
|
|
46
|
+
|
|
47
|
+
return result
|
|
48
|
+
|
|
49
|
+
segments: List[PayloadSegment] = []
|
|
50
|
+
segment_offset = options.get('segment_offset', 0)
|
|
51
|
+
|
|
52
|
+
# Parse checksum (4 bytes as hex)
|
|
53
|
+
checksum = bytes_to_hex(payload[0:4])
|
|
54
|
+
if options.get('include_segments'):
|
|
55
|
+
segments.append(PayloadSegment(
|
|
56
|
+
name='Checksum',
|
|
57
|
+
description=f'CRC checksum of message timestamp, text, and sender pubkey: 0x{checksum}',
|
|
58
|
+
start_byte=segment_offset,
|
|
59
|
+
end_byte=segment_offset + 3,
|
|
60
|
+
value=checksum
|
|
61
|
+
))
|
|
62
|
+
|
|
63
|
+
# Any additional data (if present)
|
|
64
|
+
if options.get('include_segments') and len(payload) > 4:
|
|
65
|
+
segments.append(PayloadSegment(
|
|
66
|
+
name='Additional Data',
|
|
67
|
+
description='Extra data in Ack payload',
|
|
68
|
+
start_byte=segment_offset + 4,
|
|
69
|
+
end_byte=segment_offset + len(payload) - 1,
|
|
70
|
+
value=bytes_to_hex(payload[4:])
|
|
71
|
+
))
|
|
72
|
+
|
|
73
|
+
result = AckPayload(
|
|
74
|
+
payload_type=PayloadType.Ack,
|
|
75
|
+
version=PayloadVersion.Version1,
|
|
76
|
+
is_valid=True,
|
|
77
|
+
checksum=checksum
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
if options.get('include_segments'):
|
|
81
|
+
result.segments = segments
|
|
82
|
+
|
|
83
|
+
return result
|
|
84
|
+
except Exception as error:
|
|
85
|
+
return AckPayload(
|
|
86
|
+
payload_type=PayloadType.Ack,
|
|
87
|
+
version=PayloadVersion.Version1,
|
|
88
|
+
is_valid=False,
|
|
89
|
+
errors=[str(error)],
|
|
90
|
+
checksum=''
|
|
91
|
+
)
|