Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply strict enum checking #1254

Merged
merged 18 commits into from
Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions neo.UnitTests/UT_Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ public void TestUnmapForIPEndPoin()
endPoint2.Unmap().Should().Be(endPoint);
}

[TestMethod]
public void TestStrictEnum()
{
TestEnum te = Helper.StrictEnum<TestEnum>(0x1);
te.Should().Be(TestEnum.ENTRY1);

Action action = () => Helper.StrictEnum<TestEnum>(0x2);
action.Should().Throw<ArgumentOutOfRangeException>();
}

[TestMethod]
public void TestWeightedAverage()
{
Expand Down Expand Up @@ -282,6 +292,11 @@ private static void CheckArgumentNullException(double start, double end, Func<Wo
}).WeightedAverage(p => p.Weight, p => p.Weight);
action.Should().Throw<ArgumentNullException>();
}

internal enum TestEnum : byte
{
ENTRY1 = 0x1
}
}

class Foo
Expand Down
2 changes: 1 addition & 1 deletion neo/Consensus/ChangeView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public override void Deserialize(BinaryReader reader)
{
base.Deserialize(reader);
Timestamp = reader.ReadUInt64();
Reason = (ChangeViewReason)reader.ReadByte();
Reason = Helper.StrictEnum<ChangeViewReason>(reader.ReadByte());
}

public override void Serialize(BinaryWriter writer)
Expand Down
2 changes: 1 addition & 1 deletion neo/Consensus/ConsensusMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ protected ConsensusMessage(ConsensusMessageType type)

public virtual void Deserialize(BinaryReader reader)
{
if (Type != (ConsensusMessageType)reader.ReadByte())
if (Type != Helper.StrictEnum<ConsensusMessageType>(reader.ReadByte()))
throw new FormatException();
ViewNumber = reader.ReadByte();
}
Expand Down
13 changes: 13 additions & 0 deletions neo/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -320,5 +320,18 @@ public static IConfigurationRoot LoadConfig(string config)
.AddJsonFile(configFile, true)
.Build();
}

public static T StrictEnum<T>(byte value) where T : Enum
{
T state = (T)Enum.ToObject(typeof(T), value);
if (!EnumValueCache<T>.definedValues.Contains(state))
throw new ArgumentOutOfRangeException();
ixje marked this conversation as resolved.
Show resolved Hide resolved
return state;
}

private static class EnumValueCache<T> where T : Enum
{
public static readonly HashSet<T> definedValues = new HashSet<T>((T[])Enum.GetValues(typeof(T)));
}
ixje marked this conversation as resolved.
Show resolved Hide resolved
}
}
4 changes: 2 additions & 2 deletions neo/Network/P2P/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private void DecompressPayload()
void ISerializable.Deserialize(BinaryReader reader)
{
Flags = (MessageFlags)reader.ReadByte();
Command = (MessageCommand)reader.ReadByte();
Command = Neo.Helper.StrictEnum<MessageCommand>(reader.ReadByte());
_payload_compressed = reader.ReadVarBytes(PayloadMaxSize);
DecompressPayload();
}
Expand Down Expand Up @@ -149,7 +149,7 @@ internal static int TryDeserialize(ByteString data, out Message msg)
msg = new Message()
{
Flags = flags,
Command = (MessageCommand)header[1],
Command = Neo.Helper.StrictEnum<MessageCommand>(header[1]),
_payload_compressed = length <= 0 ? new byte[0] : data.Slice(payloadIndex, (int)length).ToArray()
};
msg.DecompressPayload();
Expand Down
2 changes: 1 addition & 1 deletion neo/Network/P2P/Payloads/Cosigner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public Cosigner()
void ISerializable.Deserialize(BinaryReader reader)
{
Account = reader.ReadSerializable<UInt160>();
Scopes = (WitnessScope)reader.ReadByte();
Scopes = Neo.Helper.StrictEnum<WitnessScope>(reader.ReadByte());
AllowedContracts = Scopes.HasFlag(WitnessScope.CustomContracts)
? reader.ReadSerializableArray<UInt160>(MaxSubitems)
: new UInt160[0];
Expand Down
4 changes: 1 addition & 3 deletions neo/Network/P2P/Payloads/InvPayload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ public static IEnumerable<InvPayload> CreateGroup(InventoryType type, UInt256[]

void ISerializable.Deserialize(BinaryReader reader)
{
Type = (InventoryType)reader.ReadByte();
if (!Enum.IsDefined(typeof(InventoryType), Type))
throw new FormatException();
Type = Neo.Helper.StrictEnum<InventoryType>(reader.ReadByte());
Hashes = reader.ReadSerializableArray<UInt256>(MaxHashesCount);
}

Expand Down
6 changes: 2 additions & 4 deletions neo/Network/P2P/Payloads/TransactionAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ public class TransactionAttribute : ISerializable

void ISerializable.Deserialize(BinaryReader reader)
{
Usage = (TransactionAttributeUsage)reader.ReadByte();
if (!Enum.IsDefined(typeof(TransactionAttributeUsage), Usage))
throw new FormatException();
Usage = Neo.Helper.StrictEnum<TransactionAttributeUsage>(reader.ReadByte());
Data = reader.ReadVarBytes(252);
}

Expand All @@ -37,7 +35,7 @@ public JObject ToJson()
public static TransactionAttribute FromJson(JObject json)
{
TransactionAttribute transactionAttribute = new TransactionAttribute();
transactionAttribute.Usage = (TransactionAttributeUsage)(byte.Parse(json["usage"].AsString()));
transactionAttribute.Usage = Neo.Helper.StrictEnum<TransactionAttributeUsage>(byte.Parse(json["usage"].AsString()));
transactionAttribute.Data = Convert.FromBase64String(json["data"].AsString());
return transactionAttribute;
}
Expand Down
2 changes: 1 addition & 1 deletion neo/SmartContract/Manifest/ContractParameterDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static ContractParameterDefinition FromJson(JObject json)
return new ContractParameterDefinition
{
Name = json["name"].AsString(),
Type = (ContractParameterType)Enum.Parse(typeof(ContractParameterType), json["type"].AsString()),
Type = (ContractParameterType)Enum.Parse(typeof(ContractParameterType), json["type"].AsString())
};
}

Expand Down
2 changes: 1 addition & 1 deletion neo/Wallets/SQLite/VerificationContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class VerificationContract : SmartContract.Contract, IEquatable<Verificat
public void Deserialize(BinaryReader reader)
{
reader.ReadSerializable<UInt160>();
ParameterList = reader.ReadVarBytes().Select(p => (ContractParameterType)p).ToArray();
ParameterList = reader.ReadVarBytes().Select(p => Neo.Helper.StrictEnum<ContractParameterType>(p)).ToArray();
Script = reader.ReadVarBytes();
}

Expand Down