Added EthAddressStr to validation

This commit is contained in:
coffeepots 2018-08-13 17:33:57 +01:00
parent 3c0d27021e
commit e4d1c6817a
1 changed files with 30 additions and 1 deletions

View File

@ -13,6 +13,11 @@
type
HexQuantityStr* = distinct string
HexDataStr* = distinct string
EthAddressStr* = distinct string
func len*(data: HexQuantityStr): int = data.string.len
func len*(data: HexDataStr): int = data.string.len
func len*(data: EthAddressStr): int = data.string.len
# Hex validation
@ -60,9 +65,14 @@ func isValidHexData*(value: string): bool =
return false
return true
func isValidEthAddress*(value: string): bool =
# 20 bytes for EthAddress plus "0x"
result = value.len <= 42 and value.isValidHexData
const
SInvalidQuantity = "Invalid hex quantity format for Ethereum"
SInvalidData = "Invalid hex data format for Ethereum"
SInvalidAddress = "Invalid address format for Ethereum"
proc validateHexQuantity*(value: string) {.inline.} =
if unlikely(not value.isValidHexQuantity):
@ -72,6 +82,10 @@ proc validateHexData*(value: string) {.inline.} =
if unlikely(not value.isValidHexData):
raise newException(ValueError, SInvalidData & ": " & value)
proc validateHexAddressStr*(value: string) {.inline.} =
if unlikely(not value.isValidEthAddress):
raise newException(ValueError, SInvalidAddress & ": " & value)
# Initialisation
proc hexQuantityStr*(value: string): HexQuantityStr {.inline.} =
@ -82,6 +96,10 @@ proc hexDataStr*(value: string): HexDataStr {.inline.} =
value.validateHexData
result = value.HexDataStr
proc ethAddressStr*(value: string): EthAddressStr {.inline.} =
value.validateHexAddressStr
result = value.EthAddressStr
# Converters for use in RPC
import json
@ -93,6 +111,9 @@ proc `%`*(value: HexQuantityStr): JsonNode =
proc `%`*(value: HexDataStr): JsonNode =
result = %(value.string)
proc `%`*(value: EthAddressStr): JsonNode =
result = %(value.string)
proc fromJson*(n: JsonNode, argName: string, result: var HexQuantityStr) =
# Note that '0x' is stripped after validation
n.kind.expect(JString, argName)
@ -106,6 +127,14 @@ proc fromJson*(n: JsonNode, argName: string, result: var HexDataStr) =
n.kind.expect(JString, argName)
let hexStr = n.getStr()
if not hexStr.isValidHexData:
raise newException(ValueError, "Parameter \"" & argName & "\" is not valid as a Ethereum data \"" & hexStr & "\"")
raise newException(ValueError, "Parameter \"" & argName & "\" is not valid as Ethereum data \"" & hexStr & "\"")
result = hexStr.hexDataStr
proc fromJson*(n: JsonNode, argName: string, result: var EthAddressStr) =
# Note that '0x' is stripped after validation
n.kind.expect(JString, argName)
let hexStr = n.getStr()
if not hexStr.isValidEthAddress:
raise newException(ValueError, "Parameter \"" & argName & "\" is not valid as an Ethereum address \"" & hexStr & "\"")
result = hexStr.EthAddressStr