Skip to content

Commit 511ddfd

Browse files
committed
fix codacy errors
Signed-off-by: nadine.loepfe <[email protected]>
1 parent d1034ec commit 511ddfd

File tree

2 files changed

+74
-40
lines changed

2 files changed

+74
-40
lines changed

src/hiero_sdk_python/consensus/topic_message.py

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from datetime import datetime
2-
from typing import Optional, List, Union
2+
from typing import Optional, List, Union, Dict
33
from hiero_sdk_python.hapi.mirror import consensus_service_pb2 as mirror_proto
44

55
def _to_datetime(ts_proto) -> datetime:
@@ -30,16 +30,26 @@ class TopicMessage:
3030
def __init__(
3131
self,
3232
consensus_timestamp: datetime,
33-
contents: bytes,
34-
running_hash: bytes,
35-
sequence_number: int,
33+
message_data: Dict[str, Union[bytes, int]],
3634
chunks: List[TopicMessageChunk],
3735
transaction_id: Optional[str] = None,
3836
):
37+
"""
38+
Args:
39+
consensus_timestamp: The final consensus timestamp.
40+
message_data: Dict with required fields:
41+
{
42+
"contents": bytes,
43+
"running_hash": bytes,
44+
"sequence_number": int
45+
}
46+
chunks: All individual chunks that form this message.
47+
transaction_id: The transaction ID string if available.
48+
"""
3949
self.consensus_timestamp = consensus_timestamp
40-
self.contents = contents
41-
self.running_hash = running_hash
42-
self.sequence_number = sequence_number
50+
self.contents = message_data["contents"]
51+
self.running_hash = message_data["running_hash"]
52+
self.sequence_number = message_data["sequence_number"]
4353
self.chunks = chunks
4454
self.transaction_id = transaction_id
4555

@@ -52,7 +62,7 @@ def of_single(cls, response: mirror_proto.ConsensusTopicResponse) -> "TopicMessa
5262
consensus_timestamp = chunk.consensus_timestamp
5363
contents = response.message
5464
running_hash = response.runningHash
55-
sequence_number = response.sequence_number
65+
sequence_number = chunk.sequence_number
5666

5767
transaction_id = None
5868
if response.HasField("chunkInfo") and response.chunkInfo.HasField("initialTransactionID"):
@@ -64,9 +74,11 @@ def of_single(cls, response: mirror_proto.ConsensusTopicResponse) -> "TopicMessa
6474

6575
return cls(
6676
consensus_timestamp,
67-
contents,
68-
running_hash,
69-
sequence_number,
77+
{
78+
"contents": contents,
79+
"running_hash": running_hash,
80+
"sequence_number": sequence_number,
81+
},
7082
[chunk],
7183
transaction_id
7284
)
@@ -87,9 +99,11 @@ def of_many(cls, responses: List[mirror_proto.ConsensusTopicResponse]) -> "Topic
8799
chunks.append(c)
88100
total_size += len(r.message)
89101

