From 16c122342353f76cd7c0d6ffb83266b6a91172c2 Mon Sep 17 00:00:00 2001 From: Erik Zhang Date: Fri, 22 Nov 2019 20:38:54 +0800 Subject: [PATCH] Improve p2p message deserialization (#1262) --- .../IO/Caching/UT_ReflectionCache.cs | 51 ++++++------- neo/Consensus/ConsensusMessage.cs | 18 +---- neo/IO/Caching/ReflectionCache.cs | 74 +++++-------------- neo/IO/Caching/ReflectionCacheAttribute.cs | 5 +- neo/Network/P2P/Message.cs | 48 +----------- neo/Network/P2P/MessageCommand.cs | 19 +++++ 6 files changed, 71 insertions(+), 144 deletions(-) diff --git a/neo.UnitTests/IO/Caching/UT_ReflectionCache.cs b/neo.UnitTests/IO/Caching/UT_ReflectionCache.cs index 4e1fcce634..547c18787d 100644 --- a/neo.UnitTests/IO/Caching/UT_ReflectionCache.cs +++ b/neo.UnitTests/IO/Caching/UT_ReflectionCache.cs @@ -1,11 +1,17 @@ +using System.IO; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; using Neo.IO.Caching; -using System; namespace Neo.UnitTests.IO.Caching { - public class TestItem { } + public class TestItem : ISerializable + { + public int Size => 0; + public void Deserialize(BinaryReader reader) { } + public void Serialize(BinaryWriter writer) { } + } public class TestItem1 : TestItem { } @@ -25,44 +31,35 @@ public enum MyEmptyEnum : byte { } [TestClass] public class UT_ReflectionCache { - ReflectionCache reflectionCache; - - [TestInitialize] - public void SetUp() - { - reflectionCache = ReflectionCache.CreateFromEnum(); - } - [TestMethod] - public void TestCreateFromEnum() + public void TestCreateFromEmptyEnum() { - reflectionCache.Should().NotBeNull(); + ReflectionCache.Count.Should().Be(0); } [TestMethod] - public void TestCreateFromObjectNotEnum() + public void TestCreateInstance() { - Action action = () => ReflectionCache.CreateFromEnum(); - action.Should().Throw(); - } + object item1 = ReflectionCache.CreateInstance(MyTestEnum.Item1, null); + (item1 is TestItem1).Should().BeTrue(); - [TestMethod] - public void TestCreateFromEmptyEnum() - { - reflectionCache = ReflectionCache.CreateFromEnum(); - reflectionCache.Count.Should().Be(0); + object item2 = ReflectionCache.CreateInstance(MyTestEnum.Item2, null); + (item2 is TestItem2).Should().BeTrue(); + + object item3 = ReflectionCache.CreateInstance((MyTestEnum)0x02, null); + item3.Should().BeNull(); } [TestMethod] - public void TestCreateInstance() + public void TestCreateSerializable() { - object item1 = reflectionCache.CreateInstance((byte)MyTestEnum.Item1, null); + object item1 = ReflectionCache.CreateSerializable(MyTestEnum.Item1, new byte[0]); (item1 is TestItem1).Should().BeTrue(); - object item2 = reflectionCache.CreateInstance((byte)MyTestEnum.Item2, null); + object item2 = ReflectionCache.CreateSerializable(MyTestEnum.Item2, new byte[0]); (item2 is TestItem2).Should().BeTrue(); - object item3 = reflectionCache.CreateInstance(0x02, null); + object item3 = ReflectionCache.CreateSerializable((MyTestEnum)0x02, new byte[0]); item3.Should().BeNull(); } @@ -70,10 +67,10 @@ public void TestCreateInstance() public void TestCreateInstance2() { TestItem defaultItem = new TestItem1(); - object item2 = reflectionCache.CreateInstance((byte)MyTestEnum.Item2, defaultItem); + object item2 = ReflectionCache.CreateInstance(MyTestEnum.Item2, defaultItem); (item2 is TestItem2).Should().BeTrue(); - object item1 = reflectionCache.CreateInstance(0x02, new TestItem1()); + object item1 = ReflectionCache.CreateInstance((MyTestEnum)0x02, new TestItem1()); (item1 is TestItem1).Should().BeTrue(); } } diff --git a/neo/Consensus/ConsensusMessage.cs b/neo/Consensus/ConsensusMessage.cs index af16db03e3..0bca5534e1 100644 --- a/neo/Consensus/ConsensusMessage.cs +++ b/neo/Consensus/ConsensusMessage.cs @@ -7,11 +7,6 @@ namespace Neo.Consensus { public abstract class ConsensusMessage : ISerializable { - /// - /// Reflection cache for ConsensusMessageType - /// - private static ReflectionCache ReflectionCache = ReflectionCache.CreateFromEnum(); - public readonly ConsensusMessageType Type; public byte ViewNumber; @@ -31,15 +26,10 @@ public virtual void Deserialize(BinaryReader reader) public static ConsensusMessage DeserializeFrom(byte[] data) { - ConsensusMessage message = ReflectionCache.CreateInstance(data[0]); - if (message == null) throw new FormatException(); - - using (MemoryStream ms = new MemoryStream(data, false)) - using (BinaryReader r = new BinaryReader(ms)) - { - message.Deserialize(r); - } - return message; + ConsensusMessageType type = (ConsensusMessageType)data[0]; + ISerializable message = ReflectionCache.CreateSerializable(type, data); + if (message is null) throw new FormatException(); + return (ConsensusMessage)message; } public virtual void Serialize(BinaryWriter writer) diff --git a/neo/IO/Caching/ReflectionCache.cs b/neo/IO/Caching/ReflectionCache.cs index 452856698c..e0b92b2a92 100644 --- a/neo/IO/Caching/ReflectionCache.cs +++ b/neo/IO/Caching/ReflectionCache.cs @@ -1,80 +1,44 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; namespace Neo.IO.Caching { - public class ReflectionCache : Dictionary + internal static class ReflectionCache where T : Enum { - /// - /// Constructor - /// - public ReflectionCache() { } - /// - /// Constructor - /// - /// Enum type - public static ReflectionCache CreateFromEnum() where EnumType : struct, IConvertible - { - Type enumType = typeof(EnumType); - - if (!enumType.GetTypeInfo().IsEnum) - throw new ArgumentException("K must be an enumerated type"); + private static readonly Dictionary dictionary = new Dictionary(); - // Cache all types - ReflectionCache r = new ReflectionCache(); + public static int Count => dictionary.Count; - foreach (object t in Enum.GetValues(enumType)) + static ReflectionCache() + { + Type enumType = typeof(T); + foreach (FieldInfo field in enumType.GetFields(BindingFlags.Public | BindingFlags.Static)) { - // Get enumn member - MemberInfo[] memInfo = enumType.GetMember(t.ToString()); - if (memInfo == null || memInfo.Length != 1) - throw (new FormatException()); - // Get attribute - ReflectionCacheAttribute attribute = memInfo[0].GetCustomAttributes(typeof(ReflectionCacheAttribute), false) - .Cast() - .FirstOrDefault(); - - if (attribute == null) - throw (new FormatException()); + ReflectionCacheAttribute attribute = field.GetCustomAttribute(); + if (attribute == null) continue; // Append to cache - r.Add((T)t, attribute.Type); + dictionary.Add((T)field.GetValue(null), attribute.Type); } - return r; } - /// - /// Create object from key - /// - /// Key - /// Default value - public object CreateInstance(T key, object def = null) - { - Type tp; + public static object CreateInstance(T key, object def = null) + { // Get Type from cache - if (TryGetValue(key, out tp)) return Activator.CreateInstance(tp); + if (dictionary.TryGetValue(key, out Type t)) + return Activator.CreateInstance(t); // return null return def; } - /// - /// Create object from key - /// - /// Type - /// Key - /// Default value - public K CreateInstance(T key, K def = default(K)) - { - Type tp; - - // Get Type from cache - if (TryGetValue(key, out tp)) return (K)Activator.CreateInstance(tp); - // return null - return def; + public static ISerializable CreateSerializable(T key, byte[] data) + { + if (dictionary.TryGetValue(key, out Type t)) + return data.AsSerializable(t); + return null; } } } diff --git a/neo/IO/Caching/ReflectionCacheAttribute.cs b/neo/IO/Caching/ReflectionCacheAttribute.cs index b2ac3c3054..2bbbca8568 100644 --- a/neo/IO/Caching/ReflectionCacheAttribute.cs +++ b/neo/IO/Caching/ReflectionCacheAttribute.cs @@ -2,12 +2,13 @@ namespace Neo.IO.Caching { - public class ReflectionCacheAttribute : Attribute + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + internal class ReflectionCacheAttribute : Attribute { /// /// Type /// - public Type Type { get; private set; } + public Type Type { get; } /// /// Constructor diff --git a/neo/Network/P2P/Message.cs b/neo/Network/P2P/Message.cs index 38bc2bf6c1..578259f789 100644 --- a/neo/Network/P2P/Message.cs +++ b/neo/Network/P2P/Message.cs @@ -1,7 +1,7 @@ using Akka.IO; using Neo.Cryptography; using Neo.IO; -using Neo.Network.P2P.Payloads; +using Neo.IO.Caching; using System; using System.IO; @@ -51,51 +51,7 @@ private void DecompressPayload() byte[] decompressed = Flags.HasFlag(MessageFlags.Compressed) ? _payload_compressed.DecompressLz4(PayloadMaxSize) : _payload_compressed; - switch (Command) - { - case MessageCommand.Version: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Addr: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Ping: - case MessageCommand.Pong: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.GetHeaders: - case MessageCommand.GetBlocks: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Headers: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Inv: - case MessageCommand.GetData: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.GetBlockData: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Transaction: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Block: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.Consensus: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.FilterLoad: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.FilterAdd: - Payload = decompressed.AsSerializable(); - break; - case MessageCommand.MerkleBlock: - Payload = decompressed.AsSerializable(); - break; - } + Payload = ReflectionCache.CreateSerializable(Command, decompressed); } void ISerializable.Deserialize(BinaryReader reader) diff --git a/neo/Network/P2P/MessageCommand.cs b/neo/Network/P2P/MessageCommand.cs index d1f2befc67..ccddacfba2 100644 --- a/neo/Network/P2P/MessageCommand.cs +++ b/neo/Network/P2P/MessageCommand.cs @@ -1,35 +1,54 @@ +using Neo.IO.Caching; +using Neo.Network.P2P.Payloads; + namespace Neo.Network.P2P { public enum MessageCommand : byte { //handshaking + [ReflectionCache(typeof(VersionPayload))] Version = 0x00, Verack = 0x01, //connectivity GetAddr = 0x10, + [ReflectionCache(typeof(AddrPayload))] Addr = 0x11, + [ReflectionCache(typeof(PingPayload))] Ping = 0x18, + [ReflectionCache(typeof(PingPayload))] Pong = 0x19, //synchronization + [ReflectionCache(typeof(GetBlocksPayload))] GetHeaders = 0x20, + [ReflectionCache(typeof(HeadersPayload))] Headers = 0x21, + [ReflectionCache(typeof(GetBlocksPayload))] GetBlocks = 0x24, Mempool = 0x25, + [ReflectionCache(typeof(InvPayload))] Inv = 0x27, + [ReflectionCache(typeof(InvPayload))] GetData = 0x28, + [ReflectionCache(typeof(GetBlockDataPayload))] GetBlockData = 0x29, NotFound = 0x2a, + [ReflectionCache(typeof(Transaction))] Transaction = 0x2b, + [ReflectionCache(typeof(Block))] Block = 0x2c, + [ReflectionCache(typeof(ConsensusPayload))] Consensus = 0x2d, Reject = 0x2f, //SPV protocol + [ReflectionCache(typeof(FilterLoadPayload))] FilterLoad = 0x30, + [ReflectionCache(typeof(FilterAddPayload))] FilterAdd = 0x31, FilterClear = 0x32, + [ReflectionCache(typeof(MerkleBlockPayload))] MerkleBlock = 0x38, //others