meshcoredecoder 0.2.1__py3-none-any.whl → 0.2.3__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 CHANGED
@@ -991,12 +991,8 @@ def decode_command(args):
991
991
 
992
992
  # Decode packet
993
993
  if args.verify:
994
- # Use async verification
995
- import asyncio
996
- loop = asyncio.get_event_loop()
997
- packet = loop.run_until_complete(
998
- MeshCoreDecoder.decode_with_verification(clean_hex, options)
999
- )
994
+ # Use verification
995
+ packet = MeshCoreDecoder.decode_with_verification(clean_hex, options)
1000
996
  else:
1001
997
  packet = MeshCoreDecoder.decode(clean_hex, options)
1002
998
 
@@ -1005,11 +1001,7 @@ def decode_command(args):
1005
1001
  if args.structure:
1006
1002
  # Get structure as well
1007
1003
  if args.verify:
1008
- import asyncio
1009
- loop = asyncio.get_event_loop()
1010
- structure = loop.run_until_complete(
1011
- MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
1012
- )
1004
+ structure = MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
1013
1005
  else:
1014
1006
  structure = MeshCoreDecoder.analyze_structure(clean_hex, options)
1015
1007
  # Use to_dict() for proper serialization
@@ -1029,11 +1021,7 @@ def decode_command(args):
1029
1021
  print(f'\n{bold("=== Packet Structure ===")}')
1030
1022
 
1031
1023
  if args.verify:
1032
- import asyncio
1033
- loop = asyncio.get_event_loop()
1034
- structure = loop.run_until_complete(
1035
- MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
1036
- )
1024
+ structure = MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
1037
1025
  else:
1038
1026
  structure = MeshCoreDecoder.analyze_structure(clean_hex, options)
1039
1027
 
index.py CHANGED
@@ -6,7 +6,7 @@ MIT License
6
6
  Main entry point for the MeshCore decoder Python port