90-
if (transaction_id is None
102+
if (
103+
transaction_id is None
91104
and r.HasField("chunkInfo")
92-
and r.chunkInfo.HasField("initialTransactionID")):
105+
and r.chunkInfo.HasField("initialTransactionID")
106+
):
93107
tx_id = r.chunkInfo.initialTransactionID
94108
transaction_id = (
95109
f"{tx_id.shardNum}.{tx_id.realmNum}.{tx_id.accountNum}-"
@@ -110,9 +124,11 @@ def of_many(cls, responses: List[mirror_proto.ConsensusTopicResponse]) -> "Topic
110124

111125
return cls(
112126
consensus_timestamp,
113-
bytes(contents),
114-
running_hash,
115-
sequence_number,
127+
{
128+
"contents": bytes(contents),
129+
"running_hash": running_hash,
130+
"sequence_number": sequence_number,
131+
},
116132
chunks,
117133
transaction_id
118134
)
@@ -131,14 +147,7 @@ def from_proto(
131147
If chunking is enabled and multiple chunks are detected, they are reassembled
132148
into one combined TopicMessage. Otherwise, a single chunk is returned as-is.
133149
"""
134-
if isinstance(response_or_responses, mirror_proto.ConsensusTopicResponse):
135-
response = response_or_responses
136-
if chunking_enabled and response.HasField("chunkInfo") and response.chunkInfo.total > 1:
137-
raise ValueError(
138-
"Cannot handle multi-chunk in a single response. Pass all chunk responses in a list."
139-
)
140-
return cls.of_single(response)
141-
else:
150+
if not isinstance(response_or_responses, mirror_proto.ConsensusTopicResponse):
142151
if not response_or_responses:
143152
raise ValueError("Empty response list provided to from_proto().")
144153

@@ -147,6 +156,13 @@ def from_proto(
147156

148157
return cls.of_many(response_or_responses)
149158

159+
response = response_or_responses
160+
if chunking_enabled and response.HasField("chunkInfo") and response.chunkInfo.total > 1:
161+
raise ValueError(
162+
"Cannot handle multi-chunk in a single response. Pass all chunk responses in a list."
163+
)
164+
return cls.of_single(response)
165+
150166
def __str__(self):
151167
contents_str = self.contents.decode("utf-8", errors="replace")
152168
return (

src/hiero_sdk_python/crypto/private_key.py

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from cryptography.hazmat.primitives.asymmetric import ed25519, ec
22
from cryptography.hazmat.primitives import serialization
33
from cryptography.hazmat.backends import default_backend
4-
from typing import Union
4+
from typing import Optional, Union
55
from hiero_sdk_python.crypto.public_key import PublicKey
66

77
class PrivateKey:
@@ -60,30 +60,48 @@ def from_bytes(cls, key_bytes: bytes) -> "PrivateKey":
6060
If the key is DER-encoded, tries to parse Ed25519 vs ECDSA.
6161
"""
6262
if len(key_bytes) == 32:
63-
try:
64-
ed_priv = ed25519.Ed25519PrivateKey.from_private_bytes(key_bytes)
63+
ed_priv = cls._try_load_ed25519(key_bytes)
64+
if ed_priv:
6565
return cls(ed_priv)
66-
except Exception:
67-
pass
6866

69-
try:
70-
private_int = int.from_bytes(key_bytes, "big")
71-
ec_priv = ec.derive_private_key(private_int, ec.SECP256K1(), default_backend())
67+
ec_priv = cls._try_load_ecdsa(key_bytes)
68+
if ec_priv:
7269
return cls(ec_priv)
73-
except Exception:
74-
pass
7570

71+
der_key = cls._try_load_der(key_bytes)
72+
if der_key:
73+
return cls(der_key)
74+
75+
raise ValueError("Failed to load private key from bytes.")
76+
77+
@staticmethod
78+
def _try_load_ed25519(key_bytes: bytes) -> Optional[ed25519.Ed25519PrivateKey]:
79+
try:
80+
return ed25519.Ed25519PrivateKey.from_private_bytes(key_bytes)
81+
except Exception:
82+
return None
83+
84+
@staticmethod
85+
def _try_load_ecdsa(key_bytes: bytes) -> Optional[ec.EllipticCurvePrivateKey]:
86+
try:
87+
private_int = int.from_bytes(key_bytes, "big")
88+
return ec.derive_private_key(private_int, ec.SECP256K1(), default_backend())
89+
except Exception:
90+
return None
91+
92+
@staticmethod
93+
def _try_load_der(key_bytes: bytes) -> Optional[Union[ed25519.Ed25519PrivateKey, ec.EllipticCurvePrivateKey]]:
7694
try:
7795
private_key = serialization.load_der_private_key(key_bytes, password=None)
7896
if isinstance(private_key, ed25519.Ed25519PrivateKey):
79-
return cls(private_key)
97+
return private_key
8098
if isinstance(private_key, ec.EllipticCurvePrivateKey):
8199
if not isinstance(private_key.curve, ec.SECP256K1):
82100
raise ValueError("Only secp256k1 ECDSA is supported.")
83-
return cls(private_key)
84-
raise ValueError("Unsupported private key type.")
85-
except Exception as e:
86-
raise ValueError(f"Failed to load private key (DER): {e}")
101+
return private_key
102+
return None
103+
except Exception:
104+
return None
87105

88106
def sign(self, data: bytes) -> bytes:
89107
return self._private_key.sign(data)
@@ -130,4 +148,4 @@ def is_ecdsa(self) -> bool:
130148
def __repr__(self):
131149
if self.is_ed25519():
132150
return f"<PrivateKey (Ed25519) hex={self.to_string_raw()}>"
133-
return f"<PrivateKey (ECDSA) hex={self.to_string_raw()}>"
151+
return f"<PrivateKey (ECDSA) hex={self.to_string_raw()}>"

0 commit comments

Comments
 (0)