Fixes for short strings, added raise-on-failed-validation procs

This commit is contained in:
coffeepots 2018-07-31 18:14:20 +01:00 committed by zah
parent 723ef3cf70
commit 4773559739

View File

@ -38,10 +38,10 @@ template isHexChar*(c: char): bool =
else: true else: true
proc validateHexQuantity*(value: string): bool = proc validateHexQuantity*(value: string): bool =
if not value.hasHexHeader: if value.len < 3 or not value.hasHexHeader:
return false return false
# No leading zeros # No leading zeros (but allow 0x0)
if value[2] == '0': return false if value.len > 3 and value[2] == '0': return false
for i in 2 ..< value.len: for i in 2 ..< value.len:
let c = value[i] let c = value[i]
if not c.isHexChar: if not c.isHexChar:
@ -49,7 +49,7 @@ proc validateHexQuantity*(value: string): bool =
return true return true
proc validateHexData*(value: string): bool = proc validateHexData*(value: string): bool =
if not value.hasHexHeader: if value.len < 3 or not value.hasHexHeader:
return false return false
# Must be even number of digits # Must be even number of digits
if value.len mod 2 != 0: return false if value.len mod 2 != 0: return false
@ -60,18 +60,26 @@ proc validateHexData*(value: string): bool =
return false return false
return true return true
const
SInvalidQuantity = "Invalid hex quantity format for Ethereum"
SInvalidData = "Invalid hex data format for Ethereum"
proc validateRaiseHexQuantity*(value: string) =
if not value.validateHexQuantity:
raise newException(ValueError, SInvalidQuantity & ": " & value)
proc validateRaiseHexData*(value: string) =
if not value.validateHexData:
raise newException(ValueError, SInvalidData & ": " & value)
# Initialisation # Initialisation
proc hexQuantityStr*(value: string): HexQuantityStr = proc hexQuantityStr*(value: string): HexQuantityStr =
if not value.validateHexQuantity: value.validateRaiseHexQuantity
raise newException(ValueError, "Invalid hex quantity format for Ethereum: " & value)
else:
result = value.HexQuantityStr result = value.HexQuantityStr
proc hexDataStr*(value: string): HexDataStr = proc hexDataStr*(value: string): HexDataStr =
if not value.validateHexData: value.validateRaiseHexData
raise newException(ValueError, "Invalid hex data format for Ethereum: " & value)
else:
result = value.HexDataStr result = value.HexDataStr
# Converters for use in RPC # Converters for use in RPC