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.
Files changed (34) hide show
  1. cli.py +249 -0
  2. index.py +66 -0
  3. meshcoredecoder/__init__.py +8 -0
  4. meshcoredecoder/crypto/__init__.py +6 -0
  5. meshcoredecoder/crypto/channel_crypto.py +113 -0
  6. meshcoredecoder/crypto/ed25519_verifier.py +136 -0
  7. meshcoredecoder/crypto/key_manager.py +71 -0
  8. meshcoredecoder/decoder/__init__.py +26 -0
  9. meshcoredecoder/decoder/packet_decoder.py +500 -0
  10. meshcoredecoder/decoder/payload_decoders/__init__.py +22 -0
  11. meshcoredecoder/decoder/payload_decoders/ack.py +91 -0
  12. meshcoredecoder/decoder/payload_decoders/advert.py +281 -0
  13. meshcoredecoder/decoder/payload_decoders/anon_request.py +137 -0
  14. meshcoredecoder/decoder/payload_decoders/group_text.py +130 -0
  15. meshcoredecoder/decoder/payload_decoders/path.py +89 -0
  16. meshcoredecoder/decoder/payload_decoders/request.py +143 -0
  17. meshcoredecoder/decoder/payload_decoders/response.py +133 -0
  18. meshcoredecoder/decoder/payload_decoders/text_message.py +70 -0
  19. meshcoredecoder/decoder/payload_decoders/trace.py +156 -0
  20. meshcoredecoder/types/__init__.py +15 -0
  21. meshcoredecoder/types/crypto.py +67 -0
  22. meshcoredecoder/types/enums.py +60 -0
  23. meshcoredecoder/types/packet.py +139 -0
  24. meshcoredecoder/types/payloads.py +244 -0
  25. meshcoredecoder/utils/__init__.py +18 -0
  26. meshcoredecoder/utils/auth_token.py +234 -0
  27. meshcoredecoder/utils/enum_names.py +58 -0
  28. meshcoredecoder/utils/hex.py +38 -0
  29. meshcoredecoder-0.1.0.dist-info/METADATA +332 -0
  30. meshcoredecoder-0.1.0.dist-info/RECORD +34 -0
  31. meshcoredecoder-0.1.0.dist-info/WHEEL +5 -0
  32. meshcoredecoder-0.1.0.dist-info/entry_points.txt +2 -0
  33. meshcoredecoder-0.1.0.dist-info/licenses/LICENSE +21 -0
  34. meshcoredecoder-0.1.0.dist-info/top_level.txt +3 -0