7
7
  """
8
8
 
9
- __version__ = "0.2.1"
9
+ __version__ = "0.2.3"
10
10
 
11
11
  # Main decoder
12
12
  from src.decoder.packet_decoder import MeshCorePacketDecoder
@@ -5,4 +5,4 @@ from .decoder.packet_decoder import MeshCorePacketDecoder
5
5
  MeshCoreDecoder = MeshCorePacketDecoder
6
6
 
7
7
  __all__ = ['MeshCoreDecoder', 'MeshCorePacketDecoder']
8
- __version__ = "0.2.1"
8
+ __version__ = "0.2.3"
@@ -1014,7 +1014,7 @@ class ChannelCrypto:
1014
1014
  (decrypted_bytes[3] << 24)
1015
1015
  )
1016
1016
 
1017
- # Check if this is a room server login (has sync_timestamp)
1017
+ # For anonrequest payloads, default to repeater/sensor login
1018
1018
  # Room server: timestamp(4) + sync_timestamp(4) + password
1019
1019
  # Repeater/Sensor: timestamp(4) + password
1020
1020
  # Regular request: timestamp(4) + req_type(1) + req_data
@@ -1023,89 +1023,31 @@ class ChannelCrypto:
1023
1023
  }
1024
1024
 
1025
1025
  if len(decrypted_bytes) >= 8:
1026
- # Could be room server login with sync_timestamp
1027
- sync_timestamp = (
1028
- decrypted_bytes[4] |
1029
- (decrypted_bytes[5] << 8) |
1030
- (decrypted_bytes[6] << 16) |
1031
- (decrypted_bytes[7] << 24)
1032
- )
1033
-
1034
- # Check if bytes 4-7 look like a valid timestamp (reasonable Unix timestamp)
1035
- # If sync_timestamp is 0 or very small, it might actually be the start of a password
1036
- # Room server sync_timestamp should be a reasonable timestamp (e.g., > 1000000000)
1037
- is_likely_sync_timestamp = (sync_timestamp > 1000000000)
1038
-
1039
- if is_likely_sync_timestamp:
1040
- # Room server login: timestamp(4) + sync_timestamp(4) + password
1041
- result_data['sync_timestamp'] = sync_timestamp
1042
- # Try to decode password (null-terminated string)
1043
- password_bytes = decrypted_bytes[8:]
1044
- try:
1045
- password = password_bytes.decode('utf-8')
1046
- null_index = password.find('\0')
1047
- if null_index >= 0:
1048
- password = password[:null_index]
1049
- result_data['password'] = password
1050
- result_data['type'] = 'room_server_login'
1051
- except UnicodeDecodeError:
1052
- # Might be regular request format
1053
- if len(decrypted_bytes) >= 5:
1054
- request_type = decrypted_bytes[4]
1055
- request_data = decrypted_bytes[5:]
1056
- result_data['request_type'] = request_type
1057
- result_data['request_data'] = request_data
1058
- result_data['type'] = 'request'
1059
- else:
1060
- # sync_timestamp is 0 or very small - could be repeater/sensor login OR regular request
1061
- # Check if byte 4 is a valid request type first (0x01-0x06)
1062
- if len(decrypted_bytes) >= 5:
1063
- request_type_byte = decrypted_bytes[4]
1064
- is_valid_request_type = (0x01 <= request_type_byte <= 0x06)
1065
-
1066
- if is_valid_request_type:
1067
- # Regular request: timestamp(4) + req_type(1) + req_data
1068
- request_type = request_type_byte
1069
- request_data = decrypted_bytes[5:]
1070
- result_data['request_type'] = request_type
1071
- result_data['request_data'] = request_data
1072
- result_data['type'] = 'request'
1073
- else:
1074
- # Not a valid request type - likely repeater/sensor login
1075
- # Repeater/Sensor login: timestamp(4) + password(null-terminated string)
1076
- # Password starts at byte 4
1077
- password_bytes = decrypted_bytes[4:]
1078
- try:
1079
- password = password_bytes.decode('utf-8')
1080
- null_index = password.find('\0')
1081
- if null_index >= 0:
1082
- password = password[:null_index]
1083
- result_data['password'] = password
1084
- result_data['type'] = 'repeater_sensor_login'
1085
- except UnicodeDecodeError:
1086
- # If it's not valid UTF-8, treat as unknown
1087
- result_data['raw'] = bytes_to_hex(decrypted_bytes[4:])
1088
- result_data['type'] = 'unknown'
1089
- else:
1090
- # Too short - can't determine
1091
- result_data['raw'] = bytes_to_hex(decrypted_bytes)
1092
- result_data['type'] = 'unknown'
1093
- elif len(decrypted_bytes) >= 5:
1094
- # Could be regular request format or repeater/sensor login
1095
- # Check if byte 4 is a valid request type (0x01-0x06)
1026
+ # Check if byte 4 is a valid request type first (0x01-0x06)
1027
+ # This takes priority over checking for sync_timestamp
1096
1028
  request_type_byte = decrypted_bytes[4]
1097
1029
  is_valid_request_type = (0x01 <= request_type_byte <= 0x06)
1098
1030
 
1099
1031
  if is_valid_request_type:
1100
- # Regular request format: timestamp(4) + req_type(1) + req_data
1032
+ # Regular request: timestamp(4) + req_type(1) + req_data
1101
1033
  request_type = request_type_byte
1102
1034
  request_data = decrypted_bytes[5:]
1103
1035
  result_data['request_type'] = request_type
1104
1036
  result_data['request_data'] = request_data
1105
1037
  result_data['type'] = 'request'
1106
1038
  else:
1039
+ # Not a valid request type - check if it could be room server or repeater/sensor login
1040
+ sync_timestamp = (
1041
+ decrypted_bytes[4] |
1042
+ (decrypted_bytes[5] << 8) |
1043
+ (decrypted_bytes[6] << 16) |
1044
+ (decrypted_bytes[7] << 24)
1045
+ )
1046
+
1047
+ # For anonrequest payloads, default to repeater/sensor login
1048
+ # AnonRequest logins are always repeater/sensor logins, not room server logins
1107
1049
  # Repeater/Sensor login: timestamp(4) + password(null-terminated string)
1108
- # Byte 4 is the start of the password string
1050
+ # Password starts at byte 4
1109
1051
  password_bytes = decrypted_bytes[4:]
1110
1052
  try:
1111
1053
  password = password_bytes.decode('utf-8')
@@ -1115,15 +1057,44 @@ class ChannelCrypto:
1115
1057
  result_data['password'] = password
1116
1058
  result_data['type'] = 'repeater_sensor_login'
1117
1059
  except UnicodeDecodeError:
1118
- # If it's not valid UTF-8, might still be a request with invalid type
1119
- # or corrupted data - try as request anyway
1120
- result_data['request_type'] = request_type_byte
1121
- result_data['request_data'] = decrypted_bytes[5:]
1122
- result_data['type'] = 'request'
1060
+ # If it's not valid UTF-8, treat as unknown
1061
+ result_data['raw'] = bytes_to_hex(decrypted_bytes[4:])
1062
+ result_data['type'] = 'unknown'
1123
1063
  else:
1124
- # Too short - can't determine type
1125
- result_data['raw'] = bytes_to_hex(decrypted_bytes)
1126
- result_data['type'] = 'unknown'
1064
+ # Less than 8 bytes - check if byte 4 is a valid request type
1065
+ if len(decrypted_bytes) >= 5:
1066
+ request_type_byte = decrypted_bytes[4]
1067
+ is_valid_request_type = (0x01 <= request_type_byte <= 0x06)
1068
+
1069
+ if is_valid_request_type:
1070
+ # Regular request: timestamp(4) + req_type(1) + req_data
1071
+ request_type = request_type_byte
1072
+ request_data = decrypted_bytes[5:]
1073
+ result_data['request_type'] = request_type
1074
+ result_data['request_data'] = request_data
1075
+ result_data['type'] = 'request'
1076
+ else:
1077
+ # Not a valid request type - likely repeater/sensor login
1078
+ # Repeater/Sensor login: timestamp(4) + password(null-terminated string)
1079
+ # Byte 4 is the start of the password string
1080
+ password_bytes = decrypted_bytes[4:]
1081
+ try:
1082
+ password = password_bytes.decode('utf-8')
1083
+ null_index = password.find('\0')
1084
+ if null_index >= 0:
1085
+ password = password[:null_index]
1086
+ result_data['password'] = password
1087
+ result_data['type'] = 'repeater_sensor_login'
1088
+ except UnicodeDecodeError:
1089
+ # If it's not valid UTF-8, might still be a request with invalid type
1090
+ # or corrupted data - try as request anyway
1091
+ result_data['request_type'] = request_type_byte
1092
+ result_data['request_data'] = decrypted_bytes[5:] if len(decrypted_bytes) > 5 else b''
1093
+ result_data['type'] = 'request'
1094
+ else:
1095
+ # Too short - can't determine
1096
+ result_data['raw'] = bytes_to_hex(decrypted_bytes)
1097
+ result_data['type'] = 'unknown'
1127
1098
 
1128
1099
  return DecryptionResult(
1129
1100
  success=True,
@@ -27,7 +27,7 @@ class Ed25519SignatureVerifier:
27
27
  """Ed25519 signature verification for MeshCore advertisement packets"""
28
28
 
29
29
  @staticmethod
30
- async def verify_advertisement_signature(
30
+ def verify_advertisement_signature(
31
31
  public_key_hex: str,
32
32
  signature_hex: str,
33
33
  timestamp: int,
@@ -35,9 +35,9 @@ class MeshCorePacketDecoder:
35
35
  return result['packet']
36
36
 
37
37
  @staticmethod
38
- async def decode_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> DecodedPacket:
38
+ def decode_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> DecodedPacket:
39
39
  """Decode a raw packet from hex string with signature verification for advertisements"""
40
- result = await MeshCorePacketDecoder._parse_internal_async(hex_data, False, options)
40
+ result = MeshCorePacketDecoder._parse_internal_with_verification(hex_data, False, options)
41
41
  return result['packet']
42
42
 
43
43
  @staticmethod
@@ -47,9 +47,9 @@ class MeshCorePacketDecoder:
47
47
  return result['structure']
48
48
 
49
49
  @staticmethod
50
- async def analyze_structure_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> PacketStructure:
50
+ def analyze_structure_with_verification(hex_data: str, options: Optional[DecryptionOptions] = None) -> PacketStructure:
51
51
  """Analyze packet structure with signature verification for advertisements"""
52
- result = await MeshCorePacketDecoder._parse_internal_async(hex_data, True, options)
52
+ result = MeshCorePacketDecoder._parse_internal_with_verification(hex_data, True, options)
53
53
  return result['structure']
54
54
 
55
55
  @staticmethod
@@ -368,7 +368,7 @@ class MeshCorePacketDecoder:
368
368
  return {'packet': error_packet, 'structure': error_structure}
369
369
 
370
370
  @staticmethod
371
- async def _parse_internal_async(hex_data: str, include_structure: bool, options: Optional[DecryptionOptions]) -> Dict[str, Any]:
371
+ def _parse_internal_with_verification(hex_data: str, include_structure: bool, options: Optional[DecryptionOptions]) -> Dict[str, Any]:
372
372
  """Internal unified parsing method with signature verification for advertisements"""
373
373
  # First do the regular parsing
374
374
  result = MeshCorePacketDecoder._parse_internal(hex_data, include_structure, options)
@@ -396,7 +396,7 @@ class MeshCorePacketDecoder:
396
396
  payload_bytes = bytes_data[offset:]
397
397
 
398
398
  # Decode with verification
399
- verified_advert = await AdvertPayloadDecoder.decode_with_verification(
399
+ verified_advert = AdvertPayloadDecoder.decode_with_verification(
400
400
  payload_bytes,
401
401
  {'include_segments': include_structure, 'segment_offset': 0}
402
402
  )
@@ -252,7 +252,7 @@ class AdvertPayloadDecoder:
252
252
  return sanitized if sanitized else None
253
253
 
254
254
  @staticmethod
255
- async def decode_with_verification(
255
+ def decode_with_verification(
256
256
  payload: bytes,
257
257
  options: Optional[Dict[str, Any]] = None
258
258
  ) -> Optional[AdvertPayload]:
@@ -274,7 +274,7 @@ class AdvertPayloadDecoder:
274
274
  app_data_bytes = payload[app_data_start:]
275
275
  app_data_hex = bytes_to_hex(app_data_bytes)
276
276
 
277
- signature_valid = await Ed25519SignatureVerifier.verify_advertisement_signature(
277
+ signature_valid = Ed25519SignatureVerifier.verify_advertisement_signature(
278
278
  advert.public_key,
279
279
  advert.signature,
280
280
  advert.timestamp,
@@ -251,15 +251,18 @@ class ResponsePayloadDecoder:
251
251
  neighbors: List[NeighborEntry] = []
252
252
 
253
253
  # Check if we should attempt decryption
254
- if not options:
254
+ # Use decryption_options if available, otherwise check if options is a DecryptionOptions object
255
+ effective_options = decryption_options if decryption_options else (options if isinstance(options, DecryptionOptions) else None)
256
+
257
+ if not effective_options:
255
258
  decrypted_data = {'error': 'No decryption options provided. Use --node-key PUBKEY:PRIVKEY to provide decryption keys.'}
256
- elif not options.attempt_decryption:
259
+ elif not effective_options.attempt_decryption:
257
260
  decrypted_data = {'error': 'Decryption disabled in options'}
258
- elif not options.key_store:
261
+ elif not effective_options.key_store:
259
262
  decrypted_data = {'error': 'No key store provided. Use --node-key PUBKEY:PRIVKEY to provide decryption keys.'}
260
263
  elif len(ciphertext_bytes) == 0:
261
264
  decrypted_data = {'error': 'No ciphertext to decrypt'}
262
- elif options.attempt_decryption and options.key_store and len(ciphertext_bytes) > 0:
265
+ elif effective_options.attempt_decryption and effective_options.key_store and len(ciphertext_bytes) > 0:
263
266
  # Try to find a node key that matches the source hash
264
267
  # For Response payloads: source_hash is the node that sent the response (the responder)
265
268
  # The response is encrypted with the responder's private key, so we need the private key
@@ -286,7 +289,7 @@ class ResponsePayloadDecoder:
286
289
  our_pubkey = None # Our public key (might match destination_hash)
287
290
 
288
291
  # First, find the sender's public key (matches source_hash) and our private key
289
- for stored_pubkey, stored_privkey in options.key_store.node_keys.items():
292
+ for stored_pubkey, stored_privkey in effective_options.key_store.node_keys.items():
290
293
  pubkey_bytes = bytes.fromhex(stored_pubkey)
291
294
  if len(pubkey_bytes) > 0:
292
295
  pubkey_first_byte = byte_to_hex(pubkey_bytes[0])
@@ -350,14 +353,23 @@ class ResponsePayloadDecoder:
350
353
  (decrypted_bytes[3] << 24)
351
354
  )
352
355
 
353
- # Try to parse neighbor table (GetStats response)
356
+ # Extract content (bytes 4+)
357
+ content_bytes = decrypted_bytes[4:] if len(decrypted_bytes) > 4 else b''
358
+
359
+ # Parse response content to determine type
360
+ parsed_content = ResponsePayloadDecoder._parse_response_content(tag, content_bytes)
361
+
362
+ # Try to parse neighbor table (for GetNeighbours responses)
354
363
  neighbors, total_count = ResponsePayloadDecoder._parse_neighbors(decrypted_bytes, 0)
355
364
 
365
+ # Build decrypted_data with parsed content
356
366
  decrypted_data = {
357
367
  'tag': tag,
358
368
  'raw': bytes_to_hex(decrypted_bytes),
359
- 'neighborCount': len(neighbors)
369
+ 'content': parsed_content
360
370
  }
371
+ if len(neighbors) > 0:
372
+ decrypted_data['neighborCount'] = len(neighbors)
361
373
  if total_count is not None:
362
374
  decrypted_data['totalNeighborCount'] = total_count
363
375
  else:
@@ -372,7 +384,7 @@ class ResponsePayloadDecoder:
372
384
 
373
385
  # Try all keys as fallback - maybe the key mapping is different
374
386
  if not decryption_success:
375
- for stored_pubkey, stored_privkey in options.key_store.node_keys.items():
387
+ for stored_pubkey, stored_privkey in effective_options.key_store.node_keys.items():
376
388
  # Skip if we already tried this combination
377
389
  if sender_pubkey and stored_pubkey == sender_pubkey:
378
390
  continue
@@ -401,6 +413,27 @@ class ResponsePayloadDecoder:
401
413
  if decryption_result.success and decryption_result.data:
402
414
  decrypted_bytes = decryption_result.data
403
415
  decryption_success = True
416
+ # Parse the decrypted content
417
+ if len(decrypted_bytes) >= 4:
418
+ tag = (
419
+ decrypted_bytes[0] |
420
+ (decrypted_bytes[1] << 8) |
421
+ (decrypted_bytes[2] << 16) |
422
+ (decrypted_bytes[3] << 24)
423
+ )
424
+ content_bytes = decrypted_bytes[4:] if len(decrypted_bytes) > 4 else b''
425
+ parsed_content = ResponsePayloadDecoder._parse_response_content(tag, content_bytes)
426
+ neighbors, total_count = ResponsePayloadDecoder._parse_neighbors(decrypted_bytes, 0)
427
+
428
+ decrypted_data = {
429
+ 'tag': tag,
430
+ 'raw': bytes_to_hex(decrypted_bytes),
431
+ 'content': parsed_content
432
+ }
433
+ if len(neighbors) > 0:
434
+ decrypted_data['neighborCount'] = len(neighbors)
435
+ if total_count is not None:
436
+ decrypted_data['totalNeighborCount'] = total_count
404
437
  break
405
438
  else:
406
439
  if decryption_result.error and "succeeded but MAC" not in decryption_result.error:
@@ -409,13 +442,13 @@ class ResponsePayloadDecoder:
409
442
 
410
443
  # Fallback: try old method if key exchange didn't work
411
444
  if not decryption_success:
412
- for node_pubkey, node_privkey in options.key_store.node_keys.items():
445
+ for node_pubkey, node_privkey in effective_options.key_store.node_keys.items():
413
446
  pubkey_bytes = bytes.fromhex(node_pubkey)
414
447
  if len(pubkey_bytes) > 0:
415
448
  pubkey_first_byte = byte_to_hex(pubkey_bytes[0])
416
449
  should_try = (pubkey_first_byte == source_hash or
417
450
  pubkey_first_byte == destination_hash or
418
- len(options.key_store.node_keys) == 1)
451
+ len(effective_options.key_store.node_keys) == 1)
419
452
 
420
453
  if should_try and not any(m['pubkey'] == node_pubkey[:16] + '...' for m in matching_keys_tried):
421
454
  # Try old fallback methods
@@ -450,14 +483,22 @@ class ResponsePayloadDecoder:
450
483
  (decrypted_bytes[3] << 24)
451
484
  )
452
485
 
453
- # Try to parse neighbor table (GetStats response)
486
+ # Extract content (bytes 4+)
487
+ content_bytes = decrypted_bytes[4:] if len(decrypted_bytes) > 4 else b''
488
+
489
+ # Parse response content to determine type
490
+ parsed_content = ResponsePayloadDecoder._parse_response_content(tag, content_bytes)
491
+
492
+ # Try to parse neighbor table
454
493
  neighbors, total_count = ResponsePayloadDecoder._parse_neighbors(decrypted_bytes, 0)
455
494
 
456
495
  decrypted_data = {
457
496
  'tag': tag,
458
497
  'raw': bytes_to_hex(decrypted_bytes),
459
- 'neighborCount': len(neighbors)
498
+ 'content': parsed_content
460
499
  }
500
+ if len(neighbors) > 0:
501
+ decrypted_data['neighborCount'] = len(neighbors)
461
502
  if total_count is not None:
462
503
  decrypted_data['totalNeighborCount'] = total_count
463
504
 
@@ -471,7 +512,7 @@ class ResponsePayloadDecoder:
471
512
  # (in case of hash collisions or key format issues)
472
513
  if not decryption_success and len(matching_keys_tried) > 0:
473
514
  # We already tried matching keys, now try all remaining keys
474
- for node_pubkey, node_privkey in options.key_store.node_keys.items():
515
+ for node_pubkey, node_privkey in effective_options.key_store.node_keys.items():
475
516
  pubkey_bytes = bytes.fromhex(node_pubkey)
476
517
  if len(pubkey_bytes) > 0:
477
518
  pubkey_first_byte = byte_to_hex(pubkey_bytes[0])
@@ -496,15 +537,23 @@ class ResponsePayloadDecoder:
496
537
  (decrypted_bytes[3] << 24)
497
538
  )
498
539
 
540
+ # Extract content (bytes 4+)
541
+ content_bytes = decrypted_bytes[4:] if len(decrypted_bytes) > 4 else b''
542
+
543
+ # Parse response content to determine type
544
+ parsed_content = ResponsePayloadDecoder._parse_response_content(tag, content_bytes)
545
+
499
546
  # Try to parse neighbor table
500
547
  neighbors, total_count = ResponsePayloadDecoder._parse_neighbors(decrypted_bytes, 0)
501
548
 
502
549
  decrypted_data = {
503
550
  'tag': tag,
504
551
  'raw': bytes_to_hex(decrypted_bytes),
505
- 'neighborCount': len(neighbors),
552
+ 'content': parsed_content,
506
553
  'note': f'Decrypted with key hash {pubkey_first_byte} (did not match source/dest hash)'
507
554
  }
555
+ if len(neighbors) > 0:
556
+ decrypted_data['neighborCount'] = len(neighbors)
508
557
  if total_count is not None:
509
558
  decrypted_data['totalNeighborCount'] = total_count
510
559
 
@@ -515,10 +564,10 @@ class ResponsePayloadDecoder:
515
564
  error_msg = 'Decryption failed'
516
565
  if len(matching_keys_tried) == 0:
517
566
  error_msg += f': No node key found matching source hash ({source_hash}) or destination hash ({destination_hash})'
518
- error_msg += f'. Available keys: {len(options.key_store.node_keys)} key(s) provided'
519
- if len(options.key_store.node_keys) > 0:
567
+ error_msg += f'. Available keys: {len(effective_options.key_store.node_keys)} key(s) provided'
568
+ if len(effective_options.key_store.node_keys) > 0:
520
569
  available_hashes = []
521
- for pk in options.key_store.node_keys.keys():
570
+ for pk in effective_options.key_store.node_keys.keys():
522
571
  try:
523
572
  pk_bytes = bytes.fromhex(pk)
524
573
  if len(pk_bytes) > 0:
@@ -541,6 +590,11 @@ class ResponsePayloadDecoder:
541
590
  if decrypted_data is None:
542
591
  decrypted_data = {'error': 'Decryption was attempted but no result was set. This is a bug.'}
543
592
 
593
+ # Extract tag from decrypted_data if available
594
+ result_tag = tag
595
+ if decrypted_data and 'tag' in decrypted_data:
596
+ result_tag = decrypted_data['tag']
597
+
544
598
  result = ResponsePayload(
545
599
  payload_type=PayloadType.Response,
546
600
  version=PayloadVersion.Version1,
@@ -551,12 +605,20 @@ class ResponsePayloadDecoder:
551
605
  ciphertext=ciphertext,
552
606
  ciphertext_length=len(payload) - 4,
553
607
  decrypted=decrypted_data,
554
- tag=tag,
608
+ tag=result_tag,
555
609
  neighbors=neighbors
556
610
  )
557
611
 
558
- # Attempt decryption if key store is provided
559
- if decryption_options and decryption_options.key_store and decryption_options.attempt_decryption:
612
+ # Attempt decryption if key store is provided (second path - try if first path failed or didn't run)
613
+ # Check if first path succeeded by looking for valid content (not error and not unknown type)
614
+ first_path_succeeded = (
615
+ result.decrypted and
616
+ 'content' in result.decrypted and
617
+ result.decrypted.get('content', {}).get('type') != 'unknown' and
618
+ 'error' not in result.decrypted
619
+ )
620
+
621
+ if not first_path_succeeded and decryption_options and decryption_options.key_store and decryption_options.attempt_decryption:
560
622
  key_store = decryption_options.key_store
561
623
 
562
624
  # Try to decrypt using shared secrets or calculate from node keys
@@ -582,10 +644,13 @@ class ResponsePayloadDecoder:
582
644
  'tag': decryption_result.data['tag'],
583
645
  'content': parsed_content
584
646
  }
647
+ result.tag = decryption_result.data['tag']
585
648
  break # Stop trying once we find a working key
586
649
 
587
650
  # If shared secrets didn't work, try calculating from node keys
588
- if not result.decrypted and node_keys:
651
+ if (not result.decrypted or
652
+ (result.decrypted.get('content', {}).get('type') == 'unknown') or
653
+ 'error' in result.decrypted) and node_keys:
589
654
  destination_hash_byte = hex_to_bytes(destination_hash)[0]
590
655
 
591
656
  # Find our node key that matches destination hash
@@ -629,7 +694,10 @@ class ResponsePayloadDecoder:
629
694
  break
630
695
 
631
696
  # If no peer keys matched by hash, try all peer keys anyway
632
- if not result.decrypted and hasattr(key_store, 'peer_public_keys') and key_store.peer_public_keys:
697
+ if ((not result.decrypted or
698
+ (result.decrypted.get('content', {}).get('type') == 'unknown') or
699
+ 'error' in result.decrypted) and
700
+ hasattr(key_store, 'peer_public_keys') and key_store.peer_public_keys):
633
701
  for peer_pub_key_hex in key_store.peer_public_keys:
634
702
  shared_secret = ChannelCrypto.calculate_shared_secret(
635
703
  peer_pub_key_hex,
@@ -650,8 +718,9 @@ class ResponsePayloadDecoder:
650
718
  'tag': decryption_result.data['tag'],
651
719
  'content': parsed_content
652
720
  }
721
+ result.tag = decryption_result.data['tag']
653
722
  break
654
- if result.decrypted:
723
+ if result.decrypted and result.decrypted.get('content', {}).get('type') != 'unknown':
655
724
  break
656
725
 
657
726
  if options.get('include_segments'):
@@ -119,6 +119,9 @@ class TextMessagePayloadDecoder:
119
119
  value=ciphertext
120
120
  ))
121
121
 
122
+ # Initialize decrypted_data before using it
123
+ decrypted_data: Optional[Dict[str, Any]] = None
124
+
122
125
  result = TextMessagePayload(
123
126
  payload_type=PayloadType.TextMessage,
124
127
  version=PayloadVersion.Version1,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: meshcoredecoder
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Complete Python implementation of the MeshCore Packet Decoder
5
5
  Home-page: https://github.com/chrisdavis2110/meshcore-decoder-py
6
6
  Author: Chris Davis
@@ -190,19 +190,15 @@ The library automatically:
190
190
  ### With Signature Verification
191
191
 
192
192
  ```python
193
- import asyncio
194
193
  from meshcoredecoder import MeshCoreDecoder
195
194
 
196
- # Async verification for Ed25519 signatures
197
- async def verify_packet():
198
- packet = await MeshCoreDecoder.decode_with_verification(hex_data)
195
+ # Verify Ed25519 signatures
196
+ packet = MeshCoreDecoder.decode_with_verification(hex_data)
199
197
 
200
- if packet.payload.get('decoded'):
201
- advert = packet.payload['decoded']
202
- if hasattr(advert, 'signature_valid'):
203
- print(f"Signature Valid: {advert.signature_valid}")
204
-
205
- asyncio.run(verify_packet())
198
+ if packet.payload.get('decoded'):
199
+ advert = packet.payload['decoded']
200
+ if hasattr(advert, 'signature_valid'):
201
+ print(f"Signature Valid: {advert.signature_valid}")
206
202
  ```
207
203
 
208
204
  ## Trace Packets and SNR Analysis
@@ -1,22 +1,22 @@
1
- cli.py,sha256=eyz_PzMTqrDH9heDt9fyLJ_g5m3TG3BZqeVPZQKI74k,51851
2
- index.py,sha256=HP6fvEGgy9Xm1M0E1WKoLjXLj36xUa0Gm2syCI2PXF0,2448
3
- meshcoredecoder/__init__.py,sha256=WMT67Z33IsZM2_zKbUqqW7uielosEiwZg9awFPBrfHQ,275
1
+ cli.py,sha256=bJXnvtgbn_en1KqD6mPtSvGEvpgwVVllISo9952pVmc,51403
2
+ index.py,sha256=ibKxOS2MGPtzbEEjXawcN21M2Qlw3-qCwiQPyyw46Ak,2448
3
+ meshcoredecoder/__init__.py,sha256=UD6zQ-wRynZRuzjRyUi2qkoaBBlKftkfl7xjd88G2ss,275
4
4
  meshcoredecoder/crypto/__init__.py,sha256=00r884_WImNp5YOYfSKYtUaIj6gZdyJV0--xC_Y71Ok,236
5
- meshcoredecoder/crypto/channel_crypto.py,sha256=sNQq-CRr6zVGFOFO0Q7z5kVm7lYHY9fJsBjlSdssjTY,57242
6
- meshcoredecoder/crypto/ed25519_verifier.py,sha256=gndPYcoqnJ35mRdeAHSOzQuEKABd50XeKIWTOK1mKlY,5063
5
+ meshcoredecoder/crypto/channel_crypto.py,sha256=YKcFcD14ToqDhGfNUZwHEEW-kXKB8UP0VRuQWW75h7M,55512
6
+ meshcoredecoder/crypto/ed25519_verifier.py,sha256=9DAx0gqnf9I7fPxfKU4G1y0GbJK1stCtTKpCX4foL5k,5057
7
7
  meshcoredecoder/crypto/key_manager.py,sha256=FXABZBd1B0kQwpyg7EX-pZDqxh5KVKnlB7A1FE3NQeU,5034
8
8
  meshcoredecoder/decoder/__init__.py,sha256=P_E5CQS1eXoVy59A1mAV9TD5XCS6FpQpc4RizhOZVrw,654
9
- meshcoredecoder/decoder/packet_decoder.py,sha256=nHrdej--PbaIqxVx2AMpxxIeQdeniW8z_3_UnXsxzM4,24351
9
+ meshcoredecoder/decoder/packet_decoder.py,sha256=eNiOQdfUWU1Sb0mbo94Ox2CFMxz01XLwCm1mjtBdNwY,24351
10
10
  meshcoredecoder/decoder/payload_decoders/__init__.py,sha256=DGuu2SfDuAEg8hu9V6iWcxyXOUoen816SqcdZgVzHmU,778
11
11
  meshcoredecoder/decoder/payload_decoders/ack.py,sha256=W6JgF6ylf-Y5IWW33P-_EHTz5GEYY_-ng_aUxvDdHac,3299
12
- meshcoredecoder/decoder/payload_decoders/advert.py,sha256=EMr1sQKfrF1e3GohtC2_XbmusicNGxfPNryvfzV1eh8,12639
12
+ meshcoredecoder/decoder/payload_decoders/advert.py,sha256=OiOvjD2Db6d5GPA0Og2j7BQReGWLhiv6OcoyOtzZWOg,12627
13
13
  meshcoredecoder/decoder/payload_decoders/anon_request.py,sha256=IhoQLnC7_7MDbdZLtFjcBBbAbQ-EC9k6JFfirhct3wg,7839
14
14
  meshcoredecoder/decoder/payload_decoders/group_data.py,sha256=llDm6lXDYqM_3udSz7lOtKCfHR39hUa5zivyfs21B_U,5435
15
15
  meshcoredecoder/decoder/payload_decoders/group_text.py,sha256=BhdF1ZYrMS_UH7-xRxeNHU1WvgNf2Buk9SxpDN0YYcQ,5526
16
16
  meshcoredecoder/decoder/payload_decoders/path.py,sha256=MTptEthcN9R9r9KJf6Y40AWoZI54_vVlqBvXyAywrXk,13791
17
17
  meshcoredecoder/decoder/payload_decoders/request.py,sha256=eYA_rxrEKZa1gS7pMGWMb6I_0F89vRoMW23b_3-nx_0,18601
18
- meshcoredecoder/decoder/payload_decoders/response.py,sha256=RUAPC5jx-0R2W0l1b7BNwCqPiYqIyHljdI_72gmSDCQ,56765
19
- meshcoredecoder/decoder/payload_decoders/text_message.py,sha256=sU4BH3bzbBDmxDYjX4N-1YWlOqx0kNOpwkSfsnYF26g,10368
18
+ meshcoredecoder/decoder/payload_decoders/response.py,sha256=UP5yLbHrQjwn9azf3lVDRQdxQ1Fh4s2nB4OgRyrDUrs,61351
19
+ meshcoredecoder/decoder/payload_decoders/text_message.py,sha256=D1uTlw5UW4C8VZRt0hQiPdpFHABJbl3J3wBX90b11wU,10485
20
20
  meshcoredecoder/decoder/payload_decoders/trace.py,sha256=eN3E_5oidZzGdNsr--PhxtwYAwLW0lMJDGHz09lDqzA,6110
21
21
  meshcoredecoder/types/__init__.py,sha256=XReL92twDsQQf8GUxYbPEdZGlV8XweQCPT-43jn8IfA,640
22
22
  meshcoredecoder/types/crypto.py,sha256=o7C7IsiwMtJjzIUYRw548-AJmm898ucLDy1xYVukreE,1842
@@ -27,9 +27,9 @@ meshcoredecoder/utils/__init__.py,sha256=0_EpRPd97R2Cead_BTG9SDS6vVZV268u3XBkA-s
27
27
  meshcoredecoder/utils/auth_token.py,sha256=gVVgHH_Am1k-cZxPbrTHCafvqdWSqlg9Dw-RRYaRI8Y,6973
28
28
  meshcoredecoder/utils/enum_names.py,sha256=6cSkbxexW8PT4MkwvWUA-oHQCvELUN2o3alIbp8bkP0,1936
29
29
  meshcoredecoder/utils/hex.py,sha256=IjDuoeIAr7swv9Fa1NKstZTotTwmtufdi_psCjqVU5k,1136
30
- meshcoredecoder-0.2.1.dist-info/licenses/LICENSE,sha256=W4bNA8wxOTF7Wmcmi5UwjrrKnjT_Qua52Z5wQLPLfKM,1130
31
- meshcoredecoder-0.2.1.dist-info/METADATA,sha256=LUo8N2Q54CfUJVETmtH2TAgx4mVj8QLnxkIbmUjg4h0,30785
32
- meshcoredecoder-0.2.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
33
- meshcoredecoder-0.2.1.dist-info/entry_points.txt,sha256=P8cgSHWETiDCc2jRCB95PuVyJDDeSq0gH-ufYVlqWDY,45
34
- meshcoredecoder-0.2.1.dist-info/top_level.txt,sha256=Rj9ZjVG2I6CEgpgF8I_QqUDp-vTQEdYm2KD93mIGkJM,26
35
- meshcoredecoder-0.2.1.dist-info/RECORD,,
30
+ meshcoredecoder-0.2.3.dist-info/licenses/LICENSE,sha256=W4bNA8wxOTF7Wmcmi5UwjrrKnjT_Qua52Z5wQLPLfKM,1130
31
+ meshcoredecoder-0.2.3.dist-info/METADATA,sha256=GNlSaQ4Tn89WFE5zNx05a5SS_n4-JM1dRaTUgXoFlhY,30671
32
+ meshcoredecoder-0.2.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
33
+ meshcoredecoder-0.2.3.dist-info/entry_points.txt,sha256=P8cgSHWETiDCc2jRCB95PuVyJDDeSq0gH-ufYVlqWDY,45
34
+ meshcoredecoder-0.2.3.dist-info/top_level.txt,sha256=Rj9ZjVG2I6CEgpgF8I_QqUDp-vTQEdYm2KD93mIGkJM,26
35
+ meshcoredecoder-0.2.3.dist-info/RECORD,,