From 40b96e2d3c7a92cfbdbe5cf65bebc3a97e9fb410 Mon Sep 17 00:00:00 2001 From: kdeme Date: Tue, 4 Feb 2020 11:15:01 +0100 Subject: [PATCH] Check range on deserialising enum --- eth/rlp.nim | 6 +++++- tests/rlp/test_api_usage.nim | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/eth/rlp.nim b/eth/rlp.nim index 82107f7..eb86328 100644 --- a/eth/rlp.nim +++ b/eth/rlp.nim @@ -304,7 +304,11 @@ proc readImpl(rlp: var Rlp, T: type Integer): Integer = rlp.skipElem proc readImpl(rlp: var Rlp, T: type[enum]): T = - result = type(result)(rlp.toInt(int)) + let value = rlp.toInt(int) + if value < ord(T.low) or value > ord(T.high): + raise newException(RlpTypeMismatch, + "Enum expected, but the source RLP is not in valid range.") + result = type(result)(value) rlp.skipElem proc readImpl(rlp: var Rlp, T: type bool): T = diff --git a/tests/rlp/test_api_usage.nim b/tests/rlp/test_api_usage.nim index ef08dbc..acb7d18 100644 --- a/tests/rlp/test_api_usage.nim +++ b/tests/rlp/test_api_usage.nim @@ -194,3 +194,19 @@ test "encode/decode floats": chk f chk -f +test "invalid enum": + type + MyEnum = enum + foo, + bar + + var writer = initRlpWriter() + writer.append(2) + writer.append(-1) + let bytes = writer.finish() + var rlp = rlpFromBytes(bytes.toRange) + expect RlpTypeMismatch: + discard rlp.read(MyEnum) + rlp.skipElem() + expect RlpTypeMismatch: + discard rlp.read(MyEnum)