Skip to content

Commit

Permalink
Fix a rare bug of Overflow error
Browse files Browse the repository at this point in the history
  • Loading branch information
ebellocchia committed Feb 13, 2024
1 parent f4336fc commit ec68738
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 14 additions & 1 deletion bip_utils/utils/misc/integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,19 @@
class IntegerUtils:
"""Class container for integer utility functions."""

@staticmethod
def GetBytesNumber(data_int: int) -> int:
"""
Get the number of bytes of the specified integer.
Args:
data_int (int): Data integer
Returns:
int: Number of bytes
"""
return ((data_int.bit_length() if data_int > 0 else 1) + 7) // 8

@staticmethod
def ToBytes(data_int: int,
bytes_num: Optional[int] = None,
Expand All @@ -52,7 +65,7 @@ def ToBytes(data_int: int,
if data_int.__class__.__name__ == "mpz":
data_int = int(data_int)

bytes_num = bytes_num or ((data_int.bit_length() if data_int > 0 else 1) + 7) // 8
bytes_num = bytes_num or IntegerUtils.GetBytesNumber(data_int)
return data_int.to_bytes(bytes_num, byteorder=endianness, signed=signed)

@staticmethod
Expand Down
5 changes: 4 additions & 1 deletion bip_utils/utils/mnemonic/mnemonic_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ def WordsToBytesChunk(word1: str,
# Get back the bytes chunk
int_chunk = word1_idx + (n * ((word2_idx - word1_idx) % n)) + (n * n * ((word3_idx - word2_idx) % n))

return IntegerUtils.ToBytes(int_chunk, bytes_num=4, endianness=endianness)
if IntegerUtils.GetBytesNumber(int_chunk) > 3:
return IntegerUtils.ToBytes(int_chunk, endianness=endianness)
else:
return IntegerUtils.ToBytes(int_chunk, bytes_num=4, endianness=endianness)


class MnemonicWordsList:
Expand Down

0 comments on commit ec68738

Please sign in to comment.