diff --git a/src/Neo.CLI/CLI/MainService.Network.cs b/src/Neo.CLI/CLI/MainService.Network.cs index c579b8323e..49a056640e 100644 --- a/src/Neo.CLI/CLI/MainService.Network.cs +++ b/src/Neo.CLI/CLI/MainService.Network.cs @@ -11,6 +11,7 @@ using Akka.Actor; using Neo.ConsoleService; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P; diff --git a/src/Neo.Extensions/AssemblyExtensions.cs b/src/Neo.Extensions/AssemblyExtensions.cs new file mode 100644 index 0000000000..4f9368c98b --- /dev/null +++ b/src/Neo.Extensions/AssemblyExtensions.cs @@ -0,0 +1,23 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// AssemblyExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System.Reflection; + +namespace Neo.Extensions +{ + public static class AssemblyExtensions + { + public static string GetVersion(this Assembly assembly) + { + return assembly.GetName().Version!.ToString(3); + } + } +} diff --git a/src/Neo.Extensions/Collections/HashSetExtensions.cs b/src/Neo.Extensions/Collections/HashSetExtensions.cs new file mode 100644 index 0000000000..9cf3f13b23 --- /dev/null +++ b/src/Neo.Extensions/Collections/HashSetExtensions.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// HashSetExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System.Collections.Generic; + +namespace Neo.Extensions +{ + public static class HashSetExtensions + { + public static void Remove(this HashSet set, ISet other) + { + if (set.Count > other.Count) + { + set.ExceptWith(other); + } + else + { + set.RemoveWhere(u => other.Contains(u)); + } + } + + public static void Remove(this HashSet set, IReadOnlyDictionary other) + { + if (set.Count > other.Count) + { + set.ExceptWith(other.Keys); + } + else + { + set.RemoveWhere(u => other.ContainsKey(u)); + } + } + } +} diff --git a/src/Neo.Extensions/DateTimeExtensions.cs b/src/Neo.Extensions/DateTimeExtensions.cs new file mode 100644 index 0000000000..130d09e78d --- /dev/null +++ b/src/Neo.Extensions/DateTimeExtensions.cs @@ -0,0 +1,38 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// DateTimeExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System; + +namespace Neo.Extensions +{ + public static class DateTimeExtensions + { + /// + /// Converts a to timestamp. + /// + /// The to convert. + /// The converted timestamp. + public static uint ToTimestamp(this DateTime time) + { + return (uint)new DateTimeOffset(time.ToUniversalTime()).ToUnixTimeSeconds(); + } + + /// + /// Converts a to timestamp in milliseconds. + /// + /// The to convert. + /// The converted timestamp. + public static ulong ToTimestampMS(this DateTime time) + { + return (ulong)new DateTimeOffset(time.ToUniversalTime()).ToUnixTimeMilliseconds(); + } + } +} diff --git a/src/Neo.Extensions/Net/IpAddressExtensions.cs b/src/Neo.Extensions/Net/IpAddressExtensions.cs new file mode 100644 index 0000000000..adafee142f --- /dev/null +++ b/src/Neo.Extensions/Net/IpAddressExtensions.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// IpAddressExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System.Net; + +namespace Neo.Extensions +{ + public static class IpAddressExtensions + { + /// + /// Checks if address is IPv4 Mapped to IPv6 format, if so, Map to IPv4. + /// Otherwise, return current address. + /// + public static IPAddress UnMap(this IPAddress address) + { + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + return address; + } + + /// + /// Checks if IPEndPoint is IPv4 Mapped to IPv6 format, if so, unmap to IPv4. + /// Otherwise, return current endpoint. + /// + public static IPEndPoint UnMap(this IPEndPoint endPoint) + { + if (!endPoint.Address.IsIPv4MappedToIPv6) + return endPoint; + return new IPEndPoint(endPoint.Address.UnMap(), endPoint.Port); + } + } +} diff --git a/src/Neo.Extensions/RandomExtensions.cs b/src/Neo.Extensions/RandomExtensions.cs new file mode 100644 index 0000000000..72bcac289f --- /dev/null +++ b/src/Neo.Extensions/RandomExtensions.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// RandomExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System; +using System.Numerics; + +namespace Neo.Extensions +{ + public static class RandomExtensions + { + public static BigInteger NextBigInteger(this Random rand, int sizeInBits) + { + if (sizeInBits < 0) + throw new ArgumentException("sizeInBits must be non-negative"); + if (sizeInBits == 0) + return 0; + Span b = stackalloc byte[sizeInBits / 8 + 1]; + rand.NextBytes(b); + if (sizeInBits % 8 == 0) + b[^1] = 0; + else + b[^1] &= (byte)((1 << sizeInBits % 8) - 1); + return new BigInteger(b); + } + } +} diff --git a/src/Neo.Extensions/StringExtensions.cs b/src/Neo.Extensions/StringExtensions.cs new file mode 100644 index 0000000000..b84869b2e1 --- /dev/null +++ b/src/Neo.Extensions/StringExtensions.cs @@ -0,0 +1,47 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// StringExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System; +using System.Globalization; + +namespace Neo.Extensions +{ + public static class StringExtensions + { + /// + /// Converts a hex to byte array. + /// + /// The hex to convert. + /// The converted byte array. + public static byte[] HexToBytes(this string value) + { + if (value == null || value.Length == 0) + return []; + if (value.Length % 2 == 1) + throw new FormatException(); + var result = new byte[value.Length / 2]; + for (var i = 0; i < result.Length; i++) + result[i] = byte.Parse(value.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier); + return result; + } + + /// + /// Gets the size of the specified encoded in variable-length encoding. + /// + /// The specified . + /// The size of the . + public static int GetVarSize(this string value) + { + var size = Utility.StrictUTF8.GetByteCount(value); + return UnsafeData.GetVarSize(size) + size; + } + } +} diff --git a/src/Neo.Extensions/UnsafeData.cs b/src/Neo.Extensions/UnsafeData.cs new file mode 100644 index 0000000000..6d4c9a6f8e --- /dev/null +++ b/src/Neo.Extensions/UnsafeData.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UnsafeData.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +namespace Neo.Extensions +{ + public static class UnsafeData + { + /// + /// Gets the size of variable-length of the data. + /// + /// The length of the data. + /// The size of variable-length of the data. + public static int GetVarSize(int value) + { + if (value < 0xFD) + return sizeof(byte); + else if (value <= 0xFFFF) + return sizeof(byte) + sizeof(ushort); + else + return sizeof(byte) + sizeof(uint); + } + } +} diff --git a/src/Neo.GUI/GUI/CreateMultiSigContractDialog.cs b/src/Neo.GUI/GUI/CreateMultiSigContractDialog.cs index 5dd10f858f..d28696f138 100644 --- a/src/Neo.GUI/GUI/CreateMultiSigContractDialog.cs +++ b/src/Neo.GUI/GUI/CreateMultiSigContractDialog.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.SmartContract; using Neo.Wallets; using System; diff --git a/src/Neo.GUI/GUI/ElectionDialog.cs b/src/Neo.GUI/GUI/ElectionDialog.cs index ddc730589e..ef644074d9 100644 --- a/src/Neo.GUI/GUI/ElectionDialog.cs +++ b/src/Neo.GUI/GUI/ElectionDialog.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.SmartContract.Native; using Neo.VM; using System; diff --git a/src/Neo.GUI/GUI/ImportCustomContractDialog.cs b/src/Neo.GUI/GUI/ImportCustomContractDialog.cs index b8df534699..8faa23d593 100644 --- a/src/Neo.GUI/GUI/ImportCustomContractDialog.cs +++ b/src/Neo.GUI/GUI/ImportCustomContractDialog.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.SmartContract; using Neo.Wallets; using System; diff --git a/src/Neo.GUI/GUI/ParametersEditor.cs b/src/Neo.GUI/GUI/ParametersEditor.cs index 19eac82c31..f5156d6bfb 100644 --- a/src/Neo.GUI/GUI/ParametersEditor.cs +++ b/src/Neo.GUI/GUI/ParametersEditor.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.SmartContract; using System; using System.Collections.Generic; diff --git a/src/Neo.GUI/GUI/VotingDialog.cs b/src/Neo.GUI/GUI/VotingDialog.cs index d289cc48ca..ff5749e181 100644 --- a/src/Neo.GUI/GUI/VotingDialog.cs +++ b/src/Neo.GUI/GUI/VotingDialog.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; diff --git a/src/Neo.IO/Caching/HashSetCache.cs b/src/Neo.IO/Caching/HashSetCache.cs index 577893e924..6e39f5fd8b 100644 --- a/src/Neo.IO/Caching/HashSetCache.cs +++ b/src/Neo.IO/Caching/HashSetCache.cs @@ -15,7 +15,7 @@ namespace Neo.IO.Caching { - class HashSetCache : IReadOnlyCollection where T : IEquatable + internal class HashSetCache : IReadOnlyCollection where T : IEquatable { /// /// Sets where the Hashes are stored diff --git a/src/Neo.IO/Neo.IO.csproj b/src/Neo.IO/Neo.IO.csproj index a51ec1110a..deb98b053b 100644 --- a/src/Neo.IO/Neo.IO.csproj +++ b/src/Neo.IO/Neo.IO.csproj @@ -12,7 +12,8 @@ - + + diff --git a/src/Neo/Cryptography/ECC/ECCurve.cs b/src/Neo/Cryptography/ECC/ECCurve.cs index def1ee0cb1..805507a08e 100644 --- a/src/Neo/Cryptography/ECC/ECCurve.cs +++ b/src/Neo/Cryptography/ECC/ECCurve.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using System.Globalization; using System.Numerics; diff --git a/src/Neo/Cryptography/Helper.cs b/src/Neo/Cryptography/Helper.cs index 41e89f5a49..5ec4ea38d7 100644 --- a/src/Neo/Cryptography/Helper.cs +++ b/src/Neo/Cryptography/Helper.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Wallets; using Org.BouncyCastle.Crypto.Digests; diff --git a/src/Neo/Cryptography/MerkleTree.cs b/src/Neo/Cryptography/MerkleTree.cs index ed25171ef8..09afa29277 100644 --- a/src/Neo/Cryptography/MerkleTree.cs +++ b/src/Neo/Cryptography/MerkleTree.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using System; using System.Collections; using System.Collections.Generic; diff --git a/src/Neo/Extensions/ByteExtensions.cs b/src/Neo/Extensions/ByteExtensions.cs new file mode 100644 index 0000000000..fa451008fc --- /dev/null +++ b/src/Neo/Extensions/ByteExtensions.cs @@ -0,0 +1,66 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// ByteExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO; +using System; + +namespace Neo.Extensions +{ + public static class ByteExtensions2 + { + /// + /// Compresses the specified data using the LZ4 algorithm. + /// + /// The data to be compressed. + /// The compressed data. + public static ReadOnlyMemory CompressLz4(this byte[] data) + { + return data.AsSpan().CompressLz4(); + } + + /// + /// Decompresses the specified data using the LZ4 algorithm. + /// + /// The compressed data. + /// The maximum data size after decompression. + /// The original data. + public static byte[] DecompressLz4(this byte[] data, int maxOutput) + { + return data.AsSpan().DecompressLz4(maxOutput); + } + + /// + /// Converts a byte array to an object. + /// + /// The type to convert to. + /// The byte array to be converted. + /// The offset into the byte array from which to begin using data. + /// The converted object. + public static T AsSerializable(this byte[] value, int start = 0) where T : ISerializable, new() + { + MemoryReader reader = new(value.AsMemory(start)); + return reader.ReadSerializable(); + } + + /// + /// Converts a byte array to an array. + /// + /// The type of the array element. + /// The byte array to be converted. + /// The maximum number of elements contained in the converted array. + /// The converted array. + public static T[] AsSerializableArray(this byte[] value, int max = 0x1000000) where T : ISerializable, new() + { + MemoryReader reader = new(value); + return reader.ReadSerializableArray(max); + } + } +} diff --git a/src/Neo/Extensions/Collections/ICollectionExtensions.cs b/src/Neo/Extensions/Collections/ICollectionExtensions.cs new file mode 100644 index 0000000000..742446a4e8 --- /dev/null +++ b/src/Neo/Extensions/Collections/ICollectionExtensions.cs @@ -0,0 +1,75 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// ICollectionExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.Extensions; +using Neo.IO; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Neo.Extensions +{ + public static class ICollectionExtensions + { + /// + /// Gets the size of the specified array encoded in variable-length encoding. + /// + /// The type of the array element. + /// The specified array. + /// The size of the array. + public static int GetVarSize(this IReadOnlyCollection value) + { + int value_size; + var t = typeof(T); + if (typeof(ISerializable).IsAssignableFrom(t)) + { + value_size = value.OfType().Sum(p => p.Size); + } + else if (t.GetTypeInfo().IsEnum) + { + int element_size; + var u = t.GetTypeInfo().GetEnumUnderlyingType(); + if (u == typeof(sbyte) || u == typeof(byte)) + element_size = 1; + else if (u == typeof(short) || u == typeof(ushort)) + element_size = 2; + else if (u == typeof(int) || u == typeof(uint)) + element_size = 4; + else //if (u == typeof(long) || u == typeof(ulong)) + element_size = 8; + value_size = value.Count * element_size; + } + else + { + value_size = value.Count * Marshal.SizeOf(); + } + return UnsafeData.GetVarSize(value.Count) + value_size; + } + + /// + /// Converts an array to a byte array. + /// + /// The type of the array element. + /// The array to be converted. + /// The converted byte array. + public static byte[] ToByteArray(this IReadOnlyCollection value) + where T : ISerializable + { + using MemoryStream ms = new(); + using BinaryWriter writer = new(ms, Utility.StrictUTF8, true); + writer.Write(value); + writer.Flush(); + return ms.ToArray(); + } + } +} diff --git a/src/Neo/Extensions/HashSetExtensions.cs b/src/Neo/Extensions/HashSetExtensions.cs new file mode 100644 index 0000000000..48fdb9d43e --- /dev/null +++ b/src/Neo/Extensions/HashSetExtensions.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// HashSetExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO.Caching; +using System; +using System.Collections.Generic; + +namespace Neo.Extensions +{ + /// + /// A helper class that provides common functions. + /// + public static class HashSetExtensions2 + { + internal static void Remove(this HashSet set, HashSetCache other) + where T : IEquatable + { + if (set.Count > other.Count) + { + set.ExceptWith(other); + } + else + { + set.RemoveWhere(u => other.Contains(u)); + } + } + } +} diff --git a/src/Neo/Extensions/IO/BinaryReaderExtensions.cs b/src/Neo/Extensions/IO/BinaryReaderExtensions.cs new file mode 100644 index 0000000000..f3448d96e1 --- /dev/null +++ b/src/Neo/Extensions/IO/BinaryReaderExtensions.cs @@ -0,0 +1,79 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// BinaryReaderExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using System; +using System.IO; + +namespace Neo.Extensions +{ + public static class BinaryReaderExtensions + { + /// + /// Reads a byte array of the specified size from a . + /// + /// The for reading data. + /// The size of the byte array. + /// The byte array read from the . + public static byte[] ReadFixedBytes(this BinaryReader reader, int size) + { + var index = 0; + var data = new byte[size]; + + while (size > 0) + { + var bytesRead = reader.Read(data, index, size); + + if (bytesRead <= 0) + { + throw new FormatException(); + } + + size -= bytesRead; + index += bytesRead; + } + + return data; + } + + /// + /// Reads a byte array from a . + /// + /// The for reading data. + /// The maximum size of the byte array. + /// The byte array read from the . + public static byte[] ReadVarBytes(this BinaryReader reader, int max = 0x1000000) + { + return reader.ReadFixedBytes((int)reader.ReadVarInt((ulong)max)); + } + + /// + /// Reads an integer from a . + /// + /// The for reading data. + /// The maximum value of the integer. + /// The integer read from the . + public static ulong ReadVarInt(this BinaryReader reader, ulong max = ulong.MaxValue) + { + var fb = reader.ReadByte(); + ulong value; + if (fb == 0xFD) + value = reader.ReadUInt16(); + else if (fb == 0xFE) + value = reader.ReadUInt32(); + else if (fb == 0xFF) + value = reader.ReadUInt64(); + else + value = fb; + if (value > max) throw new FormatException(); + return value; + } + } +} diff --git a/src/Neo/Extensions/IO/BinaryWriterExtensions.cs b/src/Neo/Extensions/IO/BinaryWriterExtensions.cs new file mode 100644 index 0000000000..665eae1a69 --- /dev/null +++ b/src/Neo/Extensions/IO/BinaryWriterExtensions.cs @@ -0,0 +1,137 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// BinaryWriterExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO; +using System; +using System.Collections.Generic; +using System.IO; + +namespace Neo.Extensions +{ + public static class BinaryWriterExtensions + { + /// + /// Writes an object into a . + /// + /// The for writing data. + /// The object to be written. + public static void Write(this BinaryWriter writer, ISerializable value) + { + value.Serialize(writer); + } + + /// + /// Writes an array into a . + /// + /// The type of the array element. + /// The for writing data. + /// The array to be written. + public static void Write(this BinaryWriter writer, IReadOnlyCollection value) + where T : ISerializable + { + writer.WriteVarInt(value.Count); + foreach (T item in value) + { + item.Serialize(writer); + } + } + + /// + /// Writes a into a . + /// + /// The for writing data. + /// The to be written. + /// The fixed size of the . + public static void WriteFixedString(this BinaryWriter writer, string value, int length) + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (value.Length > length) + throw new ArgumentException(null, nameof(value)); + var bytes = Utility.StrictUTF8.GetBytes(value); + if (bytes.Length > length) + throw new ArgumentException(null, nameof(value)); + writer.Write(bytes); + if (bytes.Length < length) + writer.Write(stackalloc byte[length - bytes.Length]); + } + + /// + /// Writes an array into a . + /// + /// The type of the array element. + /// The for writing data. + /// The array to be written. + public static void WriteNullableArray(this BinaryWriter writer, T[] value) + where T : class, ISerializable + { + writer.WriteVarInt(value.Length); + foreach (var item in value) + { + var isNull = item is null; + writer.Write(!isNull); + if (isNull) continue; + item.Serialize(writer); + } + } + + /// + /// Writes a byte array into a . + /// + /// The for writing data. + /// The byte array to be written. + public static void WriteVarBytes(this BinaryWriter writer, ReadOnlySpan value) + { + writer.WriteVarInt(value.Length); + writer.Write(value); + } + + /// + /// Writes an integer into a . + /// + /// The for writing data. + /// The integer to be written. + public static void WriteVarInt(this BinaryWriter writer, long value) + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value)); + if (value < 0xFD) + { + writer.Write((byte)value); + } + else if (value <= 0xFFFF) + { + writer.Write((byte)0xFD); + writer.Write((ushort)value); + } + else if (value <= 0xFFFFFFFF) + { + writer.Write((byte)0xFE); + writer.Write((uint)value); + } + else + { + writer.Write((byte)0xFF); + writer.Write(value); + } + } + + /// + /// Writes a into a . + /// + /// The for writing data. + /// The to be written. + public static void WriteVarString(this BinaryWriter writer, string value) + { + writer.WriteVarBytes(Utility.StrictUTF8.GetBytes(value)); + } + } +} diff --git a/src/Neo/Extensions/IO/ISerializableExtensions.cs b/src/Neo/Extensions/IO/ISerializableExtensions.cs new file mode 100644 index 0000000000..67b4f39519 --- /dev/null +++ b/src/Neo/Extensions/IO/ISerializableExtensions.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// ISerializableExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO; +using System.IO; + +namespace Neo.Extensions +{ + public static class ISerializableExtensions + { + /// + /// Converts an object to a byte array. + /// + /// The object to be converted. + /// The converted byte array. + public static byte[] ToArray(this ISerializable value) + { + using MemoryStream ms = new(); + using BinaryWriter writer = new(ms, Utility.StrictUTF8, true); + value.Serialize(writer); + writer.Flush(); + return ms.ToArray(); + } + } +} diff --git a/src/Neo/Extensions/IO/MemoryReaderExtensions.cs b/src/Neo/Extensions/IO/MemoryReaderExtensions.cs new file mode 100644 index 0000000000..5591724b80 --- /dev/null +++ b/src/Neo/Extensions/IO/MemoryReaderExtensions.cs @@ -0,0 +1,70 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// MemoryReaderExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO; + +namespace Neo.Extensions +{ + /// + /// A helper class for serialization of NEO objects. + /// + public static class MemoryReaderExtensions + { + /// + /// Reads an array from a . + /// + /// The type of the array element. + /// The for reading data. + /// The maximum number of elements in the array. + /// The array read from the . + public static T[] ReadNullableArray(this ref MemoryReader reader, int max = 0x1000000) + where T : class, ISerializable, new() + { + var array = new T[reader.ReadVarInt((ulong)max)]; + for (var i = 0; i < array.Length; i++) + array[i] = reader.ReadBoolean() ? reader.ReadSerializable() : null; + return array; + } + + /// + /// Reads an object from a . + /// + /// The type of the object. + /// The for reading data. + /// The object read from the . + public static T ReadSerializable(this ref MemoryReader reader) + where T : ISerializable, new() + { + T obj = new(); + obj.Deserialize(ref reader); + return obj; + } + + /// + /// Reads an array from a . + /// + /// The type of the array element. + /// The for reading data. + /// The maximum number of elements in the array. + /// The array read from the . + public static T[] ReadSerializableArray(this ref MemoryReader reader, int max = 0x1000000) + where T : ISerializable, new() + { + var array = new T[reader.ReadVarInt((ulong)max)]; + for (var i = 0; i < array.Length; i++) + { + array[i] = new T(); + array[i].Deserialize(ref reader); + } + return array; + } + } +} diff --git a/src/Neo/Extensions/MemoryExtensions.cs b/src/Neo/Extensions/MemoryExtensions.cs new file mode 100644 index 0000000000..c1331a5998 --- /dev/null +++ b/src/Neo/Extensions/MemoryExtensions.cs @@ -0,0 +1,74 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// MemoryExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO; +using System; +using System.Reflection; + +namespace Neo.Extensions +{ + public static class MemoryExtensions + { + /// + /// Converts a byte array to an array. + /// + /// The type of the array element. + /// The byte array to be converted. + /// The maximum number of elements contained in the converted array. + /// The converted array. + public static T[] AsSerializableArray(this ReadOnlyMemory value, int max = 0x1000000) where T : ISerializable, new() + { + if (value.IsEmpty) throw new FormatException(); + MemoryReader reader = new(value); + return reader.ReadSerializableArray(max); + } + + /// + /// Converts a byte array to an object. + /// + /// The type to convert to. + /// The byte array to be converted. + /// The converted object. + public static T AsSerializable(this ReadOnlyMemory value) + where T : ISerializable, new() + { + if (value.IsEmpty) throw new FormatException(); + MemoryReader reader = new(value); + return reader.ReadSerializable(); + } + + /// + /// Converts a byte array to an object. + /// + /// The byte array to be converted. + /// The type to convert to. + /// The converted object. + public static ISerializable AsSerializable(this ReadOnlyMemory value, Type type) + { + if (!typeof(ISerializable).GetTypeInfo().IsAssignableFrom(type)) + throw new InvalidCastException(); + var serializable = (ISerializable)Activator.CreateInstance(type); + MemoryReader reader = new(value); + serializable.Deserialize(ref reader); + return serializable; + } + + /// + /// Gets the size of the specified array encoded in variable-length encoding. + /// + /// The specified array. + /// The size of the array. + public static int GetVarSize(this ReadOnlyMemory value) + { + return UnsafeData.GetVarSize(value.Length) + value.Length; + } + } +} diff --git a/src/Neo/Extensions/SpanExtensions.cs b/src/Neo/Extensions/SpanExtensions.cs new file mode 100644 index 0000000000..3bc650cbb8 --- /dev/null +++ b/src/Neo/Extensions/SpanExtensions.cs @@ -0,0 +1,80 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// SpanExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using K4os.Compression.LZ4; +using System; +using System.Buffers.Binary; + +namespace Neo.Extensions +{ + public static class SpanExtensions + { + /// + /// Compresses the specified data using the LZ4 algorithm. + /// + /// The data to be compressed. + /// The compressed data. + public static ReadOnlyMemory CompressLz4(this ReadOnlySpan data) + { + var maxLength = LZ4Codec.MaximumOutputSize(data.Length); + var buffer = new byte[sizeof(uint) + maxLength]; + BinaryPrimitives.WriteInt32LittleEndian(buffer, data.Length); + var length = LZ4Codec.Encode(data, buffer.AsSpan(sizeof(uint))); + return buffer.AsMemory(0, sizeof(uint) + length); + } + + /// + /// Compresses the specified data using the LZ4 algorithm. + /// + /// The data to be compressed. + /// The compressed data. + public static ReadOnlyMemory CompressLz4(this Span data) + { + var maxLength = LZ4Codec.MaximumOutputSize(data.Length); + var buffer = new byte[sizeof(uint) + maxLength]; + BinaryPrimitives.WriteInt32LittleEndian(buffer, data.Length); + var length = LZ4Codec.Encode(data, buffer.AsSpan(sizeof(uint))); + return buffer.AsMemory(0, sizeof(uint) + length); + } + + /// + /// Decompresses the specified data using the LZ4 algorithm. + /// + /// The compressed data. + /// The maximum data size after decompression. + /// The original data. + public static byte[] DecompressLz4(this ReadOnlySpan data, int maxOutput) + { + var length = BinaryPrimitives.ReadInt32LittleEndian(data); + if (length < 0 || length > maxOutput) throw new FormatException(); + var result = new byte[length]; + if (LZ4Codec.Decode(data[4..], result) != length) + throw new FormatException(); + return result; + } + + /// + /// Decompresses the specified data using the LZ4 algorithm. + /// + /// The compressed data. + /// The maximum data size after decompression. + /// The original data. + public static byte[] DecompressLz4(this Span data, int maxOutput) + { + var length = BinaryPrimitives.ReadInt32LittleEndian(data); + if (length < 0 || length > maxOutput) throw new FormatException(); + var result = new byte[length]; + if (LZ4Codec.Decode(data[4..], result) != length) + throw new FormatException(); + return result; + } + } +} diff --git a/src/Neo/Extensions/UInt160Extensions.cs b/src/Neo/Extensions/UInt160Extensions.cs new file mode 100644 index 0000000000..988d7e5d83 --- /dev/null +++ b/src/Neo/Extensions/UInt160Extensions.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UInt160Extensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.VM; + +namespace Neo.Extensions +{ + public static class UInt160Extensions + { + /// + /// Generates the script for calling a contract dynamically. + /// + /// The hash of the contract to be called. + /// The method to be called in the contract. + /// The arguments for calling the contract. + /// The generated script. + public static byte[] MakeScript(this UInt160 scriptHash, string method, params object[] args) + { + using ScriptBuilder sb = new(); + sb.EmitDynamicCall(scriptHash, method, args); + return sb.ToArray(); + } + } +} diff --git a/src/Neo/Extensions/VM/EvaluationStackExtensions.cs b/src/Neo/Extensions/VM/EvaluationStackExtensions.cs new file mode 100644 index 0000000000..30684c01b2 --- /dev/null +++ b/src/Neo/Extensions/VM/EvaluationStackExtensions.cs @@ -0,0 +1,37 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// EvaluationStackExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.Json; +using Neo.VM; +using System; + +namespace Neo.Extensions +{ + public static class EvaluationStackExtensions + { + /// + /// Converts the to a JSON object. + /// + /// The to convert. + /// The maximum size in bytes of the result. + /// The represented by a JSON object. + public static JArray ToJson(this EvaluationStack stack, int maxSize = int.MaxValue) + { + if (maxSize <= 0) throw new ArgumentOutOfRangeException(nameof(maxSize)); + maxSize -= 2/*[]*/+ Math.Max(0, (stack.Count - 1))/*,*/; + JArray result = []; + foreach (var item in stack) + result.Add(item.ToJson(null, ref maxSize)); + if (maxSize < 0) throw new InvalidOperationException("Max size reached."); + return result; + } + } +} diff --git a/src/Neo/Extensions/VM/ScriptBuilderExtensions.cs b/src/Neo/Extensions/VM/ScriptBuilderExtensions.cs new file mode 100644 index 0000000000..575f056dfa --- /dev/null +++ b/src/Neo/Extensions/VM/ScriptBuilderExtensions.cs @@ -0,0 +1,259 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// ScriptBuilderExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.Cryptography.ECC; +using Neo.IO; +using Neo.SmartContract; +using Neo.VM; +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace Neo.Extensions +{ + public static class ScriptBuilderExtensions + { + /// + /// Emits the opcodes for creating an array. + /// + /// The type of the elements of the array. + /// The to be used. + /// The elements of the array. + /// The same instance as . + public static ScriptBuilder CreateArray(this ScriptBuilder builder, IReadOnlyList list = null) + { + if (list is null || list.Count == 0) + return builder.Emit(OpCode.NEWARRAY0); + for (var i = list.Count - 1; i >= 0; i--) + builder.EmitPush(list[i]); + builder.EmitPush(list.Count); + return builder.Emit(OpCode.PACK); + } + + /// + /// Emits the opcodes for creating a map. + /// + /// The type of the key of the map. + /// The type of the value of the map. + /// The to be used. + /// The key/value pairs of the map. + /// The same instance as . + public static ScriptBuilder CreateMap(this ScriptBuilder builder, IEnumerable> map = null) + { + builder.Emit(OpCode.NEWMAP); + if (map != null) + foreach (var p in map) + { + builder.Emit(OpCode.DUP); + builder.EmitPush(p.Key); + builder.EmitPush(p.Value); + builder.Emit(OpCode.SETITEM); + } + return builder; + } + + /// + /// Emits the specified opcodes. + /// + /// The to be used. + /// The opcodes to emit. + /// The same instance as . + public static ScriptBuilder Emit(this ScriptBuilder builder, params OpCode[] ops) + { + foreach (var op in ops) + builder.Emit(op); + return builder; + } + + /// + /// Emits the opcodes for calling a contract dynamically. + /// + /// The to be used. + /// The hash of the contract to be called. + /// The method to be called in the contract. + /// The arguments for calling the contract. + /// The same instance as . + public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, params object[] args) + { + return EmitDynamicCall(builder, scriptHash, method, CallFlags.All, args); + } + + /// + /// Emits the opcodes for calling a contract dynamically. + /// + /// The to be used. + /// The hash of the contract to be called. + /// The method to be called in the contract. + /// The for calling the contract. + /// The arguments for calling the contract. + /// The same instance as . + public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, CallFlags flags, params object[] args) + { + builder.CreateArray(args); + builder.EmitPush(flags); + builder.EmitPush(method); + builder.EmitPush(scriptHash); + builder.EmitSysCall(ApplicationEngine.System_Contract_Call); + return builder; + } + + /// + /// Emits the opcodes for pushing the specified data onto the stack. + /// + /// The to be used. + /// The data to be pushed. + /// The same instance as . + public static ScriptBuilder EmitPush(this ScriptBuilder builder, ISerializable data) + { + return builder.EmitPush(data.ToArray()); + } + + /// + /// Emits the opcodes for pushing the specified data onto the stack. + /// + /// The to be used. + /// The data to be pushed. + /// The same instance as . + public static ScriptBuilder EmitPush(this ScriptBuilder builder, ContractParameter parameter) + { + if (parameter.Value is null) + builder.Emit(OpCode.PUSHNULL); + else + switch (parameter.Type) + { + case ContractParameterType.Signature: + case ContractParameterType.ByteArray: + builder.EmitPush((byte[])parameter.Value); + break; + case ContractParameterType.Boolean: + builder.EmitPush((bool)parameter.Value); + break; + case ContractParameterType.Integer: + if (parameter.Value is BigInteger bi) + builder.EmitPush(bi); + else + builder.EmitPush((BigInteger)typeof(BigInteger).GetConstructor([parameter.Value.GetType()]).Invoke([parameter.Value])); + break; + case ContractParameterType.Hash160: + builder.EmitPush((UInt160)parameter.Value); + break; + case ContractParameterType.Hash256: + builder.EmitPush((UInt256)parameter.Value); + break; + case ContractParameterType.PublicKey: + builder.EmitPush((ECPoint)parameter.Value); + break; + case ContractParameterType.String: + builder.EmitPush((string)parameter.Value); + break; + case ContractParameterType.Array: + { + var parameters = (IList)parameter.Value; + for (var i = parameters.Count - 1; i >= 0; i--) + builder.EmitPush(parameters[i]); + builder.EmitPush(parameters.Count); + builder.Emit(OpCode.PACK); + } + break; + case ContractParameterType.Map: + { + var pairs = (IList>)parameter.Value; + builder.CreateMap(pairs); + } + break; + default: + throw new ArgumentException(null, nameof(parameter)); + } + return builder; + } + + /// + /// Emits the opcodes for pushing the specified data onto the stack. + /// + /// The to be used. + /// The data to be pushed. + /// The same instance as . + public static ScriptBuilder EmitPush(this ScriptBuilder builder, object obj) + { + switch (obj) + { + case bool data: + builder.EmitPush(data); + break; + case byte[] data: + builder.EmitPush(data); + break; + case string data: + builder.EmitPush(data); + break; + case BigInteger data: + builder.EmitPush(data); + break; + case ISerializable data: + builder.EmitPush(data); + break; + case sbyte data: + builder.EmitPush(data); + break; + case byte data: + builder.EmitPush(data); + break; + case short data: + builder.EmitPush(data); + break; + case char data: + builder.EmitPush(data); + break; + case ushort data: + builder.EmitPush(data); + break; + case int data: + builder.EmitPush(data); + break; + case uint data: + builder.EmitPush(data); + break; + case long data: + builder.EmitPush(data); + break; + case ulong data: + builder.EmitPush(data); + break; + case Enum data: + builder.EmitPush(BigInteger.Parse(data.ToString("d"))); + break; + case ContractParameter data: + builder.EmitPush(data); + break; + case null: + builder.Emit(OpCode.PUSHNULL); + break; + default: + throw new ArgumentException(null, nameof(obj)); + } + return builder; + } + + /// + /// Emits the opcodes for invoking an interoperable service. + /// + /// The to be used. + /// The hash of the interoperable service. + /// The arguments for calling the interoperable service. + /// The same instance as . + public static ScriptBuilder EmitSysCall(this ScriptBuilder builder, uint method, params object[] args) + { + for (var i = args.Length - 1; i >= 0; i--) + EmitPush(builder, args[i]); + return builder.EmitSysCall(method); + } + } +} diff --git a/src/Neo/Helper.cs b/src/Neo/Helper.cs deleted file mode 100644 index 4458d04f42..0000000000 --- a/src/Neo/Helper.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (C) 2015-2024 The Neo Project. -// -// Helper.cs file belongs to the neo project and is free -// software distributed under the MIT software license, see the -// accompanying file LICENSE in the main directory of the -// repository or http://www.opensource.org/licenses/mit-license.php -// for more details. -// -// Redistribution and use in source and binary forms with or without -// modifications are permitted. - -using Neo.IO.Caching; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Numerics; -using System.Reflection; - -namespace Neo -{ - /// - /// A helper class that provides common functions. - /// - public static class Helper - { - private static readonly DateTime unixEpoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - internal static void Remove(this HashSet set, ISet other) - { - if (set.Count > other.Count) - { - set.ExceptWith(other); - } - else - { - set.RemoveWhere(u => other.Contains(u)); - } - } - - internal static void Remove(this HashSet set, HashSetCache other) - where T : IEquatable - { - if (set.Count > other.Count) - { - set.ExceptWith(other); - } - else - { - set.RemoveWhere(u => other.Contains(u)); - } - } - - internal static void Remove(this HashSet set, IReadOnlyDictionary other) - { - if (set.Count > other.Count) - { - set.ExceptWith(other.Keys); - } - else - { - set.RemoveWhere(u => other.ContainsKey(u)); - } - } - - internal static string GetVersion(this Assembly assembly) - { - CustomAttributeData attribute = assembly.CustomAttributes.FirstOrDefault(p => p.AttributeType == typeof(AssemblyInformationalVersionAttribute)); - if (attribute == null) return assembly.GetName().Version.ToString(3); - return (string)attribute.ConstructorArguments[0].Value; - } - - /// - /// Converts a hex to byte array. - /// - /// The hex to convert. - /// The converted byte array. - public static byte[] HexToBytes(this string value) - { - if (value == null || value.Length == 0) - return Array.Empty(); - if (value.Length % 2 == 1) - throw new FormatException(); - byte[] result = new byte[value.Length / 2]; - for (int i = 0; i < result.Length; i++) - result[i] = byte.Parse(value.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier); - return result; - } - - internal static BigInteger NextBigInteger(this Random rand, int sizeInBits) - { - if (sizeInBits < 0) - throw new ArgumentException("sizeInBits must be non-negative"); - if (sizeInBits == 0) - return 0; - Span b = stackalloc byte[sizeInBits / 8 + 1]; - rand.NextBytes(b); - if (sizeInBits % 8 == 0) - b[^1] = 0; - else - b[^1] &= (byte)((1 << sizeInBits % 8) - 1); - return new BigInteger(b); - } - - /// - /// Converts a to timestamp. - /// - /// The to convert. - /// The converted timestamp. - public static uint ToTimestamp(this DateTime time) - { - return (uint)(time.ToUniversalTime() - unixEpoch).TotalSeconds; - } - - /// - /// Converts a to timestamp in milliseconds. - /// - /// The to convert. - /// The converted timestamp. - public static ulong ToTimestampMS(this DateTime time) - { - return (ulong)(time.ToUniversalTime() - unixEpoch).TotalMilliseconds; - } - - /// - /// Checks if address is IPv4 Mapped to IPv6 format, if so, Map to IPv4. - /// Otherwise, return current address. - /// - internal static IPAddress Unmap(this IPAddress address) - { - if (address.IsIPv4MappedToIPv6) - address = address.MapToIPv4(); - return address; - } - - /// - /// Checks if IPEndPoint is IPv4 Mapped to IPv6 format, if so, unmap to IPv4. - /// Otherwise, return current endpoint. - /// - internal static IPEndPoint Unmap(this IPEndPoint endPoint) - { - if (!endPoint.Address.IsIPv4MappedToIPv6) - return endPoint; - return new IPEndPoint(endPoint.Address.Unmap(), endPoint.Port); - } - } -} diff --git a/src/Neo/IO/Caching/ReflectionCache.cs b/src/Neo/IO/Caching/ReflectionCache.cs index 5007b67740..f24f4e5ab6 100644 --- a/src/Neo/IO/Caching/ReflectionCache.cs +++ b/src/Neo/IO/Caching/ReflectionCache.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using System; using System.Collections.Generic; using System.Reflection; diff --git a/src/Neo/IO/Helper.cs b/src/Neo/IO/Helper.cs deleted file mode 100644 index 2e6d362ee1..0000000000 --- a/src/Neo/IO/Helper.cs +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright (C) 2015-2024 The Neo Project. -// -// Helper.cs file belongs to the neo project and is free -// software distributed under the MIT software license, see the -// accompanying file LICENSE in the main directory of the -// repository or http://www.opensource.org/licenses/mit-license.php -// for more details. -// -// Redistribution and use in source and binary forms with or without -// modifications are permitted. - -using K4os.Compression.LZ4; -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace Neo.IO -{ - /// - /// A helper class for serialization of NEO objects. - /// - public static class Helper - { - /// - /// Converts a byte array to an object. - /// - /// The type to convert to. - /// The byte array to be converted. - /// The offset into the byte array from which to begin using data. - /// The converted object. - public static T AsSerializable(this byte[] value, int start = 0) where T : ISerializable, new() - { - MemoryReader reader = new(value.AsMemory(start)); - return reader.ReadSerializable(); - } - - /// - /// Converts a byte array to an object. - /// - /// The type to convert to. - /// The byte array to be converted. - /// The converted object. - public static T AsSerializable(this ReadOnlyMemory value) where T : ISerializable, new() - { - if (value.IsEmpty) throw new FormatException(); - MemoryReader reader = new(value); - return reader.ReadSerializable(); - } - - /// - /// Converts a byte array to an object. - /// - /// The byte array to be converted. - /// The type to convert to. - /// The converted object. - public static ISerializable AsSerializable(this ReadOnlyMemory value, Type type) - { - if (!typeof(ISerializable).GetTypeInfo().IsAssignableFrom(type)) - throw new InvalidCastException(); - ISerializable serializable = (ISerializable)Activator.CreateInstance(type); - MemoryReader reader = new(value); - serializable.Deserialize(ref reader); - return serializable; - } - - /// - /// Converts a byte array to an array. - /// - /// The type of the array element. - /// The byte array to be converted. - /// The maximum number of elements contained in the converted array. - /// The converted array. - public static T[] AsSerializableArray(this byte[] value, int max = 0x1000000) where T : ISerializable, new() - { - MemoryReader reader = new(value); - return reader.ReadSerializableArray(max); - } - - /// - /// Converts a byte array to an array. - /// - /// The type of the array element. - /// The byte array to be converted. - /// The maximum number of elements contained in the converted array. - /// The converted array. - public static T[] AsSerializableArray(this ReadOnlyMemory value, int max = 0x1000000) where T : ISerializable, new() - { - if (value.IsEmpty) throw new FormatException(); - MemoryReader reader = new(value); - return reader.ReadSerializableArray(max); - } - - /// - /// Compresses the specified data using the LZ4 algorithm. - /// - /// The data to be compressed. - /// The compressed data. - public static ReadOnlyMemory CompressLz4(this ReadOnlySpan data) - { - int maxLength = LZ4Codec.MaximumOutputSize(data.Length); - byte[] buffer = new byte[sizeof(uint) + maxLength]; - BinaryPrimitives.WriteInt32LittleEndian(buffer, data.Length); - int length = LZ4Codec.Encode(data, buffer.AsSpan(sizeof(uint))); - return buffer.AsMemory(0, sizeof(uint) + length); - } - - /// - /// Decompresses the specified data using the LZ4 algorithm. - /// - /// The compressed data. - /// The maximum data size after decompression. - /// The original data. - public static byte[] DecompressLz4(this ReadOnlySpan data, int maxOutput) - { - int length = BinaryPrimitives.ReadInt32LittleEndian(data); - if (length < 0 || length > maxOutput) throw new FormatException(); - byte[] result = new byte[length]; - if (LZ4Codec.Decode(data[4..], result) != length) - throw new FormatException(); - return result; - } - - /// - /// Gets the size of variable-length of the data. - /// - /// The length of the data. - /// The size of variable-length of the data. - public static int GetVarSize(int value) - { - if (value < 0xFD) - return sizeof(byte); - else if (value <= 0xFFFF) - return sizeof(byte) + sizeof(ushort); - else - return sizeof(byte) + sizeof(uint); - } - - /// - /// Gets the size of the specified array encoded in variable-length encoding. - /// - /// The type of the array element. - /// The specified array. - /// The size of the array. - public static int GetVarSize(this IReadOnlyCollection value) - { - int value_size; - Type t = typeof(T); - if (typeof(ISerializable).IsAssignableFrom(t)) - { - value_size = value.OfType().Sum(p => p.Size); - } - else if (t.GetTypeInfo().IsEnum) - { - int element_size; - Type u = t.GetTypeInfo().GetEnumUnderlyingType(); - if (u == typeof(sbyte) || u == typeof(byte)) - element_size = 1; - else if (u == typeof(short) || u == typeof(ushort)) - element_size = 2; - else if (u == typeof(int) || u == typeof(uint)) - element_size = 4; - else //if (u == typeof(long) || u == typeof(ulong)) - element_size = 8; - value_size = value.Count * element_size; - } - else - { - value_size = value.Count * Marshal.SizeOf(); - } - return GetVarSize(value.Count) + value_size; - } - - /// - /// Gets the size of the specified array encoded in variable-length encoding. - /// - /// The specified array. - /// The size of the array. - public static int GetVarSize(this ReadOnlyMemory value) - { - return GetVarSize(value.Length) + value.Length; - } - - /// - /// Gets the size of the specified encoded in variable-length encoding. - /// - /// The specified . - /// The size of the . - public static int GetVarSize(this string value) - { - int size = Utility.StrictUTF8.GetByteCount(value); - return GetVarSize(size) + size; - } - - /// - /// Reads a byte array of the specified size from a . - /// - /// The for reading data. - /// The size of the byte array. - /// The byte array read from the . - public static byte[] ReadFixedBytes(this BinaryReader reader, int size) - { - var index = 0; - var data = new byte[size]; - - while (size > 0) - { - var bytesRead = reader.Read(data, index, size); - - if (bytesRead <= 0) - { - throw new FormatException(); - } - - size -= bytesRead; - index += bytesRead; - } - - return data; - } - - /// - /// Reads an array from a . - /// - /// The type of the array element. - /// The for reading data. - /// The maximum number of elements in the array. - /// The array read from the . - public static T[] ReadNullableArray(this ref MemoryReader reader, int max = 0x1000000) where T : class, ISerializable, new() - { - T[] array = new T[reader.ReadVarInt((ulong)max)]; - for (int i = 0; i < array.Length; i++) - array[i] = reader.ReadBoolean() ? reader.ReadSerializable() : null; - return array; - } - - /// - /// Reads an object from a . - /// - /// The type of the object. - /// The for reading data. - /// The object read from the . - public static T ReadSerializable(this ref MemoryReader reader) where T : ISerializable, new() - { - T obj = new(); - obj.Deserialize(ref reader); - return obj; - } - - /// - /// Reads an array from a . - /// - /// The type of the array element. - /// The for reading data. - /// The maximum number of elements in the array. - /// The array read from the . - public static T[] ReadSerializableArray(this ref MemoryReader reader, int max = 0x1000000) where T : ISerializable, new() - { - T[] array = new T[reader.ReadVarInt((ulong)max)]; - for (int i = 0; i < array.Length; i++) - { - array[i] = new T(); - array[i].Deserialize(ref reader); - } - return array; - } - - /// - /// Reads a byte array from a . - /// - /// The for reading data. - /// The maximum size of the byte array. - /// The byte array read from the . - public static byte[] ReadVarBytes(this BinaryReader reader, int max = 0x1000000) - { - return reader.ReadFixedBytes((int)reader.ReadVarInt((ulong)max)); - } - - /// - /// Reads an integer from a . - /// - /// The for reading data. - /// The maximum value of the integer. - /// The integer read from the . - public static ulong ReadVarInt(this BinaryReader reader, ulong max = ulong.MaxValue) - { - byte fb = reader.ReadByte(); - ulong value; - if (fb == 0xFD) - value = reader.ReadUInt16(); - else if (fb == 0xFE) - value = reader.ReadUInt32(); - else if (fb == 0xFF) - value = reader.ReadUInt64(); - else - value = fb; - if (value > max) throw new FormatException(); - return value; - } - - /// - /// Converts an object to a byte array. - /// - /// The object to be converted. - /// The converted byte array. - public static byte[] ToArray(this ISerializable value) - { - using MemoryStream ms = new(); - using BinaryWriter writer = new(ms, Utility.StrictUTF8, true); - value.Serialize(writer); - writer.Flush(); - return ms.ToArray(); - } - - /// - /// Converts an array to a byte array. - /// - /// The type of the array element. - /// The array to be converted. - /// The converted byte array. - public static byte[] ToByteArray(this IReadOnlyCollection value) where T : ISerializable - { - using MemoryStream ms = new(); - using BinaryWriter writer = new(ms, Utility.StrictUTF8, true); - writer.Write(value); - writer.Flush(); - return ms.ToArray(); - } - - /// - /// Writes an object into a . - /// - /// The for writing data. - /// The object to be written. - public static void Write(this BinaryWriter writer, ISerializable value) - { - value.Serialize(writer); - } - - /// - /// Writes an array into a . - /// - /// The type of the array element. - /// The for writing data. - /// The array to be written. - public static void Write(this BinaryWriter writer, IReadOnlyCollection value) where T : ISerializable - { - writer.WriteVarInt(value.Count); - foreach (T item in value) - { - item.Serialize(writer); - } - } - - /// - /// Writes a into a . - /// - /// The for writing data. - /// The to be written. - /// The fixed size of the . - public static void WriteFixedString(this BinaryWriter writer, string value, int length) - { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (value.Length > length) - throw new ArgumentException(null, nameof(value)); - byte[] bytes = Utility.StrictUTF8.GetBytes(value); - if (bytes.Length > length) - throw new ArgumentException(null, nameof(value)); - writer.Write(bytes); - if (bytes.Length < length) - writer.Write(stackalloc byte[length - bytes.Length]); - } - - /// - /// Writes an array into a . - /// - /// The type of the array element. - /// The for writing data. - /// The array to be written. - public static void WriteNullableArray(this BinaryWriter writer, T[] value) where T : class, ISerializable - { - writer.WriteVarInt(value.Length); - foreach (var item in value) - { - bool isNull = item is null; - writer.Write(!isNull); - if (isNull) continue; - item.Serialize(writer); - } - } - - /// - /// Writes a byte array into a . - /// - /// The for writing data. - /// The byte array to be written. - public static void WriteVarBytes(this BinaryWriter writer, ReadOnlySpan value) - { - writer.WriteVarInt(value.Length); - writer.Write(value); - } - - /// - /// Writes an integer into a . - /// - /// The for writing data. - /// The integer to be written. - public static void WriteVarInt(this BinaryWriter writer, long value) - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value)); - if (value < 0xFD) - { - writer.Write((byte)value); - } - else if (value <= 0xFFFF) - { - writer.Write((byte)0xFD); - writer.Write((ushort)value); - } - else if (value <= 0xFFFFFFFF) - { - writer.Write((byte)0xFE); - writer.Write((uint)value); - } - else - { - writer.Write((byte)0xFF); - writer.Write(value); - } - } - - /// - /// Writes a into a . - /// - /// The for writing data. - /// The to be written. - public static void WriteVarString(this BinaryWriter writer, string value) - { - writer.WriteVarBytes(Utility.StrictUTF8.GetBytes(value)); - } - } -} diff --git a/src/Neo/NeoSystem.cs b/src/Neo/NeoSystem.cs index 3121432db5..99be387712 100644 --- a/src/Neo/NeoSystem.cs +++ b/src/Neo/NeoSystem.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Akka.Actor; +using Neo.Extensions; using Neo.IO.Caching; using Neo.Ledger; using Neo.Network.P2P; diff --git a/src/Neo/Network/P2P/Helper.cs b/src/Neo/Network/P2P/Helper.cs index f171a7b0a3..ffbbc6a702 100644 --- a/src/Neo/Network/P2P/Helper.cs +++ b/src/Neo/Network/P2P/Helper.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography; -using Neo.IO; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using System.IO; diff --git a/src/Neo/Network/P2P/Message.cs b/src/Neo/Network/P2P/Message.cs index 9d3c63a85b..96c79f2b10 100644 --- a/src/Neo/Network/P2P/Message.cs +++ b/src/Neo/Network/P2P/Message.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Akka.IO; +using Neo.Extensions; using Neo.IO; using Neo.IO.Caching; using System; diff --git a/src/Neo/Network/P2P/Payloads/AddrPayload.cs b/src/Neo/Network/P2P/Payloads/AddrPayload.cs index ebdceb65ec..90958a38ef 100644 --- a/src/Neo/Network/P2P/Payloads/AddrPayload.cs +++ b/src/Neo/Network/P2P/Payloads/AddrPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/Block.cs b/src/Neo/Network/P2P/Payloads/Block.cs index 3c727b9886..ab28c6c363 100644 --- a/src/Neo/Network/P2P/Payloads/Block.cs +++ b/src/Neo/Network/P2P/Payloads/Block.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Ledger; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/AndCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/AndCondition.cs index e395b10d5d..2fed4d32fb 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/AndCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/AndCondition.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/CalledByContractCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/CalledByContractCondition.cs index f853743b72..a4b1b7c20a 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/CalledByContractCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/CalledByContractCondition.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/CalledByGroupCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/CalledByGroupCondition.cs index d28cd9f8bf..2c9ab054c8 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/CalledByGroupCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/CalledByGroupCondition.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/GroupCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/GroupCondition.cs index 3187b62988..611ad7af09 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/GroupCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/GroupCondition.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/NotCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/NotCondition.cs index 83ecd4d973..8bf90454b0 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/NotCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/NotCondition.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conditions/OrCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/OrCondition.cs index b06fc922a8..32c0bfd718 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/OrCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/OrCondition.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; @@ -30,7 +31,14 @@ public class OrCondition : WitnessCondition /// public WitnessCondition[] Expressions; - public override int Size => base.Size + Expressions.GetVarSize(); + public override int Size + { + get + { + return base.Size + Expressions.GetVarSize(); + } + } + public override WitnessConditionType Type => WitnessConditionType.Or; protected override void DeserializeWithoutType(ref MemoryReader reader, int maxNestDepth) diff --git a/src/Neo/Network/P2P/Payloads/Conditions/ScriptHashCondition.cs b/src/Neo/Network/P2P/Payloads/Conditions/ScriptHashCondition.cs index 9199e1a9a2..de18bdfd1d 100644 --- a/src/Neo/Network/P2P/Payloads/Conditions/ScriptHashCondition.cs +++ b/src/Neo/Network/P2P/Payloads/Conditions/ScriptHashCondition.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/Conflicts.cs b/src/Neo/Network/P2P/Payloads/Conflicts.cs index 082de2014d..a876468828 100644 --- a/src/Neo/Network/P2P/Payloads/Conflicts.cs +++ b/src/Neo/Network/P2P/Payloads/Conflicts.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Persistence; diff --git a/src/Neo/Network/P2P/Payloads/ExtensiblePayload.cs b/src/Neo/Network/P2P/Payloads/ExtensiblePayload.cs index 306f6327ab..6e2b94a17d 100644 --- a/src/Neo/Network/P2P/Payloads/ExtensiblePayload.cs +++ b/src/Neo/Network/P2P/Payloads/ExtensiblePayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Persistence; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/FilterAddPayload.cs b/src/Neo/Network/P2P/Payloads/FilterAddPayload.cs index ff4aa1287b..4f4e9df152 100644 --- a/src/Neo/Network/P2P/Payloads/FilterAddPayload.cs +++ b/src/Neo/Network/P2P/Payloads/FilterAddPayload.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/FilterLoadPayload.cs b/src/Neo/Network/P2P/Payloads/FilterLoadPayload.cs index 2608e0e7b0..f0eae27278 100644 --- a/src/Neo/Network/P2P/Payloads/FilterLoadPayload.cs +++ b/src/Neo/Network/P2P/Payloads/FilterLoadPayload.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/GetBlocksPayload.cs b/src/Neo/Network/P2P/Payloads/GetBlocksPayload.cs index d12c8ae2cd..ccff8206c2 100644 --- a/src/Neo/Network/P2P/Payloads/GetBlocksPayload.cs +++ b/src/Neo/Network/P2P/Payloads/GetBlocksPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/Header.cs b/src/Neo/Network/P2P/Payloads/Header.cs index 9e1d77fb8a..8b3eda0e28 100644 --- a/src/Neo/Network/P2P/Payloads/Header.cs +++ b/src/Neo/Network/P2P/Payloads/Header.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Ledger; diff --git a/src/Neo/Network/P2P/Payloads/HeadersPayload.cs b/src/Neo/Network/P2P/Payloads/HeadersPayload.cs index 152ba32857..e5800d4544 100644 --- a/src/Neo/Network/P2P/Payloads/HeadersPayload.cs +++ b/src/Neo/Network/P2P/Payloads/HeadersPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/InvPayload.cs b/src/Neo/Network/P2P/Payloads/InvPayload.cs index aa4d340d99..17625f6dc4 100644 --- a/src/Neo/Network/P2P/Payloads/InvPayload.cs +++ b/src/Neo/Network/P2P/Payloads/InvPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.Collections.Generic; diff --git a/src/Neo/Network/P2P/Payloads/MerkleBlockPayload.cs b/src/Neo/Network/P2P/Payloads/MerkleBlockPayload.cs index aebb17d5d9..97f9ed0f27 100644 --- a/src/Neo/Network/P2P/Payloads/MerkleBlockPayload.cs +++ b/src/Neo/Network/P2P/Payloads/MerkleBlockPayload.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using System; using System.Collections; diff --git a/src/Neo/Network/P2P/Payloads/NetworkAddressWithTime.cs b/src/Neo/Network/P2P/Payloads/NetworkAddressWithTime.cs index d3cfd15f66..0b7e0acc37 100644 --- a/src/Neo/Network/P2P/Payloads/NetworkAddressWithTime.cs +++ b/src/Neo/Network/P2P/Payloads/NetworkAddressWithTime.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; using System; @@ -68,7 +69,7 @@ void ISerializable.Deserialize(ref MemoryReader reader) // Address ReadOnlyMemory data = reader.ReadMemory(16); - Address = new IPAddress(data.Span).Unmap(); + Address = new IPAddress(data.Span).UnMap(); // Capabilities Capabilities = new NodeCapability[reader.ReadVarInt(VersionPayload.MaxCapabilities)]; diff --git a/src/Neo/Network/P2P/Payloads/OracleResponse.cs b/src/Neo/Network/P2P/Payloads/OracleResponse.cs index 2770f556a8..bf3aa70cf4 100644 --- a/src/Neo/Network/P2P/Payloads/OracleResponse.cs +++ b/src/Neo/Network/P2P/Payloads/OracleResponse.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Persistence; diff --git a/src/Neo/Network/P2P/Payloads/PingPayload.cs b/src/Neo/Network/P2P/Payloads/PingPayload.cs index f6296a7713..6ac3d2d94e 100644 --- a/src/Neo/Network/P2P/Payloads/PingPayload.cs +++ b/src/Neo/Network/P2P/Payloads/PingPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Neo/Network/P2P/Payloads/Signer.cs b/src/Neo/Network/P2P/Payloads/Signer.cs index 79065408f4..9b5e317abc 100644 --- a/src/Neo/Network/P2P/Payloads/Signer.cs +++ b/src/Neo/Network/P2P/Payloads/Signer.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads.Conditions; diff --git a/src/Neo/Network/P2P/Payloads/Transaction.cs b/src/Neo/Network/P2P/Payloads/Transaction.cs index b922674d91..6f41b5141b 100644 --- a/src/Neo/Network/P2P/Payloads/Transaction.cs +++ b/src/Neo/Network/P2P/Payloads/Transaction.cs @@ -11,6 +11,7 @@ using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Ledger; diff --git a/src/Neo/Network/P2P/Payloads/VersionPayload.cs b/src/Neo/Network/P2P/Payloads/VersionPayload.cs index 8cec6278e7..f8fe74a856 100644 --- a/src/Neo/Network/P2P/Payloads/VersionPayload.cs +++ b/src/Neo/Network/P2P/Payloads/VersionPayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; using System; diff --git a/src/Neo/Network/P2P/Payloads/Witness.cs b/src/Neo/Network/P2P/Payloads/Witness.cs index 34932cc7fb..b3da47d2b7 100644 --- a/src/Neo/Network/P2P/Payloads/Witness.cs +++ b/src/Neo/Network/P2P/Payloads/Witness.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/src/Neo/Network/P2P/Payloads/WitnessRule.cs b/src/Neo/Network/P2P/Payloads/WitnessRule.cs index 3bac09e7f5..bb75cefd40 100644 --- a/src/Neo/Network/P2P/Payloads/WitnessRule.cs +++ b/src/Neo/Network/P2P/Payloads/WitnessRule.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads.Conditions; diff --git a/src/Neo/Network/P2P/Peer.cs b/src/Neo/Network/P2P/Peer.cs index 767d747b1d..074c5cf3ba 100644 --- a/src/Neo/Network/P2P/Peer.cs +++ b/src/Neo/Network/P2P/Peer.cs @@ -11,6 +11,7 @@ using Akka.Actor; using Akka.IO; +using Neo.Extensions; using Neo.IO; using System; using System.Buffers.Binary; @@ -138,7 +139,7 @@ protected virtual int ConnectingMax static Peer() { - localAddresses.UnionWith(NetworkInterface.GetAllNetworkInterfaces().SelectMany(p => p.GetIPProperties().UnicastAddresses).Select(p => p.Address.Unmap())); + localAddresses.UnionWith(NetworkInterface.GetAllNetworkInterfaces().SelectMany(p => p.GetIPProperties().UnicastAddresses).Select(p => p.Address.UnMap())); } /// @@ -163,7 +164,7 @@ protected void AddPeers(IEnumerable peers) /// Indicates whether the remote node is trusted. A trusted node will always be connected. protected void ConnectToPeer(IPEndPoint endPoint, bool isTrusted = false) { - endPoint = endPoint.Unmap(); + endPoint = endPoint.UnMap(); // If the address is the same, the ListenerTcpPort should be different, otherwise, return if (endPoint.Port == ListenerTcpPort && localAddresses.Contains(endPoint.Address)) return; @@ -210,7 +211,7 @@ protected override void OnReceive(object message) ConnectToPeer(connect.EndPoint, connect.IsTrusted); break; case Tcp.Connected connected: - OnTcpConnected(((IPEndPoint)connected.RemoteAddress).Unmap(), ((IPEndPoint)connected.LocalAddress).Unmap()); + OnTcpConnected(((IPEndPoint)connected.RemoteAddress).UnMap(), ((IPEndPoint)connected.LocalAddress).UnMap()); break; case Tcp.Bound _: tcp_listener = Sender; @@ -302,7 +303,7 @@ private void OnTcpCommandFailed(Tcp.Command cmd) switch (cmd) { case Tcp.Connect connect: - ImmutableInterlocked.Update(ref ConnectingPeers, p => p.Remove(((IPEndPoint)connect.RemoteAddress).Unmap())); + ImmutableInterlocked.Update(ref ConnectingPeers, p => p.Remove(((IPEndPoint)connect.RemoteAddress).UnMap())); break; } } diff --git a/src/Neo/Network/P2P/RemoteNode.cs b/src/Neo/Network/P2P/RemoteNode.cs index a4bf0cc089..e570afeb13 100644 --- a/src/Neo/Network/P2P/RemoteNode.cs +++ b/src/Neo/Network/P2P/RemoteNode.cs @@ -13,6 +13,7 @@ using Akka.Configuration; using Akka.IO; using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.IO.Actors; using Neo.IO.Caching; diff --git a/src/Neo/Network/P2P/TaskManager.cs b/src/Neo/Network/P2P/TaskManager.cs index e9c12e58a4..c5708df923 100644 --- a/src/Neo/Network/P2P/TaskManager.cs +++ b/src/Neo/Network/P2P/TaskManager.cs @@ -12,6 +12,7 @@ using Akka.Actor; using Akka.Configuration; using Akka.IO; +using Neo.Extensions; using Neo.IO.Actors; using Neo.IO.Caching; using Neo.Ledger; diff --git a/src/Neo/Persistence/SnapshotCache.cs b/src/Neo/Persistence/SnapshotCache.cs index 6731e5342f..07afdccfab 100644 --- a/src/Neo/Persistence/SnapshotCache.cs +++ b/src/Neo/Persistence/SnapshotCache.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.SmartContract; using System; using System.Collections.Generic; diff --git a/src/Neo/SmartContract/ApplicationEngine.cs b/src/Neo/SmartContract/ApplicationEngine.cs index 38430f3632..da2c7ba362 100644 --- a/src/Neo/SmartContract/ApplicationEngine.cs +++ b/src/Neo/SmartContract/ApplicationEngine.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/src/Neo/SmartContract/BinarySerializer.cs b/src/Neo/SmartContract/BinarySerializer.cs index 2bdeced678..29c33fee39 100644 --- a/src/Neo/SmartContract/BinarySerializer.cs +++ b/src/Neo/SmartContract/BinarySerializer.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/ContractParametersContext.cs b/src/Neo/SmartContract/ContractParametersContext.cs index c4129f0ad1..ea5ea35ab8 100644 --- a/src/Neo/SmartContract/ContractParametersContext.cs +++ b/src/Neo/SmartContract/ContractParametersContext.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/src/Neo/SmartContract/ContractState.cs b/src/Neo/SmartContract/ContractState.cs index 5b413c41a4..c323028346 100644 --- a/src/Neo/SmartContract/ContractState.cs +++ b/src/Neo/SmartContract/ContractState.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.SmartContract.Manifest; using Neo.VM; diff --git a/src/Neo/SmartContract/Helper.cs b/src/Neo/SmartContract/Helper.cs index d0bc3c939b..96ec2af03c 100644 --- a/src/Neo/SmartContract/Helper.cs +++ b/src/Neo/SmartContract/Helper.cs @@ -11,6 +11,7 @@ using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract.Manifest; diff --git a/src/Neo/SmartContract/Manifest/ContractGroup.cs b/src/Neo/SmartContract/Manifest/ContractGroup.cs index 231354327c..ffadf80769 100644 --- a/src/Neo/SmartContract/Manifest/ContractGroup.cs +++ b/src/Neo/SmartContract/Manifest/ContractGroup.cs @@ -11,7 +11,7 @@ using Neo.Cryptography; using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/Manifest/ContractPermission.cs b/src/Neo/SmartContract/Manifest/ContractPermission.cs index 44c67fd9a1..429b195b87 100644 --- a/src/Neo/SmartContract/Manifest/ContractPermission.cs +++ b/src/Neo/SmartContract/Manifest/ContractPermission.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/Manifest/ContractPermissionDescriptor.cs b/src/Neo/SmartContract/Manifest/ContractPermissionDescriptor.cs index d950d25c62..6cebaa99ee 100644 --- a/src/Neo/SmartContract/Manifest/ContractPermissionDescriptor.cs +++ b/src/Neo/SmartContract/Manifest/ContractPermissionDescriptor.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.VM.Types; using System; diff --git a/src/Neo/SmartContract/MethodToken.cs b/src/Neo/SmartContract/MethodToken.cs index 1b391edd32..1b8fa00242 100644 --- a/src/Neo/SmartContract/MethodToken.cs +++ b/src/Neo/SmartContract/MethodToken.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using System; diff --git a/src/Neo/SmartContract/Native/ContractManagement.cs b/src/Neo/SmartContract/Native/ContractManagement.cs index 6fefd2d05f..9fb66a063c 100644 --- a/src/Neo/SmartContract/Native/ContractManagement.cs +++ b/src/Neo/SmartContract/Native/ContractManagement.cs @@ -11,7 +11,7 @@ #pragma warning disable IDE0051 -using Neo.IO; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract.Iterators; diff --git a/src/Neo/SmartContract/Native/FungibleToken.cs b/src/Neo/SmartContract/Native/FungibleToken.cs index 21de0a5644..ab6ed8f9c0 100644 --- a/src/Neo/SmartContract/Native/FungibleToken.cs +++ b/src/Neo/SmartContract/Native/FungibleToken.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Persistence; using Neo.SmartContract.Manifest; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/Native/HashIndexState.cs b/src/Neo/SmartContract/Native/HashIndexState.cs index 229458ffdd..bca7fb28ac 100644 --- a/src/Neo/SmartContract/Native/HashIndexState.cs +++ b/src/Neo/SmartContract/Native/HashIndexState.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/Native/LedgerContract.cs b/src/Neo/SmartContract/Native/LedgerContract.cs index 329e0565d5..3d2d16e023 100644 --- a/src/Neo/SmartContract/Native/LedgerContract.cs +++ b/src/Neo/SmartContract/Native/LedgerContract.cs @@ -11,6 +11,7 @@ #pragma warning disable IDE0051 +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/src/Neo/SmartContract/Native/NeoToken.cs b/src/Neo/SmartContract/Native/NeoToken.cs index 40f63355df..d639a55caf 100644 --- a/src/Neo/SmartContract/Native/NeoToken.cs +++ b/src/Neo/SmartContract/Native/NeoToken.cs @@ -12,6 +12,7 @@ #pragma warning disable IDE0051 using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Persistence; using Neo.SmartContract.Iterators; diff --git a/src/Neo/SmartContract/Native/OracleContract.cs b/src/Neo/SmartContract/Native/OracleContract.cs index be4765581a..9baeea6ec3 100644 --- a/src/Neo/SmartContract/Native/OracleContract.cs +++ b/src/Neo/SmartContract/Native/OracleContract.cs @@ -12,7 +12,7 @@ #pragma warning disable IDE0051 using Neo.Cryptography; -using Neo.IO; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.VM; diff --git a/src/Neo/SmartContract/Native/OracleRequest.cs b/src/Neo/SmartContract/Native/OracleRequest.cs index d18968ef00..2114ad301d 100644 --- a/src/Neo/SmartContract/Native/OracleRequest.cs +++ b/src/Neo/SmartContract/Native/OracleRequest.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.VM; using Neo.VM.Types; using Array = Neo.VM.Types.Array; diff --git a/src/Neo/SmartContract/Native/RoleManagement.cs b/src/Neo/SmartContract/Native/RoleManagement.cs index d0437594c9..a67d454cd6 100644 --- a/src/Neo/SmartContract/Native/RoleManagement.cs +++ b/src/Neo/SmartContract/Native/RoleManagement.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.Persistence; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/SmartContract/Native/TransactionState.cs b/src/Neo/SmartContract/Native/TransactionState.cs index b17296b42d..050358f179 100644 --- a/src/Neo/SmartContract/Native/TransactionState.cs +++ b/src/Neo/SmartContract/Native/TransactionState.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.VM; diff --git a/src/Neo/SmartContract/Native/TrimmedBlock.cs b/src/Neo/SmartContract/Native/TrimmedBlock.cs index 4cc4c39c0f..c2bab2567c 100644 --- a/src/Neo/SmartContract/Native/TrimmedBlock.cs +++ b/src/Neo/SmartContract/Native/TrimmedBlock.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.VM; diff --git a/src/Neo/SmartContract/NefFile.cs b/src/Neo/SmartContract/NefFile.cs index 3e343d3be2..5638447688 100644 --- a/src/Neo/SmartContract/NefFile.cs +++ b/src/Neo/SmartContract/NefFile.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.VM; diff --git a/src/Neo/SmartContract/NotifyEventArgs.cs b/src/Neo/SmartContract/NotifyEventArgs.cs index 257efb3a66..9c88290c6d 100644 --- a/src/Neo/SmartContract/NotifyEventArgs.cs +++ b/src/Neo/SmartContract/NotifyEventArgs.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.VM; using Neo.VM.Types; diff --git a/src/Neo/VM/Helper.cs b/src/Neo/VM/Helper.cs index c6423ac1f1..efec792f13 100644 --- a/src/Neo/VM/Helper.cs +++ b/src/Neo/VM/Helper.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.SmartContract; using Neo.VM.Types; @@ -29,255 +29,6 @@ namespace Neo.VM /// public static class Helper { - /// - /// Emits the opcodes for creating an array. - /// - /// The type of the elements of the array. - /// The to be used. - /// The elements of the array. - /// The same instance as . - public static ScriptBuilder CreateArray(this ScriptBuilder builder, IReadOnlyList list = null) - { - if (list is null || list.Count == 0) - return builder.Emit(OpCode.NEWARRAY0); - for (int i = list.Count - 1; i >= 0; i--) - builder.EmitPush(list[i]); - builder.EmitPush(list.Count); - return builder.Emit(OpCode.PACK); - } - - /// - /// Emits the opcodes for creating a map. - /// - /// The type of the key of the map. - /// The type of the value of the map. - /// The to be used. - /// The key/value pairs of the map. - /// The same instance as . - public static ScriptBuilder CreateMap(this ScriptBuilder builder, IEnumerable> map = null) - { - builder.Emit(OpCode.NEWMAP); - if (map != null) - foreach (var p in map) - { - builder.Emit(OpCode.DUP); - builder.EmitPush(p.Key); - builder.EmitPush(p.Value); - builder.Emit(OpCode.SETITEM); - } - return builder; - } - - /// - /// Emits the specified opcodes. - /// - /// The to be used. - /// The opcodes to emit. - /// The same instance as . - public static ScriptBuilder Emit(this ScriptBuilder builder, params OpCode[] ops) - { - foreach (OpCode op in ops) - builder.Emit(op); - return builder; - } - - /// - /// Emits the opcodes for calling a contract dynamically. - /// - /// The to be used. - /// The hash of the contract to be called. - /// The method to be called in the contract. - /// The arguments for calling the contract. - /// The same instance as . - public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, params object[] args) - { - return EmitDynamicCall(builder, scriptHash, method, CallFlags.All, args); - } - - /// - /// Emits the opcodes for calling a contract dynamically. - /// - /// The to be used. - /// The hash of the contract to be called. - /// The method to be called in the contract. - /// The for calling the contract. - /// The arguments for calling the contract. - /// The same instance as . - public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, CallFlags flags, params object[] args) - { - builder.CreateArray(args); - builder.EmitPush(flags); - builder.EmitPush(method); - builder.EmitPush(scriptHash); - builder.EmitSysCall(ApplicationEngine.System_Contract_Call); - return builder; - } - - /// - /// Emits the opcodes for pushing the specified data onto the stack. - /// - /// The to be used. - /// The data to be pushed. - /// The same instance as . - public static ScriptBuilder EmitPush(this ScriptBuilder builder, ISerializable data) - { - return builder.EmitPush(data.ToArray()); - } - - /// - /// Emits the opcodes for pushing the specified data onto the stack. - /// - /// The to be used. - /// The data to be pushed. - /// The same instance as . - public static ScriptBuilder EmitPush(this ScriptBuilder builder, ContractParameter parameter) - { - if (parameter.Value is null) - builder.Emit(OpCode.PUSHNULL); - else - switch (parameter.Type) - { - case ContractParameterType.Signature: - case ContractParameterType.ByteArray: - builder.EmitPush((byte[])parameter.Value); - break; - case ContractParameterType.Boolean: - builder.EmitPush((bool)parameter.Value); - break; - case ContractParameterType.Integer: - if (parameter.Value is BigInteger bi) - builder.EmitPush(bi); - else - builder.EmitPush((BigInteger)typeof(BigInteger).GetConstructor(new[] { parameter.Value.GetType() }).Invoke(new[] { parameter.Value })); - break; - case ContractParameterType.Hash160: - builder.EmitPush((UInt160)parameter.Value); - break; - case ContractParameterType.Hash256: - builder.EmitPush((UInt256)parameter.Value); - break; - case ContractParameterType.PublicKey: - builder.EmitPush((ECPoint)parameter.Value); - break; - case ContractParameterType.String: - builder.EmitPush((string)parameter.Value); - break; - case ContractParameterType.Array: - { - IList parameters = (IList)parameter.Value; - for (int i = parameters.Count - 1; i >= 0; i--) - builder.EmitPush(parameters[i]); - builder.EmitPush(parameters.Count); - builder.Emit(OpCode.PACK); - } - break; - case ContractParameterType.Map: - { - var pairs = (IList>)parameter.Value; - builder.CreateMap(pairs); - } - break; - default: - throw new ArgumentException(null, nameof(parameter)); - } - return builder; - } - - /// - /// Emits the opcodes for pushing the specified data onto the stack. - /// - /// The to be used. - /// The data to be pushed. - /// The same instance as . - public static ScriptBuilder EmitPush(this ScriptBuilder builder, object obj) - { - switch (obj) - { - case bool data: - builder.EmitPush(data); - break; - case byte[] data: - builder.EmitPush(data); - break; - case string data: - builder.EmitPush(data); - break; - case BigInteger data: - builder.EmitPush(data); - break; - case ISerializable data: - builder.EmitPush(data); - break; - case sbyte data: - builder.EmitPush(data); - break; - case byte data: - builder.EmitPush(data); - break; - case short data: - builder.EmitPush(data); - break; - case char data: - builder.EmitPush((ushort)data); - break; - case ushort data: - builder.EmitPush(data); - break; - case int data: - builder.EmitPush(data); - break; - case uint data: - builder.EmitPush(data); - break; - case long data: - builder.EmitPush(data); - break; - case ulong data: - builder.EmitPush(data); - break; - case Enum data: - builder.EmitPush(BigInteger.Parse(data.ToString("d"))); - break; - case ContractParameter data: - builder.EmitPush(data); - break; - case null: - builder.Emit(OpCode.PUSHNULL); - break; - default: - throw new ArgumentException(null, nameof(obj)); - } - return builder; - } - - /// - /// Emits the opcodes for invoking an interoperable service. - /// - /// The to be used. - /// The hash of the interoperable service. - /// The arguments for calling the interoperable service. - /// The same instance as . - public static ScriptBuilder EmitSysCall(this ScriptBuilder builder, uint method, params object[] args) - { - for (int i = args.Length - 1; i >= 0; i--) - EmitPush(builder, args[i]); - return builder.EmitSysCall(method); - } - - /// - /// Generates the script for calling a contract dynamically. - /// - /// The hash of the contract to be called. - /// The method to be called in the contract. - /// The arguments for calling the contract. - /// The generated script. - public static byte[] MakeScript(this UInt160 scriptHash, string method, params object[] args) - { - using ScriptBuilder sb = new(); - sb.EmitDynamicCall(scriptHash, method, args); - return sb.ToArray(); - } - /// /// Converts the to a JSON object. /// @@ -289,24 +40,7 @@ public static JObject ToJson(this StackItem item, int maxSize = int.MaxValue) return ToJson(item, null, ref maxSize); } - /// - /// Converts the to a JSON object. - /// - /// The to convert. - /// The maximum size in bytes of the result. - /// The represented by a JSON object. - public static JArray ToJson(this EvaluationStack stack, int maxSize = int.MaxValue) - { - if (maxSize <= 0) throw new ArgumentOutOfRangeException(nameof(maxSize)); - maxSize -= 2/*[]*/+ Math.Max(0, (stack.Count - 1))/*,*/; - JArray result = new(); - foreach (var item in stack) - result.Add(ToJson(item, null, ref maxSize)); - if (maxSize < 0) throw new InvalidOperationException("Max size reached."); - return result; - } - - private static JObject ToJson(StackItem item, HashSet context, ref int maxSize) + public static JObject ToJson(this StackItem item, HashSet context, ref int maxSize) { JObject json = new() { diff --git a/src/Neo/Wallets/AssetDescriptor.cs b/src/Neo/Wallets/AssetDescriptor.cs index 7b9be7b16b..e8ba27b4e4 100644 --- a/src/Neo/Wallets/AssetDescriptor.cs +++ b/src/Neo/Wallets/AssetDescriptor.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Native; diff --git a/src/Neo/Wallets/Helper.cs b/src/Neo/Wallets/Helper.cs index b8427d078d..89dcb30034 100644 --- a/src/Neo/Wallets/Helper.cs +++ b/src/Neo/Wallets/Helper.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; @@ -93,7 +94,7 @@ public static long CalculateNetworkFee(this Transaction tx, DataCache snapshot, UInt160[] hashes = tx.GetScriptHashesForVerifying(snapshot); // base size for transaction: includes const_header + signers + attributes + script + hashes - int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Attributes.GetVarSize() + tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length), index = -1; + int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Attributes.GetVarSize() + tx.Script.GetVarSize() + UnsafeData.GetVarSize(hashes.Length), index = -1; uint exec_fee_factor = NativeContract.Policy.GetExecFeeFactor(snapshot); long networkFee = 0; foreach (UInt160 hash in hashes) @@ -151,7 +152,7 @@ public static long CalculateNetworkFee(this Transaction tx, DataCache snapshot, else if (IsMultiSigContract(witnessScript, out int m, out int n)) { int size_inv = 66 * m; - size += IO.Helper.GetVarSize(size_inv) + size_inv + witnessScript.GetVarSize(); + size += UnsafeData.GetVarSize(size_inv) + size_inv + witnessScript.GetVarSize(); networkFee += exec_fee_factor * MultiSignatureContractCost(m, n); } // We can support more contract types in the future. diff --git a/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs b/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs index 147a80034b..433359e261 100644 --- a/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs +++ b/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Persistence; using Neo.Plugins.ApplicationLogs.Store.States; using Neo.SmartContract; diff --git a/src/Plugins/ApplicationLogs/Store/States/BlockLogState.cs b/src/Plugins/ApplicationLogs/Store/States/BlockLogState.cs index 54369a672a..ce957b79f6 100644 --- a/src/Plugins/ApplicationLogs/Store/States/BlockLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/BlockLogState.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo; +using Neo.Extensions; using Neo.IO; namespace Neo.Plugins.ApplicationLogs.Store.States diff --git a/src/Plugins/ApplicationLogs/Store/States/EngineLogState.cs b/src/Plugins/ApplicationLogs/Store/States/EngineLogState.cs index 96f9041aaf..4a997757f5 100644 --- a/src/Plugins/ApplicationLogs/Store/States/EngineLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/EngineLogState.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; namespace Neo.Plugins.ApplicationLogs.Store.States diff --git a/src/Plugins/ApplicationLogs/Store/States/ExecutionLogState.cs b/src/Plugins/ApplicationLogs/Store/States/ExecutionLogState.cs index 210ac36283..ace7f0e42f 100644 --- a/src/Plugins/ApplicationLogs/Store/States/ExecutionLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/ExecutionLogState.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Ledger; using Neo.VM; diff --git a/src/Plugins/ApplicationLogs/Store/States/NotifyLogState.cs b/src/Plugins/ApplicationLogs/Store/States/NotifyLogState.cs index 70b53268e5..87cc5e60ae 100644 --- a/src/Plugins/ApplicationLogs/Store/States/NotifyLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/NotifyLogState.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo; +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; diff --git a/src/Plugins/ApplicationLogs/Store/States/TransactionEngineLogState.cs b/src/Plugins/ApplicationLogs/Store/States/TransactionEngineLogState.cs index 9417f984e2..80e5be7e97 100644 --- a/src/Plugins/ApplicationLogs/Store/States/TransactionEngineLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/TransactionEngineLogState.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; namespace Neo.Plugins.ApplicationLogs.Store.States diff --git a/src/Plugins/ApplicationLogs/Store/States/TransactionLogState.cs b/src/Plugins/ApplicationLogs/Store/States/TransactionLogState.cs index 1667478509..bca012ec50 100644 --- a/src/Plugins/ApplicationLogs/Store/States/TransactionLogState.cs +++ b/src/Plugins/ApplicationLogs/Store/States/TransactionLogState.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; namespace Neo.Plugins.ApplicationLogs.Store.States diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.Get.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.Get.cs index edffc1cb09..d055ddbb4a 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.Get.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.Get.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Plugins.DBFTPlugin.Messages; using Neo.SmartContract; @@ -110,7 +111,7 @@ internal int GetExpectedBlockSizeWithoutTransactions(int expectedTransactions) sizeof(byte) + // PrimaryIndex UInt160.Length + // NextConsensus 1 + _witnessSize + // Witness - IO.Helper.GetVarSize(expectedTransactions); + UnsafeData.GetVarSize(expectedTransactions); } } } diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs index f68f004c3c..a1e9b28bc4 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.Plugins.DBFTPlugin.Messages; diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs index 2e6a3a19a6..92b8ba0a0b 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs @@ -11,6 +11,7 @@ using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs index 3c6ab8e243..b00fdd9393 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs @@ -11,6 +11,7 @@ using Akka.Actor; using Neo.Cryptography; +using Neo.Extensions; using Neo.Ledger; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/DBFTPlugin/Messages/ConsensusMessage.cs b/src/Plugins/DBFTPlugin/Messages/ConsensusMessage.cs index de030d166d..f8cd8cbc14 100644 --- a/src/Plugins/DBFTPlugin/Messages/ConsensusMessage.cs +++ b/src/Plugins/DBFTPlugin/Messages/ConsensusMessage.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Plugins.DBFTPlugin.Types; using System; diff --git a/src/Plugins/DBFTPlugin/Messages/PrepareRequest.cs b/src/Plugins/DBFTPlugin/Messages/PrepareRequest.cs index 495ccbd726..c5b150b572 100644 --- a/src/Plugins/DBFTPlugin/Messages/PrepareRequest.cs +++ b/src/Plugins/DBFTPlugin/Messages/PrepareRequest.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Plugins.DBFTPlugin.Types; using System; diff --git a/src/Plugins/DBFTPlugin/Messages/PrepareResponse.cs b/src/Plugins/DBFTPlugin/Messages/PrepareResponse.cs index b4608ff9af..3c49693c69 100644 --- a/src/Plugins/DBFTPlugin/Messages/PrepareResponse.cs +++ b/src/Plugins/DBFTPlugin/Messages/PrepareResponse.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Plugins.DBFTPlugin.Types; using System.IO; diff --git a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs index 2d7283cd22..40528d8aaf 100644 --- a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs +++ b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs index 6d3880f3c0..dc7d532d30 100644 --- a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs +++ b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs index 8fae1596ef..cec8a45a3a 100644 --- a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs +++ b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs index 2de33470ea..2feb919520 100644 --- a/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs +++ b/src/Plugins/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Plugins.DBFTPlugin.Consensus; diff --git a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Cache.cs b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Cache.cs index d8baef8529..e832e8994b 100644 --- a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Cache.cs +++ b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Cache.cs @@ -9,7 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.IO; +using Neo.Extensions; using Neo.Persistence; using System.Collections.Generic; using System.IO; diff --git a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs index 510db49250..0d68564732 100644 --- a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs +++ b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; using System; diff --git a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs index e0190dd146..dc58535fb3 100644 --- a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs +++ b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs index 024a07f8c8..b1b7707729 100644 --- a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs +++ b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; using System; diff --git a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.cs b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.cs index ef45548645..2e20f03a9d 100644 --- a/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.cs +++ b/src/Plugins/MPTTrie/Cryptography/MPTTrie/Node.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; @@ -31,11 +32,11 @@ public int Size switch (type) { case NodeType.BranchNode: - return size + BranchSize + IO.Helper.GetVarSize(Reference); + return size + BranchSize + UnsafeData.GetVarSize(Reference); case NodeType.ExtensionNode: - return size + ExtensionSize + IO.Helper.GetVarSize(Reference); + return size + ExtensionSize + UnsafeData.GetVarSize(Reference); case NodeType.LeafNode: - return size + LeafSize + IO.Helper.GetVarSize(Reference); + return size + LeafSize + UnsafeData.GetVarSize(Reference); case NodeType.HashNode: return size + HashSize; case NodeType.Empty: diff --git a/src/Plugins/OracleService/OracleService.cs b/src/Plugins/OracleService/OracleService.cs index a6d91892a3..902c2f9677 100644 --- a/src/Plugins/OracleService/OracleService.cs +++ b/src/Plugins/OracleService/OracleService.cs @@ -444,8 +444,8 @@ public static Transaction CreateResponseTx(DataCache snapshot, OracleRequest req int size_inv = 66 * m; int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Script.GetVarSize() - + IO.Helper.GetVarSize(hashes.Length) + witnessDict[NativeContract.Oracle.Hash].Size - + IO.Helper.GetVarSize(size_inv) + size_inv + oracleSignContract.Script.GetVarSize(); + + UnsafeData.GetVarSize(hashes.Length) + witnessDict[NativeContract.Oracle.Hash].Size + + UnsafeData.GetVarSize(size_inv) + size_inv + oracleSignContract.Script.GetVarSize(); var feePerByte = NativeContract.Policy.GetFeePerByte(snapshot); if (response.Result.Length > OracleResponse.MaxResultSize) diff --git a/src/Plugins/RpcClient/ContractClient.cs b/src/Plugins/RpcClient/ContractClient.cs index f4ec020abc..02b8edc5ef 100644 --- a/src/Plugins/RpcClient/ContractClient.cs +++ b/src/Plugins/RpcClient/ContractClient.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Network.RPC.Models; using Neo.SmartContract; diff --git a/src/Plugins/RpcClient/Nep17API.cs b/src/Plugins/RpcClient/Nep17API.cs index 0870670231..c1f7324c4c 100644 --- a/src/Plugins/RpcClient/Nep17API.cs +++ b/src/Plugins/RpcClient/Nep17API.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Network.RPC.Models; using Neo.SmartContract; diff --git a/src/Plugins/RpcClient/RpcClient.cs b/src/Plugins/RpcClient/RpcClient.cs index 27b0023ec0..7866c7e40f 100644 --- a/src/Plugins/RpcClient/RpcClient.cs +++ b/src/Plugins/RpcClient/RpcClient.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/RpcClient/Utility.cs b/src/Plugins/RpcClient/Utility.cs index 659942f8f8..37331eec1b 100644 --- a/src/Plugins/RpcClient/Utility.cs +++ b/src/Plugins/RpcClient/Utility.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.Json; using Neo.Network.P2P.Payloads; using Neo.Network.P2P.Payloads.Conditions; diff --git a/src/Plugins/RpcServer/RpcServer.Node.cs b/src/Plugins/RpcServer/RpcServer.Node.cs index 716125e2cf..567629bd0d 100644 --- a/src/Plugins/RpcServer/RpcServer.Node.cs +++ b/src/Plugins/RpcServer/RpcServer.Node.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Akka.Actor; -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.Ledger; using Neo.Network.P2P; diff --git a/src/Plugins/RpcServer/RpcServer.SmartContract.cs b/src/Plugins/RpcServer/RpcServer.SmartContract.cs index 70edc4cedb..1cb1960cfc 100644 --- a/src/Plugins/RpcServer/RpcServer.SmartContract.cs +++ b/src/Plugins/RpcServer/RpcServer.SmartContract.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; @@ -189,7 +190,7 @@ private static Signer[] SignersFromJson(JArray _params, ProtocolSettings setting // Validate format - _ = IO.Helper.ToByteArray(ret).AsSerializableArray(); + _ = ret.ToByteArray().AsSerializableArray(); return ret; } diff --git a/src/Plugins/RpcServer/RpcServer.Wallet.cs b/src/Plugins/RpcServer/RpcServer.Wallet.cs index 50f3c7a1e0..909ab8f688 100644 --- a/src/Plugins/RpcServer/RpcServer.Wallet.cs +++ b/src/Plugins/RpcServer/RpcServer.Wallet.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Akka.Actor; -using Neo.IO; +using Neo.Extensions; using Neo.Json; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/src/Plugins/SQLiteWallet/SQLiteWallet.cs b/src/Plugins/SQLiteWallet/SQLiteWallet.cs index a4004dcff0..65f86ea8ff 100644 --- a/src/Plugins/SQLiteWallet/SQLiteWallet.cs +++ b/src/Plugins/SQLiteWallet/SQLiteWallet.cs @@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore; using Neo.Cryptography; -using Neo.IO; +using Neo.Extensions; using Neo.SmartContract; using Neo.Wallets.NEP6; using System.Buffers.Binary; diff --git a/src/Plugins/SQLiteWallet/VerificationContract.cs b/src/Plugins/SQLiteWallet/VerificationContract.cs index e128045adb..2f62a7174b 100644 --- a/src/Plugins/SQLiteWallet/VerificationContract.cs +++ b/src/Plugins/SQLiteWallet/VerificationContract.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; diff --git a/src/Plugins/StateService/Network/StateRoot.cs b/src/Plugins/StateService/Network/StateRoot.cs index 5b4e8610f2..7b3b7e9706 100644 --- a/src/Plugins/StateService/Network/StateRoot.cs +++ b/src/Plugins/StateService/Network/StateRoot.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P; diff --git a/src/Plugins/StateService/Network/Vote.cs b/src/Plugins/StateService/Network/Vote.cs index e6840c7a9f..bba40f6a54 100644 --- a/src/Plugins/StateService/Network/Vote.cs +++ b/src/Plugins/StateService/Network/Vote.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/StateService/StatePlugin.cs b/src/Plugins/StateService/StatePlugin.cs index 5f6e1ef1d8..fb3029803f 100644 --- a/src/Plugins/StateService/StatePlugin.cs +++ b/src/Plugins/StateService/StatePlugin.cs @@ -12,8 +12,8 @@ using Akka.Actor; using Neo.ConsoleService; using Neo.Cryptography.MPTTrie; +using Neo.Extensions; using Neo.IEventHandlers; -using Neo.IO; using Neo.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/StateService/Storage/StateSnapshot.cs b/src/Plugins/StateService/Storage/StateSnapshot.cs index 70ec006227..6dc1b323fd 100644 --- a/src/Plugins/StateService/Storage/StateSnapshot.cs +++ b/src/Plugins/StateService/Storage/StateSnapshot.cs @@ -10,7 +10,7 @@ // modifications are permitted. using Neo.Cryptography.MPTTrie; -using Neo.IO; +using Neo.Extensions; using Neo.Persistence; using Neo.Plugins.StateService.Network; using System; diff --git a/src/Plugins/StateService/Storage/StateStore.cs b/src/Plugins/StateService/Storage/StateStore.cs index f2ca6d7d05..beb19818bb 100644 --- a/src/Plugins/StateService/Storage/StateStore.cs +++ b/src/Plugins/StateService/Storage/StateStore.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Akka.Actor; +using Neo.Extensions; using Neo.IO; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/StateService/Verification/VerificationService.cs b/src/Plugins/StateService/Verification/VerificationService.cs index a8eb9fd030..3d77bc3501 100644 --- a/src/Plugins/StateService/Verification/VerificationService.cs +++ b/src/Plugins/StateService/Verification/VerificationService.cs @@ -11,6 +11,7 @@ using Akka.Actor; using Akka.Util.Internal; +using Neo.Extensions; using Neo.IO; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/StorageDumper/StorageDumper.cs b/src/Plugins/StorageDumper/StorageDumper.cs index c47df9ac1d..3b73465ad1 100644 --- a/src/Plugins/StorageDumper/StorageDumper.cs +++ b/src/Plugins/StorageDumper/StorageDumper.cs @@ -10,8 +10,8 @@ // modifications are permitted. using Neo.ConsoleService; +using Neo.Extensions; using Neo.IEventHandlers; -using Neo.IO; using Neo.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/TokensTracker/Extensions.cs b/src/Plugins/TokensTracker/Extensions.cs index 7805056280..83b4371435 100644 --- a/src/Plugins/TokensTracker/Extensions.cs +++ b/src/Plugins/TokensTracker/Extensions.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Persistence; using Neo.VM.Types; @@ -33,13 +34,13 @@ public static string ToBase64(this ReadOnlySpan item) public static int GetVarSize(this ByteString item) { var length = item.GetSpan().Length; - return IO.Helper.GetVarSize(length) + length; + return UnsafeData.GetVarSize(length) + length; } public static int GetVarSize(this BigInteger item) { var length = item.GetByteCount(); - return IO.Helper.GetVarSize(length) + length; + return UnsafeData.GetVarSize(length) + length; } public static IEnumerable<(TKey, TValue)> FindPrefix(this IStore db, byte[] prefix) diff --git a/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs b/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs index 1f375f33d9..2965985653 100644 --- a/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs +++ b/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.VM.Types; using System; diff --git a/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs b/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs index 5c999e8e00..9248267785 100644 --- a/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs +++ b/src/Plugins/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.VM.Types; using System; diff --git a/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs b/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs index bbceabec2b..817d789e5c 100644 --- a/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs +++ b/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs b/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs index d4698cba1e..71bfceb49d 100644 --- a/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs +++ b/src/Plugins/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/src/Plugins/TokensTracker/Trackers/TokenBalance.cs b/src/Plugins/TokensTracker/Trackers/TokenBalance.cs index f54a7c9856..a171fa40d7 100644 --- a/src/Plugins/TokensTracker/Trackers/TokenBalance.cs +++ b/src/Plugins/TokensTracker/Trackers/TokenBalance.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System.IO; using System.Numerics; diff --git a/src/Plugins/TokensTracker/Trackers/TokenTransfer.cs b/src/Plugins/TokensTracker/Trackers/TokenTransfer.cs index 0a221850fc..9bb389b516 100644 --- a/src/Plugins/TokensTracker/Trackers/TokenTransfer.cs +++ b/src/Plugins/TokensTracker/Trackers/TokenTransfer.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System.IO; using System.Numerics; diff --git a/src/Plugins/TokensTracker/Trackers/TokenTransferKey.cs b/src/Plugins/TokensTracker/Trackers/TokenTransferKey.cs index 252eb20af0..3c59131749 100644 --- a/src/Plugins/TokensTracker/Trackers/TokenTransferKey.cs +++ b/src/Plugins/TokensTracker/Trackers/TokenTransferKey.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using System; using System.Buffers.Binary; diff --git a/src/Plugins/TokensTracker/Trackers/TrackerBase.cs b/src/Plugins/TokensTracker/Trackers/TrackerBase.cs index 471362b019..40009e6d85 100644 --- a/src/Plugins/TokensTracker/Trackers/TrackerBase.cs +++ b/src/Plugins/TokensTracker/Trackers/TrackerBase.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Ledger; diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs index 05592d366b..e601ec1f07 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs @@ -17,7 +17,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using static Neo.Helper; +using static Neo.Extensions.HashSetExtensions; namespace Neo.Cryptography.MPTTrie.Tests { diff --git a/tests/Neo.Extensions.Tests/Collections/UT_HashSetExtensions.cs b/tests/Neo.Extensions.Tests/Collections/UT_HashSetExtensions.cs new file mode 100644 index 0000000000..cb475a7e5c --- /dev/null +++ b/tests/Neo.Extensions.Tests/Collections/UT_HashSetExtensions.cs @@ -0,0 +1,75 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_HashSetExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Neo.IO.Caching; +using System.Collections.Generic; +using System.Linq; + +namespace Neo.Extensions.Tests.Collections +{ + [TestClass] + public class UT_HashSetExtensions + { + [TestMethod] + public void TestRemoveHashsetDictionary() + { + var a = new HashSet + { + 1, + 2, + 3 + }; + + var b = new Dictionary + { + [2] = null + }; + + a.Remove(b); + + CollectionAssert.AreEqual(new int[] { 1, 3 }, a.ToArray()); + + b[4] = null; + b[5] = null; + b[1] = null; + a.Remove(b); + + CollectionAssert.AreEqual(new int[] { 3 }, a.ToArray()); + } + + [TestMethod] + public void TestRemoveHashsetSet() + { + var a = new HashSet + { + 1, + 2, + 3 + }; + + var b = new SortedSet() + { + 2 + }; + + a.Remove(b); + + CollectionAssert.AreEqual(new int[] { 1, 3 }, a.ToArray()); + + b.Add(4); + b.Add(5); + b.Add(1); + a.Remove(b); + + CollectionAssert.AreEqual(new int[] { 3 }, a.ToArray()); + } + } +} diff --git a/tests/Neo.Extensions.Tests/Net/UT_IpAddressExtensions.cs b/tests/Neo.Extensions.Tests/Net/UT_IpAddressExtensions.cs new file mode 100644 index 0000000000..bbf26c5cb7 --- /dev/null +++ b/tests/Neo.Extensions.Tests/Net/UT_IpAddressExtensions.cs @@ -0,0 +1,43 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_IpAddressExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using FluentAssertions; +using Neo.Extensions; +using System.Net; + +namespace Neo.Extensions.Tests.Net +{ + [TestClass] + public class UT_IpAddressExtensions + { + [TestMethod] + public void TestUnmapForIPAddress() + { + var addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); + addr.UnMap().Should().Be(addr); + + var addr2 = addr.MapToIPv6(); + addr2.UnMap().Should().Be(addr); + } + + [TestMethod] + public void TestUnmapForIPEndPoin() + { + var addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); + var endPoint = new IPEndPoint(addr, 8888); + endPoint.UnMap().Should().Be(endPoint); + + var addr2 = addr.MapToIPv6(); + var endPoint2 = new IPEndPoint(addr2, 8888); + endPoint2.UnMap().Should().Be(endPoint); + } + } +} diff --git a/tests/Neo.Extensions.Tests/UT_AssemblyExtensions.cs b/tests/Neo.Extensions.Tests/UT_AssemblyExtensions.cs new file mode 100644 index 0000000000..43f66f95da --- /dev/null +++ b/tests/Neo.Extensions.Tests/UT_AssemblyExtensions.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_AssemblyExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using FluentAssertions; +using System; +using System.Linq; + +namespace Neo.Extensions.Tests +{ + [TestClass] + public class UT_AssemblyExtensions + { + [TestMethod] + public void TestGetVersion() + { + // assembly without version + + var asm = AppDomain.CurrentDomain.GetAssemblies() + .Where(u => u.FullName == "Anonymously Hosted DynamicMethods Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") + .FirstOrDefault(); + string version = asm?.GetVersion() ?? ""; + version.Should().Be("0.0.0"); + } + } +} diff --git a/tests/Neo.Extensions.Tests/UT_BigIntegerExtensions.cs b/tests/Neo.Extensions.Tests/UT_BigIntegerExtensions.cs index b887d1c973..574dd87653 100644 --- a/tests/Neo.Extensions.Tests/UT_BigIntegerExtensions.cs +++ b/tests/Neo.Extensions.Tests/UT_BigIntegerExtensions.cs @@ -18,6 +18,7 @@ namespace Neo.Extensions.Tests [TestClass] public class UT_BigIntegerExtensions { + [TestMethod] public void TestGetLowestSetBit() { diff --git a/tests/Neo.Extensions.Tests/UT_DateTimeExtensions.cs b/tests/Neo.Extensions.Tests/UT_DateTimeExtensions.cs new file mode 100644 index 0000000000..43414a8f81 --- /dev/null +++ b/tests/Neo.Extensions.Tests/UT_DateTimeExtensions.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_DateTimeExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using FluentAssertions; +using System; + +namespace Neo.Extensions.Tests +{ + [TestClass] + public class UT_DateTimeExtensions + { + private static readonly DateTime unixEpoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + [TestMethod] + public void TestToTimestamp() + { + var time = DateTime.Now; + var expected = (uint)(time.ToUniversalTime() - unixEpoch).TotalSeconds; + var actual = time.ToTimestamp(); + + actual.Should().Be(expected); + } + + [TestMethod] + public void TestToTimestampMS() + { + var time = DateTime.Now; + var expected = (ulong)(time.ToUniversalTime() - unixEpoch).TotalMilliseconds; + var actual = time.ToTimestampMS(); + + actual.Should().Be(expected); + } + } +} diff --git a/tests/Neo.Extensions.Tests/UT_RandomExtensions.cs b/tests/Neo.Extensions.Tests/UT_RandomExtensions.cs new file mode 100644 index 0000000000..fb7c6a8cf7 --- /dev/null +++ b/tests/Neo.Extensions.Tests/UT_RandomExtensions.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_RandomExtensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using FluentAssertions; +using System; + +namespace Neo.Extensions.Tests +{ + [TestClass] + public class UT_RandomExtensions + { + [TestMethod] + public void TestNextBigIntegerForRandom() + { + Random ran = new(); + Action action1 = () => ran.NextBigInteger(-1); + action1.Should().Throw(); + + ran.NextBigInteger(0).Should().Be(0); + ran.NextBigInteger(8).Should().NotBeNull(); + ran.NextBigInteger(9).Should().NotBeNull(); + } + } +} diff --git a/tests/Neo.Extensions.Tests/UT_StringExtensions.cs b/tests/Neo.Extensions.Tests/UT_StringExtensions.cs new file mode 100644 index 0000000000..9c8ea927da --- /dev/null +++ b/tests/Neo.Extensions.Tests/UT_StringExtensions.cs @@ -0,0 +1,198 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_StringExtensdions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Neo.Extensions.Tests +{ + [TestClass] + public class UT_StringExtensions + { + [TestMethod] + public void TestHexToBytes() + { + string nullStr = null; + _ = nullStr.HexToBytes().ToHexString().Should().Be(Array.Empty().ToHexString()); + string emptyStr = ""; + emptyStr.HexToBytes().ToHexString().Should().Be(Array.Empty().ToHexString()); + string str1 = "hab"; + Action action = () => str1.HexToBytes(); + action.Should().Throw(); + string str2 = "0102"; + byte[] bytes = str2.HexToBytes(); + bytes.ToHexString().Should().Be(new byte[] { 0x01, 0x02 }.ToHexString()); + } + + [TestMethod] + public void TestGetVarSizeString() + { + int result = "AA".GetVarSize(); + Assert.AreEqual(3, result); + } + + [TestMethod] + public void TestGetVarSizeInt() + { + for (int i = 0; i < 3; i++) + { + if (i == 0) + { + int result = UnsafeData.GetVarSize(1); + Assert.AreEqual(1, result); + } + else if (i == 1) + { + int result = UnsafeData.GetVarSize(0xFFFF); + Assert.AreEqual(3, result); + } + else + { + int result = UnsafeData.GetVarSize(0xFFFFFF); + Assert.AreEqual(5, result); + } + } + } + + + [TestMethod] + public void TestGetVarSizeGeneric() + { + for (int i = 0; i < 9; i++) + { + if (i == 0) + { + int result = new UInt160[] { UInt160.Zero }.GetVarSize(); + Assert.AreEqual(21, result); + } + else if (i == 1)//sbyte + { + List initList = new() + { + TestEnum0.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(2, result); + } + else if (i == 2)//byte + { + List initList = new() + { + TestEnum1.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(2, result); + } + else if (i == 3)//short + { + List initList = new() + { + TestEnum2.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(3, result); + } + else if (i == 4)//ushort + { + List initList = new() + { + TestEnum3.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(3, result); + } + else if (i == 5)//int + { + List initList = new() + { + TestEnum4.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(5, result); + } + else if (i == 6)//uint + { + List initList = new() + { + TestEnum5.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(5, result); + } + else if (i == 7)//long + { + List initList = new() + { + TestEnum6.case1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(9, result); + } + else if (i == 8) + { + List initList = new() + { + 1 + }; + IReadOnlyCollection testList = initList.AsReadOnly(); + int result = testList.GetVarSize(); + Assert.AreEqual(5, result); + } + } + } + + enum TestEnum0 : sbyte + { + case1 = 1, case2 = 2 + } + + enum TestEnum1 : byte + { + case1 = 1, case2 = 2 + } + + enum TestEnum2 : short + { + case1 = 1, case2 = 2 + } + + enum TestEnum3 : ushort + { + case1 = 1, case2 = 2 + } + + enum TestEnum4 : int + { + case1 = 1, case2 = 2 + } + + enum TestEnum5 : uint + { + case1 = 1, case2 = 2 + } + + enum TestEnum6 : long + { + case1 = 1, case2 = 2 + } + } +} diff --git a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs index c3cf226a3e..6ac90dafc5 100644 --- a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs @@ -11,6 +11,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using Neo.Extensions; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs index 863d424405..d9a4cdb2ef 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs @@ -11,6 +11,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using Neo.Extensions; using Neo.Json; using Neo.SmartContract; using Neo.SmartContract.Native; @@ -19,7 +20,7 @@ using System.Linq; using System.Numerics; using System.Threading.Tasks; -using static Neo.Helper; +using static Neo.Extensions.HashSetExtensions; namespace Neo.Network.RPC.Tests { diff --git a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs index 7defa163ad..a05918c83f 100644 --- a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs @@ -11,6 +11,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using Neo.Extensions; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs index 4af0f557e3..ea2b0f4237 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs @@ -13,6 +13,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Moq.Protected; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index ae025cf65a..b7eecf2298 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -13,6 +13,7 @@ using Moq; using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P; diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs index ab5693937f..b779abf069 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs @@ -12,6 +12,7 @@ using Akka.Actor; using Akka.Util.Internal; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Ledger; diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs index c8b655024c..36c4d2bb01 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Wallet.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Wallet.cs index 2db71ae570..51d08dbf7e 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Wallet.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Wallet.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs b/tests/Neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs index 3d4e4c56f2..0d1e20c37a 100644 --- a/tests/Neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs +++ b/tests/Neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; +using Neo.Extensions; using System; using System.Globalization; using System.Numerics; diff --git a/tests/Neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs b/tests/Neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs index 4b0c7d484f..e5767acd37 100644 --- a/tests/Neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs +++ b/tests/Neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using System; using System.IO; diff --git a/tests/Neo.UnitTests/Cryptography/UT_Base58.cs b/tests/Neo.UnitTests/Cryptography/UT_Base58.cs index e7cb467dfa..091513862c 100644 --- a/tests/Neo.UnitTests/Cryptography/UT_Base58.cs +++ b/tests/Neo.UnitTests/Cryptography/UT_Base58.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; +using Neo.Extensions; using System; using System.Collections.Generic; diff --git a/tests/Neo.UnitTests/Cryptography/UT_Crypto.cs b/tests/Neo.UnitTests/Cryptography/UT_Crypto.cs index e311d6cafe..2f7de65b77 100644 --- a/tests/Neo.UnitTests/Cryptography/UT_Crypto.cs +++ b/tests/Neo.UnitTests/Cryptography/UT_Crypto.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; +using Neo.Extensions; using Neo.Wallets; using System; using System.Security.Cryptography; diff --git a/tests/Neo.UnitTests/Cryptography/UT_MerkleTree.cs b/tests/Neo.UnitTests/Cryptography/UT_MerkleTree.cs index f8a6b19b34..edcea4dd75 100644 --- a/tests/Neo.UnitTests/Cryptography/UT_MerkleTree.cs +++ b/tests/Neo.UnitTests/Cryptography/UT_MerkleTree.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using System; using System.Collections; diff --git a/tests/Neo.UnitTests/Extensions/NativeContractExtensions.cs b/tests/Neo.UnitTests/Extensions/NativeContractExtensions.cs index 9a282759a9..db2d23c16e 100644 --- a/tests/Neo.UnitTests/Extensions/NativeContractExtensions.cs +++ b/tests/Neo.UnitTests/Extensions/NativeContractExtensions.cs @@ -9,6 +9,7 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/Extensions/Nep17NativeContractExtensions.cs b/tests/Neo.UnitTests/Extensions/Nep17NativeContractExtensions.cs index a3f33f26a7..d32e16d0c6 100644 --- a/tests/Neo.UnitTests/Extensions/Nep17NativeContractExtensions.cs +++ b/tests/Neo.UnitTests/Extensions/Nep17NativeContractExtensions.cs @@ -10,6 +10,7 @@ // modifications are permitted. using FluentAssertions; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/IO/Caching/UT_DataCache.cs b/tests/Neo.UnitTests/IO/Caching/UT_DataCache.cs index 224b1cc3f6..3c5e8e6e7d 100644 --- a/tests/Neo.UnitTests/IO/Caching/UT_DataCache.cs +++ b/tests/Neo.UnitTests/IO/Caching/UT_DataCache.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Persistence; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/IO/UT_IOHelper.cs b/tests/Neo.UnitTests/IO/UT_IOHelper.cs index 48453c992a..514a8daaf5 100644 --- a/tests/Neo.UnitTests/IO/UT_IOHelper.cs +++ b/tests/Neo.UnitTests/IO/UT_IOHelper.cs @@ -31,7 +31,7 @@ public void TestAsSerializableGeneric() 0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00 }; - UInt160 result = Neo.IO.Helper.AsSerializable(caseArray); + UInt160 result = caseArray.AsSerializable(); Assert.AreEqual(UInt160.Zero, result); } @@ -44,7 +44,7 @@ public void TestReadFixedBytes() using (BinaryReader reader = new(new MemoryStream(data), Encoding.UTF8, false)) { - byte[] result = Neo.IO.Helper.ReadFixedBytes(reader, 3); + byte[] result = reader.ReadFixedBytes(3); Assert.AreEqual("010203", result.ToHexString()); Assert.AreEqual(3, reader.BaseStream.Position); @@ -54,7 +54,7 @@ public void TestReadFixedBytes() using (BinaryReader reader = new(new MemoryStream(data), Encoding.UTF8, false)) { - byte[] result = Neo.IO.Helper.ReadFixedBytes(reader, 4); + byte[] result = reader.ReadFixedBytes(4); Assert.AreEqual("01020304", result.ToHexString()); Assert.AreEqual(4, reader.BaseStream.Position); @@ -64,7 +64,7 @@ public void TestReadFixedBytes() using (BinaryReader reader = new(new MemoryStream(data), Encoding.UTF8, false)) { - Assert.ThrowsException(() => Neo.IO.Helper.ReadFixedBytes(reader, 5)); + Assert.ThrowsException(() => reader.ReadFixedBytes(5)); Assert.AreEqual(4, reader.BaseStream.Position); } } @@ -87,7 +87,7 @@ public void TestNullableArray() using (MemoryStream stream = new()) using (BinaryWriter writter = new(stream)) { - Neo.IO.Helper.WriteNullableArray(writter, caseArray); + writter.WriteNullableArray(caseArray); data = stream.ToArray(); } @@ -103,38 +103,43 @@ public void TestNullableArray() // Read 100% MemoryReader reader = new(data); - var read = Neo.IO.Helper.ReadNullableArray(ref reader); + var read = reader.ReadNullableArray(); CollectionAssert.AreEqual(caseArray, read); } [TestMethod] public void TestAsSerializable() { - for (int i = 0; i < 2; i++) - { - if (i == 0) - { - byte[] caseArray = new byte[] { 0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00 }; - ISerializable result = Neo.IO.Helper.AsSerializable(caseArray, typeof(UInt160)); - Assert.AreEqual(UInt160.Zero, result); - } - else - { - Action action = () => Neo.IO.Helper.AsSerializable(Array.Empty(), typeof(double)); - action.Should().Throw(); - } - } + byte[] caseArray = [0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00]; + ISerializable result = caseArray.AsSerializable(); + Assert.AreEqual(UInt160.Zero, result); } [TestMethod] public void TestCompression() { var data = new byte[] { 1, 2, 3, 4 }; - var byteArray = Neo.IO.Helper.CompressLz4(data); - var result = Neo.IO.Helper.DecompressLz4(byteArray.Span, byte.MaxValue); + var byteArray = data.CompressLz4(); + var result = byteArray.Span.DecompressLz4(byte.MaxValue); CollectionAssert.AreEqual(result, data); @@ -143,198 +148,41 @@ public void TestCompression() data = new byte[255]; for (int x = 0; x < data.Length; x++) data[x] = 1; - byteArray = Neo.IO.Helper.CompressLz4(data); - result = Neo.IO.Helper.DecompressLz4(byteArray.Span, byte.MaxValue); + byteArray = data.CompressLz4(); + result = byteArray.Span.DecompressLz4(byte.MaxValue); Assert.IsTrue(byteArray.Length < result.Length); CollectionAssert.AreEqual(result, data); // Error max length - Assert.ThrowsException(() => Neo.IO.Helper.DecompressLz4(byteArray.Span, byte.MaxValue - 1)); - Assert.ThrowsException(() => Neo.IO.Helper.DecompressLz4(byteArray.Span, -1)); + Assert.ThrowsException(() => byteArray.Span.DecompressLz4(byte.MaxValue - 1)); + Assert.ThrowsException(() => byteArray.Span.DecompressLz4(-1)); // Error length byte[] data_wrong = byteArray.ToArray(); data_wrong[0]++; - Assert.ThrowsException(() => Neo.IO.Helper.DecompressLz4(data_wrong, byte.MaxValue)); + Assert.ThrowsException(() => data_wrong.DecompressLz4(byte.MaxValue)); } [TestMethod] public void TestAsSerializableArray() { - byte[] byteArray = Neo.IO.Helper.ToByteArray(new UInt160[] { UInt160.Zero }); - UInt160[] result = Neo.IO.Helper.AsSerializableArray(byteArray); + byte[] byteArray = new UInt160[] { UInt160.Zero }.ToByteArray(); + UInt160[] result = byteArray.AsSerializableArray(); Assert.AreEqual(1, result.Length); Assert.AreEqual(UInt160.Zero, result[0]); } - [TestMethod] - public void TestGetVarSizeInt() - { - for (int i = 0; i < 3; i++) - { - if (i == 0) - { - int result = Neo.IO.Helper.GetVarSize(1); - Assert.AreEqual(1, result); - } - else if (i == 1) - { - int result = Neo.IO.Helper.GetVarSize(0xFFFF); - Assert.AreEqual(3, result); - } - else - { - int result = Neo.IO.Helper.GetVarSize(0xFFFFFF); - Assert.AreEqual(5, result); - } - } - } - enum TestEnum0 : sbyte - { - case1 = 1, case2 = 2 - } - - enum TestEnum1 : byte - { - case1 = 1, case2 = 2 - } - - enum TestEnum2 : short - { - case1 = 1, case2 = 2 - } - - enum TestEnum3 : ushort - { - case1 = 1, case2 = 2 - } - - enum TestEnum4 : int - { - case1 = 1, case2 = 2 - } - - enum TestEnum5 : uint - { - case1 = 1, case2 = 2 - } - - enum TestEnum6 : long - { - case1 = 1, case2 = 2 - } - - [TestMethod] - public void TestGetVarSizeGeneric() - { - for (int i = 0; i < 9; i++) - { - if (i == 0) - { - int result = Neo.IO.Helper.GetVarSize(new UInt160[] { UInt160.Zero }); - Assert.AreEqual(21, result); - } - else if (i == 1)//sbyte - { - List initList = new() - { - TestEnum0.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(2, result); - } - else if (i == 2)//byte - { - List initList = new() - { - TestEnum1.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(2, result); - } - else if (i == 3)//short - { - List initList = new() - { - TestEnum2.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(3, result); - } - else if (i == 4)//ushort - { - List initList = new() - { - TestEnum3.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(3, result); - } - else if (i == 5)//int - { - List initList = new() - { - TestEnum4.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(5, result); - } - else if (i == 6)//uint - { - List initList = new() - { - TestEnum5.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(5, result); - } - else if (i == 7)//long - { - List initList = new() - { - TestEnum6.case1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(9, result); - } - else if (i == 8) - { - List initList = new() - { - 1 - }; - IReadOnlyCollection testList = initList.AsReadOnly(); - int result = Neo.IO.Helper.GetVarSize(testList); - Assert.AreEqual(5, result); - } - } - } - - [TestMethod] - public void TestGetVarSizeString() - { - int result = Neo.IO.Helper.GetVarSize("AA"); - Assert.AreEqual(3, result); - } - [TestMethod] public void TestReadSerializable() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.Write(writer, UInt160.Zero); + writer.Write(UInt160.Zero); MemoryReader reader = new(stream.ToArray()); - UInt160 result = Neo.IO.Helper.ReadSerializable(ref reader); + UInt160 result = reader.ReadSerializable(); Assert.AreEqual(UInt160.Zero, result); } @@ -343,9 +191,9 @@ public void TestReadSerializableArray() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.Write(writer, new UInt160[] { UInt160.Zero }); + writer.Write(new UInt160[] { UInt160.Zero }); MemoryReader reader = new(stream.ToArray()); - UInt160[] resultArray = Neo.IO.Helper.ReadSerializableArray(ref reader); + UInt160[] resultArray = reader.ReadSerializableArray(); Assert.AreEqual(1, resultArray.Length); Assert.AreEqual(UInt160.Zero, resultArray[0]); } @@ -355,10 +203,10 @@ public void TestReadVarBytes() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarBytes(writer, new byte[] { 0xAA, 0xAA }); + writer.WriteVarBytes(new byte[] { 0xAA, 0xAA }); stream.Seek(0, SeekOrigin.Begin); BinaryReader reader = new(stream); - byte[] byteArray = Neo.IO.Helper.ReadVarBytes(reader, 10); + byte[] byteArray = reader.ReadVarBytes(10); Assert.AreEqual(Encoding.Default.GetString(new byte[] { 0xAA, 0xAA }), Encoding.Default.GetString(byteArray)); } @@ -371,30 +219,30 @@ public void TestReadVarInt() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFFFF); + writer.WriteVarInt(0xFFFF); stream.Seek(0, SeekOrigin.Begin); BinaryReader reader = new(stream); - ulong result = Neo.IO.Helper.ReadVarInt(reader, 0xFFFF); + ulong result = reader.ReadVarInt(0xFFFF); Assert.AreEqual((ulong)0xFFFF, result); } else if (i == 1) { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFFFFFFFF); + writer.WriteVarInt(0xFFFFFFFF); stream.Seek(0, SeekOrigin.Begin); BinaryReader reader = new(stream); - ulong result = Neo.IO.Helper.ReadVarInt(reader, 0xFFFFFFFF); + ulong result = reader.ReadVarInt(0xFFFFFFFF); Assert.AreEqual(0xFFFFFFFF, result); } else { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFFFFFFFFFF); + writer.WriteVarInt(0xFFFFFFFFFF); stream.Seek(0, SeekOrigin.Begin); BinaryReader reader = new(stream); - Action action = () => Neo.IO.Helper.ReadVarInt(reader, 0xFFFFFFFF); + Action action = () => reader.ReadVarInt(0xFFFFFFFF); action.Should().Throw(); } } @@ -403,7 +251,7 @@ public void TestReadVarInt() [TestMethod] public void TestToArray() { - byte[] byteArray = Neo.IO.Helper.ToArray(UInt160.Zero); + byte[] byteArray = UInt160.Zero.ToArray(); Assert.AreEqual(Encoding.Default.GetString(new byte[] { 0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00, @@ -413,7 +261,7 @@ public void TestToArray() [TestMethod] public void TestToByteArrayGeneric() { - byte[] byteArray = Neo.IO.Helper.ToByteArray(new UInt160[] { UInt160.Zero }); + byte[] byteArray = new UInt160[] { UInt160.Zero }.ToByteArray(); Assert.AreEqual(Encoding.Default.GetString(new byte[] { 0x01,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00, @@ -425,7 +273,7 @@ public void TestWrite() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.Write(writer, UInt160.Zero); + writer.Write(UInt160.Zero); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -440,7 +288,7 @@ public void TestWriteGeneric() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.Write(writer, new UInt160[] { UInt160.Zero }); + writer.Write(new UInt160[] { UInt160.Zero }); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -459,28 +307,28 @@ public void TestWriteFixedString() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Action action = () => Neo.IO.Helper.WriteFixedString(writer, null, 0); + Action action = () => writer.WriteFixedString(null, 0); action.Should().Throw(); } else if (i == 1) { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Action action = () => Neo.IO.Helper.WriteFixedString(writer, "AA", Encoding.UTF8.GetBytes("AA").Length - 1); + Action action = () => writer.WriteFixedString("AA", Encoding.UTF8.GetBytes("AA").Length - 1); action.Should().Throw(); } else if (i == 2) { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Action action = () => Neo.IO.Helper.WriteFixedString(writer, "拉拉", Encoding.UTF8.GetBytes("拉拉").Length - 1); + Action action = () => writer.WriteFixedString("拉拉", Encoding.UTF8.GetBytes("拉拉").Length - 1); action.Should().Throw(); } else if (i == 3) { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteFixedString(writer, "AA", Encoding.UTF8.GetBytes("AA").Length + 1); + writer.WriteFixedString("AA", Encoding.UTF8.GetBytes("AA").Length + 1); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -496,7 +344,7 @@ public void TestWriteVarBytes() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarBytes(writer, new byte[] { 0xAA }); + writer.WriteVarBytes(new byte[] { 0xAA }); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -512,14 +360,14 @@ public void TestWriteVarInt() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Action action = () => Neo.IO.Helper.WriteVarInt(writer, -1); + Action action = () => writer.WriteVarInt(-1); action.Should().Throw(); } else if (i == 1) { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFC); + writer.WriteVarInt(0xFC); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -529,7 +377,7 @@ public void TestWriteVarInt() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFFFF); + writer.WriteVarInt(0xFFFF); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -540,7 +388,7 @@ public void TestWriteVarInt() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xFFFFFFFF); + writer.WriteVarInt(0xFFFFFFFF); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -551,7 +399,7 @@ public void TestWriteVarInt() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarInt(writer, 0xAEFFFFFFFF); + writer.WriteVarInt(0xAEFFFFFFFF); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); @@ -566,7 +414,7 @@ public void TestWriteVarString() { MemoryStream stream = new(); BinaryWriter writer = new(stream); - Neo.IO.Helper.WriteVarString(writer, "a"); + writer.WriteVarString("a"); stream.Seek(0, SeekOrigin.Begin); byte[] byteArray = new byte[stream.Length]; stream.Read(byteArray, 0, (int)stream.Length); diff --git a/tests/Neo.UnitTests/IO/UT_MemoryReader.cs b/tests/Neo.UnitTests/IO/UT_MemoryReader.cs index a045a0b688..25278b3e22 100644 --- a/tests/Neo.UnitTests/IO/UT_MemoryReader.cs +++ b/tests/Neo.UnitTests/IO/UT_MemoryReader.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using System.IO; using System.Text; diff --git a/tests/Neo.UnitTests/Ledger/UT_MemoryPool.cs b/tests/Neo.UnitTests/Ledger/UT_MemoryPool.cs index 45cdee05c7..ca4e08341e 100644 --- a/tests/Neo.UnitTests/Ledger/UT_MemoryPool.cs +++ b/tests/Neo.UnitTests/Ledger/UT_MemoryPool.cs @@ -14,6 +14,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Ledger; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs b/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs index c3c5c2c86f..fbb2ca5106 100644 --- a/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs +++ b/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; diff --git a/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs b/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs index b113d59da7..cb538771dc 100644 --- a/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs +++ b/tests/Neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs index 6e189ad3ec..1308909d73 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Conflicts.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Conflicts.cs index a0dac53fbe..219c8cc684 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Conflicts.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Conflicts.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_ExtensiblePayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_ExtensiblePayload.cs index 1a0ad19a9a..28fdcaf068 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_ExtensiblePayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_ExtensiblePayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs index 76eff8e198..ae5a0e7758 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs index f73e9b5595..0661649215 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs index 3aa4049d87..5859d974ce 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs index 6752525ac0..ccd4e7aaed 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs index 9ecdd7f5e4..1c11871225 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs index 09454d298f..0bdb4982c8 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract.Native; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs index 4735fddfe1..c799ff8289 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs index f491d46749..b1849f1332 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using System; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs index 2ed86e4da7..3e2c6c336c 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NotValidBefore.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NotValidBefore.cs index bff21a4e5e..193f14902d 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NotValidBefore.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_NotValidBefore.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract.Native; diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs index dc910c5142..97bb61a98a 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs @@ -825,7 +825,7 @@ public void Transaction_Serialize_Deserialize_Simple() "010000"); // empty witnesses // try to deserialize - var tx2 = sTx.AsSerializable(); + Transaction tx2 = sTx.AsSerializable(); tx2.Version.Should().Be(0x00); tx2.Nonce.Should().Be(0x01020304); @@ -887,7 +887,7 @@ public void Transaction_Serialize_Deserialize_DistinctCosigners() // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; Assert.ThrowsException(() => - tx2 = Neo.IO.Helper.AsSerializable(sTx) + tx2 = sTx.AsSerializable() ); Assert.IsNull(tx2); } diff --git a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs index a77740a1e5..66bebf68d8 100644 --- a/tests/Neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs +++ b/tests/Neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Capabilities; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Network/P2P/UT_Message.cs b/tests/Neo.UnitTests/Network/P2P/UT_Message.cs index 35f99fc44f..7a43cf89a4 100644 --- a/tests/Neo.UnitTests/Network/P2P/UT_Message.cs +++ b/tests/Neo.UnitTests/Network/P2P/UT_Message.cs @@ -12,6 +12,7 @@ using Akka.IO; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/Network/P2P/UT_RemoteNode.cs b/tests/Neo.UnitTests/Network/P2P/UT_RemoteNode.cs index 9f114e2708..cfa94a3113 100644 --- a/tests/Neo.UnitTests/Network/P2P/UT_RemoteNode.cs +++ b/tests/Neo.UnitTests/Network/P2P/UT_RemoteNode.cs @@ -13,6 +13,7 @@ using Akka.TestKit.Xunit2; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P; using Neo.Network.P2P.Capabilities; diff --git a/tests/Neo.UnitTests/Persistence/UT_MemoryStore.cs b/tests/Neo.UnitTests/Persistence/UT_MemoryStore.cs index 133d9eb66c..ec49c12040 100644 --- a/tests/Neo.UnitTests/Persistence/UT_MemoryStore.cs +++ b/tests/Neo.UnitTests/Persistence/UT_MemoryStore.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Persistence; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/SmartContract/Manifest/UT_ContractManifest.cs b/tests/Neo.UnitTests/SmartContract/Manifest/UT_ContractManifest.cs index 4e2e866281..fdbcf671b2 100644 --- a/tests/Neo.UnitTests/SmartContract/Manifest/UT_ContractManifest.cs +++ b/tests/Neo.UnitTests/SmartContract/Manifest/UT_ContractManifest.cs @@ -11,6 +11,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/SmartContract/Native/UT_GasToken.cs b/tests/Neo.UnitTests/SmartContract/Native/UT_GasToken.cs index a7d087fa86..b6e41c559f 100644 --- a/tests/Neo.UnitTests/SmartContract/Native/UT_GasToken.cs +++ b/tests/Neo.UnitTests/SmartContract/Native/UT_GasToken.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/SmartContract/Native/UT_NativeContract.cs b/tests/Neo.UnitTests/SmartContract/Native/UT_NativeContract.cs index f9a3089f9d..64d6338f0c 100644 --- a/tests/Neo.UnitTests/SmartContract/Native/UT_NativeContract.cs +++ b/tests/Neo.UnitTests/SmartContract/Native/UT_NativeContract.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/SmartContract/Native/UT_PolicyContract.cs b/tests/Neo.UnitTests/SmartContract/Native/UT_PolicyContract.cs index 745670977e..d5e6f22800 100644 --- a/tests/Neo.UnitTests/SmartContract/Native/UT_PolicyContract.cs +++ b/tests/Neo.UnitTests/SmartContract/Native/UT_PolicyContract.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.Contract.cs b/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.Contract.cs index f9dc5e7b46..2d71b97e25 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.Contract.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.Contract.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.SmartContract; using Neo.VM; using System.Linq; diff --git a/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.cs b/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.cs index a670e3b4b7..0722a4e15c 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_ApplicationEngine.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.UnitTests.Extensions; diff --git a/tests/Neo.UnitTests/SmartContract/UT_Contract.cs b/tests/Neo.UnitTests/SmartContract/UT_Contract.cs index 07ae320a0f..ecd8532faa 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_Contract.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_Contract.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; diff --git a/tests/Neo.UnitTests/SmartContract/UT_MethodToken.cs b/tests/Neo.UnitTests/SmartContract/UT_MethodToken.cs index 9d687e1053..b6be60cdab 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_MethodToken.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_MethodToken.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; using System; diff --git a/tests/Neo.UnitTests/SmartContract/UT_NefFile.cs b/tests/Neo.UnitTests/SmartContract/UT_NefFile.cs index 40142e93be..b5fb90fe22 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_NefFile.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_NefFile.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.SmartContract; using System; diff --git a/tests/Neo.UnitTests/SmartContract/UT_SmartContractHelper.cs b/tests/Neo.UnitTests/SmartContract/UT_SmartContractHelper.cs index 42308d91f2..d223c747f6 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_SmartContractHelper.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_SmartContractHelper.cs @@ -10,6 +10,7 @@ // modifications are permitted. using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/SmartContract/UT_Syscalls.cs b/tests/Neo.UnitTests/SmartContract/UT_Syscalls.cs index a864c5d427..e2f89751c1 100644 --- a/tests/Neo.UnitTests/SmartContract/UT_Syscalls.cs +++ b/tests/Neo.UnitTests/SmartContract/UT_Syscalls.cs @@ -12,6 +12,7 @@ using Akka.TestKit.Xunit2; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/TestUtils.Block.cs b/tests/Neo.UnitTests/TestUtils.Block.cs index bed85131e6..dd1ad77625 100644 --- a/tests/Neo.UnitTests/TestUtils.Block.cs +++ b/tests/Neo.UnitTests/TestUtils.Block.cs @@ -11,6 +11,7 @@ using Akka.Util.Internal; using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/TestUtils.Transaction.cs b/tests/Neo.UnitTests/TestUtils.Transaction.cs index f6d6ebd4b5..70ac264a19 100644 --- a/tests/Neo.UnitTests/TestUtils.Transaction.cs +++ b/tests/Neo.UnitTests/TestUtils.Transaction.cs @@ -12,6 +12,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.UnitTests/TestUtils.cs b/tests/Neo.UnitTests/TestUtils.cs index a9ad4d8ff7..3b768940e8 100644 --- a/tests/Neo.UnitTests/TestUtils.cs +++ b/tests/Neo.UnitTests/TestUtils.cs @@ -13,6 +13,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; using Neo.Cryptography.ECC; +using Neo.Extensions; using Neo.IO; using Neo.Json; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.UnitTests/UT_Helper.cs b/tests/Neo.UnitTests/UT_Helper.cs index 413c9dcf31..70e1cec074 100644 --- a/tests/Neo.UnitTests/UT_Helper.cs +++ b/tests/Neo.UnitTests/UT_Helper.cs @@ -147,6 +147,22 @@ public void TestRemoveHashsetHashSetCache() CollectionAssert.AreEqual(new int[] { 3 }, a.ToArray()); } + [TestMethod] + public void TestToHexString() + { + byte[] nullStr = null; + Assert.ThrowsException(() => nullStr.ToHexString()); + byte[] empty = Array.Empty(); + empty.ToHexString().Should().Be(""); + empty.ToHexString(false).Should().Be(""); + empty.ToHexString(true).Should().Be(""); + + byte[] str1 = new byte[] { (byte)'n', (byte)'e', (byte)'o' }; + str1.ToHexString().Should().Be("6e656f"); + str1.ToHexString(false).Should().Be("6e656f"); + str1.ToHexString(true).Should().Be("6f656e"); + } + [TestMethod] public void TestGetVersion() { @@ -159,6 +175,16 @@ public void TestGetVersion() version.Should().Be("0.0.0"); } + [TestMethod] + public void TestToByteArrayStandard() + { + BigInteger number = BigInteger.Zero; + Assert.AreEqual("", number.ToByteArrayStandard().ToHexString()); + + number = BigInteger.One; + Assert.AreEqual("01", number.ToByteArrayStandard().ToHexString()); + } + [TestMethod] public void TestNextBigIntegerForRandom() { @@ -175,10 +201,10 @@ public void TestNextBigIntegerForRandom() public void TestUnmapForIPAddress() { var addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); - addr.Unmap().Should().Be(addr); + addr.UnMap().Should().Be(addr); var addr2 = addr.MapToIPv6(); - addr2.Unmap().Should().Be(addr); + addr2.UnMap().Should().Be(addr); } [TestMethod] @@ -186,11 +212,11 @@ public void TestUnmapForIPEndPoin() { var addr = new IPAddress(new byte[] { 127, 0, 0, 1 }); var endPoint = new IPEndPoint(addr, 8888); - endPoint.Unmap().Should().Be(endPoint); + endPoint.UnMap().Should().Be(endPoint); var addr2 = addr.MapToIPv6(); var endPoint2 = new IPEndPoint(addr2, 8888); - endPoint2.Unmap().Should().Be(endPoint); + endPoint2.UnMap().Should().Be(endPoint); } } } diff --git a/tests/Neo.UnitTests/VM/UT_Helper.cs b/tests/Neo.UnitTests/VM/UT_Helper.cs index 3e83256669..167566f27e 100644 --- a/tests/Neo.UnitTests/VM/UT_Helper.cs +++ b/tests/Neo.UnitTests/VM/UT_Helper.cs @@ -428,7 +428,7 @@ private void TestEmitPush3Ulong() { ScriptBuilder sb = new ScriptBuilder(); ulong temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -438,7 +438,7 @@ private void TestEmitPush3Long() { ScriptBuilder sb = new ScriptBuilder(); long temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -448,7 +448,7 @@ private void TestEmitPush3Uint() { ScriptBuilder sb = new ScriptBuilder(); uint temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -458,7 +458,7 @@ private void TestEmitPush3Int() { ScriptBuilder sb = new ScriptBuilder(); int temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -468,7 +468,7 @@ private void TestEmitPush3Ushort() { ScriptBuilder sb = new ScriptBuilder(); ushort temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -478,7 +478,7 @@ private void TestEmitPush3Char() { ScriptBuilder sb = new ScriptBuilder(); char temp = char.MinValue; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -488,7 +488,7 @@ private void TestEmitPush3Short() { ScriptBuilder sb = new ScriptBuilder(); short temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -498,7 +498,7 @@ private void TestEmitPush3Byte() { ScriptBuilder sb = new ScriptBuilder(); byte temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); @@ -508,7 +508,7 @@ private void TestEmitPush3Sbyte() { ScriptBuilder sb = new ScriptBuilder(); sbyte temp = 0; - VM.Helper.EmitPush(sb, temp); + sb.EmitPush(temp); byte[] tempArray = new byte[1]; tempArray[0] = (byte)OpCode.PUSH0; CollectionAssert.AreEqual(tempArray, sb.ToArray()); diff --git a/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Contract.cs b/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Contract.cs index 37f816c240..bac6c0d4eb 100644 --- a/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Contract.cs +++ b/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Contract.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.Json; using Neo.SmartContract; using Neo.Wallets.NEP6; diff --git a/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Wallet.cs b/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Wallet.cs index a914b235b7..3f3a61ca03 100644 --- a/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Wallet.cs +++ b/tests/Neo.UnitTests/Wallets/NEP6/UT_NEP6Wallet.cs @@ -11,6 +11,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Extensions; using Neo.Json; using Neo.Network.P2P.Payloads; using Neo.SmartContract; diff --git a/tests/Neo.UnitTests/Wallets/UT_Wallets_Helper.cs b/tests/Neo.UnitTests/Wallets/UT_Wallets_Helper.cs index 843eeae192..055ea193f7 100644 --- a/tests/Neo.UnitTests/Wallets/UT_Wallets_Helper.cs +++ b/tests/Neo.UnitTests/Wallets/UT_Wallets_Helper.cs @@ -12,6 +12,7 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography; +using Neo.Extensions; using Neo.IO; using Neo.Wallets; using System;