1
0

bitcoin.py: make int_to_hex throw on overflow

This commit is contained in:
SomberNight
2018-06-16 02:34:27 +02:00
parent 79f4a8bae9
commit 1a8e8bc047
2 changed files with 29 additions and 3 deletions

View File

@@ -50,12 +50,18 @@ def rev_hex(s):
return bh2u(bfh(s)[::-1])
def int_to_hex(i, length=1):
def int_to_hex(i: int, length: int=1) -> str:
"""Converts int to little-endian hex string.
`length` is the number of bytes available
"""
if not isinstance(i, int):
raise TypeError('{} instead of int'.format(i))
range_size = pow(256, length)
if i < -range_size/2 or i >= range_size:
raise OverflowError('cannot convert int {} to hex ({} bytes)'.format(i, length))
if i < 0:
# two's complement
i = pow(256, length) + i
i = range_size + i
s = hex(i)[2:].rstrip('L')
s = "0"*(2*length - len(s)) + s
return rev_hex(s)