@@ -0,0 +1,281 @@
1
+ """
2
+ Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
3
+ MIT License
4
+
5
+ Advert payload decoder with Ed25519 signature verification
6
+ """
7
+
8
+ from datetime import datetime
9
+ from typing import Optional, Dict, Any, List
10
+ from ...types.payloads import AdvertPayload
11
+ from ...types.packet import PayloadSegment
12
+ from ...types.enums import PayloadType, PayloadVersion, DeviceRole, AdvertFlags
13
+ from ...utils.hex import bytes_to_hex
14
+ from ...utils.enum_names import get_device_role_name
15
+
16
+
17
+ class AdvertPayloadDecoder:
18
+ @staticmethod
19
+ def decode(
20
+ payload: bytes,
21
+ options: Optional[Dict[str, Any]] = None
22
+ ) -> Optional[AdvertPayload]:
23
+ """Decode an Advert payload"""
24
+ if options is None:
25
+ options = {}
26
+
27
+ try:
28
+ # Start of appdata section: public_key(32) + timestamp(4) + signature(64) + flags(1) = 101 bytes
29
+ if len(payload) < 101:
30
+ result = AdvertPayload(
31
+ payload_type=PayloadType.Advert,
32
+ version=PayloadVersion.Version1,
33
+ is_valid=False,
34
+ errors=['Advertisement payload too short'],
35
+ public_key='',
36
+ timestamp=0,
37
+ signature='',
38
+ app_data={'flags': 0, 'device_role': DeviceRole.ChatNode, 'has_location': False, 'has_name': False}
39
+ )
40
+
41
+ if options.get('include_segments'):
42
+ result.segments = [PayloadSegment(
43
+ name='Invalid Advert Data',
44
+ description='Advert payload too short (minimum 101 bytes required)',
45
+ start_byte=options.get('segment_offset', 0),
46
+ end_byte=(options.get('segment_offset', 0) + len(payload) - 1),
47
+ value=bytes_to_hex(payload)
48
+ )]
49
+
50
+ return result
51
+
52
+ segments: List[PayloadSegment] = []
53
+ segment_offset = options.get('segment_offset', 0)
54
+ current_offset = 0
55
+
56
+ # Parse advertisement structure from payloads.md
57
+ public_key = bytes_to_hex(payload[current_offset:current_offset + 32])
58
+ if options.get('include_segments'):
59
+ segments.append(PayloadSegment(
60
+ name='Public Key',
61
+ description='Ed25519 public key',
62
+ start_byte=segment_offset + current_offset,
63
+ end_byte=segment_offset + current_offset + 31,
64
+ value=public_key
65
+ ))
66
+ current_offset += 32
67
+
68
+ timestamp = AdvertPayloadDecoder._read_uint32_le(payload, current_offset)
69
+ if options.get('include_segments'):
70
+ timestamp_date = datetime.fromtimestamp(timestamp)
71
+ segments.append(PayloadSegment(
72
+ name='Timestamp',
73
+ description=f'{timestamp} ({timestamp_date.strftime("%Y-%m-%dT%H:%M:%S")}Z)',
74
+ start_byte=segment_offset + current_offset,
75
+ end_byte=segment_offset + current_offset + 3,
76
+ value=bytes_to_hex(payload[current_offset:current_offset + 4])
77
+ ))
78
+ current_offset += 4
79
+
80
+ signature = bytes_to_hex(payload[current_offset:current_offset + 64])
81
+ if options.get('include_segments'):
82
+ segments.append(PayloadSegment(
83
+ name='Signature',
84
+ description='Ed25519 signature',
85
+ start_byte=segment_offset + current_offset,
86
+ end_byte=segment_offset + current_offset + 63,
87
+ value=signature
88
+ ))
89
+ current_offset += 64
90
+
91
+ flags = payload[current_offset]
92
+ if options.get('include_segments'):
93
+ binary_str = f'{flags:08b}'
94
+ device_role = AdvertPayloadDecoder._parse_device_role(flags)
95
+ role_name = get_device_role_name(device_role)
96
+ has_location = bool(flags & AdvertFlags.HasLocation.value)
97
+ has_name = bool(flags & AdvertFlags.HasName.value)
98
+ flag_desc = f' | Bits 0-3 (Role): {role_name} | Bit 4 (Location): {"Yes" if has_location else "No"} | Bit 7 (Name): {"Yes" if has_name else "No"}'
99
+ segments.append(PayloadSegment(
100
+ name='App Flags',
101
+ description=f'Binary: {binary_str}{flag_desc}',
102
+ start_byte=segment_offset + current_offset,
103
+ end_byte=segment_offset + current_offset,
104
+ value=f'{flags:02X}'
105
+ ))
106
+ current_offset += 1
107
+
108
+ app_data = {
109
+ 'flags': flags,
110
+ 'device_role': AdvertPayloadDecoder._parse_device_role(flags),
111
+ 'has_location': bool(flags & AdvertFlags.HasLocation.value),
112
+ 'has_name': bool(flags & AdvertFlags.HasName.value)
113
+ }
114
+
115
+ advert = AdvertPayload(
116
+ payload_type=PayloadType.Advert,
117
+ version=PayloadVersion.Version1,
118
+ is_valid=True,
119
+ public_key=public_key,
120
+ timestamp=timestamp,
121
+ signature=signature,
122
+ app_data=app_data
123
+ )
124
+
125
+ offset = current_offset
126
+
127
+ # Location data (if HasLocation flag is set)
128
+ if flags & AdvertFlags.HasLocation.value and len(payload) >= offset + 8:
129
+ lat = AdvertPayloadDecoder._read_int32_le(payload, offset) / 1000000
130
+ lon = AdvertPayloadDecoder._read_int32_le(payload, offset + 4) / 1000000
131
+ advert.app_data['location'] = {
132
+ 'latitude': round(lat * 1000000) / 1000000, # Keep precision
133
+ 'longitude': round(lon * 1000000) / 1000000
134
+ }
135
+
136
+ if options.get('include_segments'):
137
+ segments.append(PayloadSegment(
138
+ name='Latitude',
139
+ description=f'{lat}° ({lat})',
140
+ start_byte=segment_offset + offset,
141
+ end_byte=segment_offset + offset + 3,
142
+ value=bytes_to_hex(payload[offset:offset + 4])
143
+ ))
144
+
145
+ segments.append(PayloadSegment(
146
+ name='Longitude',
147
+ description=f'{lon}° ({lon})',
148
+ start_byte=segment_offset + offset + 4,
149
+ end_byte=segment_offset + offset + 7,
150
+ value=bytes_to_hex(payload[offset + 4:offset + 8])
151
+ ))
152
+
153
+ offset += 8
154
+
155
+ # Skip feature fields for now (HasFeature1, HasFeature2)
156
+ if flags & AdvertFlags.HasFeature1.value:
157
+ offset += 2
158
+ if flags & AdvertFlags.HasFeature2.value:
159
+ offset += 2
160
+
161
+ # Name data (if HasName flag is set)
162
+ if flags & AdvertFlags.HasName.value and len(payload) > offset:
163
+ name_bytes = payload[offset:]
164
+ raw_name = name_bytes.decode('utf-8', errors='replace').split('\0')[0]
165
+ advert.app_data['name'] = AdvertPayloadDecoder._sanitize_control_characters(raw_name) or raw_name
166
+
167
+ if options.get('include_segments'):
168
+ segments.append(PayloadSegment(
169
+ name='Node Name',
170
+ description=f'Node name: "{advert.app_data.get("name")}"',
171
+ start_byte=segment_offset + offset,
172
+ end_byte=segment_offset + len(payload) - 1,
173
+ value=bytes_to_hex(name_bytes)
174
+ ))
175
+
176
+ if options.get('include_segments'):
177
+ advert.segments = segments
178
+
179
+ return advert
180
+ except Exception as error:
181
+ return AdvertPayload(
182
+ payload_type=PayloadType.Advert,
183
+ version=PayloadVersion.Version1,
184
+ is_valid=False,
185
+ errors=[str(error)],
186
+ public_key='',
187
+ timestamp=0,
188
+ signature='',
189
+ app_data={'flags': 0, 'device_role': DeviceRole.ChatNode, 'has_location': False, 'has_name': False}
190
+ )
191
+
192
+ @staticmethod
193
+ def _parse_device_role(flags: int) -> DeviceRole:
194
+ """Parse device role from flags byte"""
195
+ role_value = flags & 0x0F
196
+ if role_value == 0x01:
197
+ return DeviceRole.ChatNode
198
+ elif role_value == 0x02:
199
+ return DeviceRole.Repeater
200
+ elif role_value == 0x03:
201
+ return DeviceRole.RoomServer
202
+ elif role_value == 0x04:
203
+ return DeviceRole.Sensor
204
+ else:
205
+ return DeviceRole.ChatNode
206
+
207
+ @staticmethod
208
+ def _read_uint32_le(buffer: bytes, offset: int) -> int:
209
+ """Read a 32-bit unsigned integer in little-endian format"""
210
+ return (
211
+ buffer[offset] |
212
+ (buffer[offset + 1] << 8) |
213
+ (buffer[offset + 2] << 16) |
214
+ (buffer[offset + 3] << 24)
215
+ )
216
+
217
+ @staticmethod
218
+ def _read_int32_le(buffer: bytes, offset: int) -> int:
219
+ """Read a 32-bit signed integer in little-endian format"""
220
+ value = AdvertPayloadDecoder._read_uint32_le(buffer, offset)
221
+ # Convert unsigned to signed
222
+ return value - 0x100000000 if value > 0x7FFFFFFF else value
223
+
224
+ @staticmethod
225
+ def _sanitize_control_characters(value: Optional[str]) -> Optional[str]:
226
+ """Remove control characters from string"""
227
+ if not value:
228
+ return None
229
+ import re
230
+ sanitized = value.strip().rstrip('\0').replace('\0', '')
231
+ # Remove control characters
232
+ sanitized = re.sub(r'[\x00-\x1F\x7F]', '', sanitized)
233
+ return sanitized if sanitized else None
234
+
235
+ @staticmethod
236
+ async def decode_with_verification(
237
+ payload: bytes,
238
+ options: Optional[Dict[str, Any]] = None
239
+ ) -> Optional[AdvertPayload]:
240
+ """Decode advertisement payload with signature verification"""
241
+ from src.crypto.ed25519_verifier import Ed25519SignatureVerifier
242
+
243
+ if options is None:
244
+ options = {}
245
+
246
+ # First decode normally
247
+ advert = AdvertPayloadDecoder.decode(payload, options)
248
+ if not advert or not advert.is_valid:
249
+ return advert
250
+
251
+ # Perform signature verification
252
+ try:
253
+ # Extract app_data from the payload (everything after public_key + timestamp + signature)
254
+ app_data_start = 32 + 4 + 64 # public_key + timestamp + signature
255
+ app_data_bytes = payload[app_data_start:]
256
+ app_data_hex = bytes_to_hex(app_data_bytes)
257
+
258
+ signature_valid = await Ed25519SignatureVerifier.verify_advertisement_signature(
259
+ advert.public_key,
260
+ advert.signature,
261
+ advert.timestamp,
262
+ app_data_hex
263
+ )
264
+
265
+ advert.signature_valid = signature_valid
266
+
267
+ if not signature_valid:
268
+ advert.signature_error = 'Ed25519 signature verification failed'
269
+ advert.is_valid = False
270
+ if not advert.errors:
271
+ advert.errors = []
272
+ advert.errors.append('Invalid Ed25519 signature')
273
+ except Exception as error:
274
+ advert.signature_valid = False
275
+ advert.signature_error = str(error)
276
+ advert.is_valid = False
277
+ if not advert.errors:
278
+ advert.errors = []
279
+ advert.errors.append('Signature verification failed: ' + str(error))
280
+
281
+ return advert
@@ -0,0 +1,137 @@
1
+ """
2
+ Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
3
+ MIT License
4
+
5
+ AnonRequest payload decoder
6
+ """
7
+
8
+ from typing import Optional, Dict, Any, List
9
+ from ...types.payloads import AnonRequestPayload
10
+ from ...types.packet import PayloadSegment
11
+ from ...types.enums import PayloadType, PayloadVersion
12
+ from ...utils.hex import byte_to_hex, bytes_to_hex
13
+
14
+
15
+ class AnonRequestPayloadDecoder:
16
+ @staticmethod
17
+ def decode(
18
+ payload: bytes,
19
+ options: Optional[Dict[str, Any]] = None
20
+ ) -> Optional[AnonRequestPayload]:
21
+ """Decode an AnonRequest payload"""
22
+ if options is None:
23
+ options = {}
24
+
25
+ try:
26
+ # Based on MeshCore payloads.md - AnonRequest payload structure:
27
+ # - destination_hash (1 byte)
28
+ # - sender_public_key (32 bytes)
29
+ # - cipher_mac (2 bytes)
30
+ # - ciphertext (rest of payload)
31
+
32
+ if len(payload) < 35:
33
+ result = AnonRequestPayload(
34
+ payload_type=PayloadType.AnonRequest,
35
+ version=PayloadVersion.Version1,
36
+ is_valid=False,
37
+ errors=['AnonRequest payload too short (minimum 35 bytes: dest + public key + MAC)'],
38
+ destination_hash='',
39
+ sender_public_key='',
40
+ cipher_mac='',
41
+ ciphertext='',
42
+ ciphertext_length=0
43
+ )
44
+
45
+ if options.get('include_segments'):
46
+ result.segments = [PayloadSegment(
47
+ name='Invalid AnonRequest Data',
48
+ description='AnonRequest payload too short (minimum 35 bytes required: 1 for dest hash + 32 for public key + 2 for MAC)',
49
+ start_byte=options.get('segment_offset', 0),
50
+ end_byte=(options.get('segment_offset', 0) + len(payload) - 1),
51
+ value=bytes_to_hex(payload)
52
+ )]
53
+
54
+ return result
55
+
56
+ segments: List[PayloadSegment] = []
57
+ segment_offset = options.get('segment_offset', 0)
58
+ offset = 0
59
+
60
+ # Parse destination hash (1 byte)
61
+ destination_hash = byte_to_hex(payload[0])
62
+
63
+ if options.get('include_segments'):
64
+ segments.append(PayloadSegment(
65
+ name='Destination Hash',
66
+ description=f'First byte of destination node public key: 0x{destination_hash}',
67
+ start_byte=segment_offset + offset,
68
+ end_byte=segment_offset + offset,
69
+ value=destination_hash
70
+ ))
71
+ offset += 1
72
+
73
+ # Parse sender public key (32 bytes)
74
+ sender_public_key = bytes_to_hex(payload[1:33])
75
+
76
+ if options.get('include_segments'):
77
+ segments.append(PayloadSegment(
78
+ name='Sender Public Key',
79
+ description='Ed25519 public key of the sender (32 bytes)',
80
+ start_byte=segment_offset + offset,
81
+ end_byte=segment_offset + offset + 31,
82
+ value=sender_public_key
83
+ ))
84
+ offset += 32
85
+
86
+ # Parse cipher MAC (2 bytes)
87
+ cipher_mac = bytes_to_hex(payload[33:35])
88
+
89
+ if options.get('include_segments'):
90
+ segments.append(PayloadSegment(
91
+ name='Cipher MAC',
92
+ description='MAC for encrypted data verification (2 bytes)',
93
+ start_byte=segment_offset + offset,
94
+ end_byte=segment_offset + offset + 1,
95
+ value=cipher_mac
96
+ ))
97
+ offset += 2
98
+
99
+ # Parse ciphertext (remaining bytes)
100
+ ciphertext = bytes_to_hex(payload[35:])
101
+
102
+ if options.get('include_segments') and len(payload) > 35:
103
+ segments.append(PayloadSegment(
104
+ name='Ciphertext',
105
+ description=f'Encrypted message data ({len(payload) - 35} bytes). Contains encrypted plaintext with timestamp, sync timestamp (room server only), and password',
106
+ start_byte=segment_offset + offset,
107
+ end_byte=segment_offset + len(payload) - 1,
108
+ value=ciphertext
109
+ ))
110
+
111
+ result = AnonRequestPayload(
112
+ payload_type=PayloadType.AnonRequest,
113
+ version=PayloadVersion.Version1,
114
+ is_valid=True,
115
+ destination_hash=destination_hash,
116
+ sender_public_key=sender_public_key,
117
+ cipher_mac=cipher_mac,
118
+ ciphertext=ciphertext,
119
+ ciphertext_length=len(payload) - 35
120
+ )
121
+
122
+ if options.get('include_segments'):
123
+ result.segments = segments
124
+
125
+ return result
126
+ except Exception as error:
127
+ return AnonRequestPayload(
128
+ payload_type=PayloadType.AnonRequest,
129
+ version=PayloadVersion.Version1,
130
+ is_valid=False,
131
+ errors=[str(error)],
132
+ destination_hash='',
133
+ sender_public_key='',
134
+ cipher_mac='',
135
+ ciphertext='',
136
+ ciphertext_length=0
137
+ )
@@ -0,0 +1,130 @@
1
+ """
2
+ Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
3
+ MIT License
4
+
5
+ GroupText payload decoder with decryption support
6
+ """
7
+
8
+ from typing import Optional, Dict, Any, List
9
+ from ...types.payloads import GroupTextPayload
10
+ from ...types.packet import PayloadSegment
11
+ from ...types.enums import PayloadType, PayloadVersion
12
+ from ...types.crypto import DecryptionOptions, CryptoKeyStore
13
+ from ...crypto.channel_crypto import ChannelCrypto
14
+ from ...utils.hex import byte_to_hex, bytes_to_hex
15
+
16
+
17
+ class GroupTextPayloadDecoder:
18
+ @staticmethod
19
+ def decode(
20
+ payload: bytes,
21
+ options: Optional[DecryptionOptions] = None
22
+ ) -> Optional[GroupTextPayload]:
23
+ """Decode a GroupText payload with optional decryption"""
24
+ if options is None:
25
+ options = DecryptionOptions()
26
+
27
+ try:
28
+ if len(payload) < 3:
29
+ result = GroupTextPayload(
30
+ payload_type=PayloadType.GroupText,
31
+ version=PayloadVersion.Version1,
32
+ is_valid=False,
33
+ errors=['GroupText payload too short (need at least channel_hash(1) + MAC(2))'],
34
+ channel_hash='',
35
+ cipher_mac='',
36
+ ciphertext='',
37
+ ciphertext_length=0
38
+ )
39
+
40
+ if options and hasattr(options, 'include_segments') and options.include_segments:
41
+ result.segments = [PayloadSegment(
42
+ name='Invalid GroupText Data',
43
+ description='GroupText payload too short (minimum 3 bytes required)',
44
+ start_byte=options.get('segment_offset', 0) if isinstance(options, dict) else 0,
45
+ end_byte=(options.get('segment_offset', 0) if isinstance(options, dict) else 0) + len(payload) - 1,
46
+ value=bytes_to_hex(payload)
47
+ )]
48
+
49
+ return result
50
+
51
+ segments: List[PayloadSegment] = []
52
+ segment_offset = options.get('segment_offset', 0) if isinstance(options, dict) else 0
53
+ offset = 0
54
+
55
+ # Channel hash (1 byte) - first byte of SHA256 of channel's shared key
56
+ channel_hash = byte_to_hex(payload[offset])
57
+ if isinstance(options, dict) and options.get('include_segments'):
58
+ segments.append(PayloadSegment(
59
+ name='Channel Hash',
60
+ description='First byte of SHA256 of channel\'s shared key',
61
+ start_byte=segment_offset + offset,
62
+ end_byte=segment_offset + offset,
63
+ value=channel_hash
64
+ ))
65
+ offset += 1
66
+
67
+ # MAC (2 bytes) - message authentication code
68
+ cipher_mac = bytes_to_hex(payload[offset:offset + 2])
69
+ if isinstance(options, dict) and options.get('include_segments'):
70
+ segments.append(PayloadSegment(
71
+ name='Cipher MAC',
72
+ description='MAC for encrypted data',
73
+ start_byte=segment_offset + offset,
74
+ end_byte=segment_offset + offset + 1,
75
+ value=cipher_mac
76
+ ))
77
+ offset += 2
78
+
79
+ # Ciphertext (remaining bytes) - encrypted message
80
+ ciphertext = bytes_to_hex(payload[offset:])
81
+ if isinstance(options, dict) and options.get('include_segments') and len(payload) > offset:
82
+ segments.append(PayloadSegment(
83
+ name='Ciphertext',
84
+ description='Encrypted message content (timestamp + flags + message)',
85
+ start_byte=segment_offset + offset,
86
+ end_byte=segment_offset + len(payload) - 1,
87
+ value=ciphertext
88
+ ))
89
+
90
+ group_text = GroupTextPayload(
91
+ payload_type=PayloadType.GroupText,
92
+ version=PayloadVersion.Version1,
93
+ is_valid=True,
94
+ channel_hash=channel_hash,
95
+ cipher_mac=cipher_mac,
96
+ ciphertext=ciphertext,
97
+ ciphertext_length=len(payload) - 3
98
+ )
99
+
100
+ # Attempt decryption if key store is provided
101
+ if options.key_store and options.key_store.has_channel_key(channel_hash):
102
+ # Try all possible keys for this hash (handles collisions)
103
+ channel_keys = options.key_store.get_channel_keys(channel_hash)
104
+
105
+ for channel_key in channel_keys:
106
+ decryption_result = ChannelCrypto.decrypt_group_text_message(
107
+ ciphertext,
108
+ cipher_mac,
109
+ channel_key
110
+ )
111
+
112
+ if decryption_result.success and decryption_result.data:
113
+ group_text.decrypted = decryption_result.data
114
+ break # Stop trying keys once we find one that works
115
+
116
+ if isinstance(options, dict) and options.get('include_segments'):
117
+ group_text.segments = segments
118
+
119
+ return group_text
120
+ except Exception as error:
121
+ return GroupTextPayload(
122
+ payload_type=PayloadType.GroupText,
123
+ version=PayloadVersion.Version1,
124
+ is_valid=False,
125
+ errors=[str(error)],
126
+ channel_hash='',
127
+ cipher_mac='',
128
+ ciphertext='',
129
+ ciphertext_length=0
130
+ )
@@ -0,0 +1,89 @@
1
+ """
2
+ Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
3
+ MIT License
4
+
5
+ Path payload decoder
6
+ """
7
+
8
+ from typing import Optional, Dict, Any, List
9
+ from ...types.payloads import PathPayload
10
+ from ...types.enums import PayloadType, PayloadVersion
11
+ from ...utils.hex import byte_to_hex, bytes_to_hex
12
+
13
+
14
+ class PathPayloadDecoder:
15
+ @staticmethod
16
+ def decode(
17
+ payload: bytes,
18
+ options: Optional[Dict[str, Any]] = None
19
+ ) -> Optional[PathPayload]:
20
+ """Decode a Path payload"""
21
+ if options is None:
22
+ options = {}
23
+
24
+ try:
25
+ # Based on MeshCore payloads.md - Path payload structure:
26
+ # - path_length (1 byte)
27
+ # - path (variable length) - list of node hashes (one byte each)
28
+ # - extra_type (1 byte) - bundled payload type
29
+ # - extra (rest of data) - bundled payload content
30
+
31
+ if len(payload) < 2:
32
+ return PathPayload(
33
+ payload_type=PayloadType.Path,
34
+ version=PayloadVersion.Version1,
35
+ is_valid=False,
36
+ errors=['Path payload too short (minimum 2 bytes: path length + extra type)'],
37
+ path_length=0,
38
+ path_hashes=[],
39
+ extra_type=0,
40
+ extra_data=''
41
+ )
42
+
43
+ path_length = payload[0]
44
+
45
+ if len(payload) < 1 + path_length + 1:
46
+ return PathPayload(
47
+ payload_type=PayloadType.Path,
48
+ version=PayloadVersion.Version1,
49
+ is_valid=False,
50
+ errors=[f'Path payload too short (need {1 + path_length + 1} bytes for path length + path + extra type)'],
51
+ path_length=path_length,
52
+ path_hashes=[],
53
+ extra_type=0,
54
+ extra_data=''
55
+ )
56
+
57
+ # Parse path hashes (one byte each)
58
+ path_hashes: List[str] = []
59
+ for i in range(path_length):
60
+ path_hashes.append(byte_to_hex(payload[1 + i]))
61
+
62
+ # Parse extra type (1 byte after path)
63
+ extra_type = payload[1 + path_length]
64
+
65
+ # Parse extra data (remaining bytes)
66
+ extra_data = ''
67
+ if len(payload) > 1 + path_length + 1:
68
+ extra_data = bytes_to_hex(payload[1 + path_length + 1:])
69
+
70
+ return PathPayload(
71
+ payload_type=PayloadType.Path,
72
+ version=PayloadVersion.Version1,
73
+ is_valid=True,
74
+ path_length=path_length,
75
+ path_hashes=path_hashes,
76
+ extra_type=extra_type,
77
+ extra_data=extra_data
78
+ )
79
+ except Exception as error:
80
+ return PathPayload(
81
+ payload_type=PayloadType.Path,
82
+ version=PayloadVersion.Version1,
83
+ is_valid=False,
84
+ errors=[str(error)],
85
+ path_length=0,
86
+ path_hashes=[],
87
+ extra_type=0,
88
+ extra_data=''
89
+ )