Skip to content

Commit f869a79

Browse files
authored
gossipsub: small refactor (leanEthereum#70)
* gossipsub: small refactor * fmt * small doc fix * trigger ci
1 parent 61145a0 commit f869a79

1 file changed

Lines changed: 18 additions & 22 deletions

File tree

src/lean_spec/subspecs/networking/gossipsub.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -110,30 +110,31 @@ def id(self) -> MessageId:
110110
if self._id is not None:
111111
return self._id
112112

113-
domain: bytes
114-
data_for_hash: bytes
115-
113+
# Determine domain and data based on snappy decompression
116114
if self._snappy_decompress:
117115
try:
118116
# Try to decompress the data with snappy
119117
decompressed_data = self._snappy_decompress(self.raw_data)
120118
# Valid snappy decompression - use valid domain
121-
domain = MESSAGE_DOMAIN_VALID_SNAPPY
122-
data_for_hash = decompressed_data
119+
domain, data_for_hash = (
120+
MESSAGE_DOMAIN_VALID_SNAPPY,
121+
decompressed_data,
122+
)
123123
except Exception:
124124
# Invalid snappy decompression - use invalid domain
125-
domain = MESSAGE_DOMAIN_INVALID_SNAPPY
126-
data_for_hash = self.raw_data
125+
domain, data_for_hash = (
126+
MESSAGE_DOMAIN_INVALID_SNAPPY,
127+
self.raw_data,
128+
)
127129
else:
128130
# No decompressor provided - use invalid domain
129-
domain = MESSAGE_DOMAIN_INVALID_SNAPPY
130-
data_for_hash = self.raw_data
131-
132-
# The internal computation returns the raw bytes...
133-
computed_id_bytes = self._compute_raw_id(domain, data_for_hash)
131+
domain, data_for_hash = (
132+
MESSAGE_DOMAIN_INVALID_SNAPPY,
133+
self.raw_data,
134+
)
134135

135-
# We then cast to our strict NewType before caching and returning.
136-
self._id = MessageId(computed_id_bytes)
136+
# Compute the raw ID bytes and cast to our strict type before caching
137+
self._id = MessageId(self._compute_raw_id(domain, data_for_hash))
137138
return self._id
138139

139140
def _compute_raw_id(self, domain: bytes, message_data: bytes) -> bytes:
@@ -147,12 +148,7 @@ def _compute_raw_id(self, domain: bytes, message_data: bytes) -> bytes:
147148
Returns:
148149
A 20-byte raw bytes digest.
149150
"""
150-
# Encode the topic length as little-endian bytes
151-
topic_len_bytes = len(self.topic).to_bytes(8, "little")
152-
153-
# Concatenate all components for hashing
154-
data_to_hash = domain + topic_len_bytes + self.topic + message_data
155-
151+
# Concatenate all components: domain + topic_len + topic + data
152+
data_to_hash = domain + len(self.topic).to_bytes(8, "little") + self.topic + message_data
156153
# Compute SHA256 and take the first 20 bytes
157-
digest = hashlib.sha256(data_to_hash).digest()
158-
return digest[:20]
154+
return hashlib.sha256(data_to_hash).digest()[:20]

0 commit comments

Comments
 (0)