diff --git a/src/neo/Network/P2P/TaskSession.cs b/src/neo/Network/P2P/TaskSession.cs index 859f282d35..6680f27511 100644 --- a/src/neo/Network/P2P/TaskSession.cs +++ b/src/neo/Network/P2P/TaskSession.cs @@ -20,7 +20,7 @@ public TaskSession(VersionPayload version) { var fullNode = version.Capabilities.OfType().FirstOrDefault(); this.IsFullNode = fullNode != null; - this.LastBlockIndex = fullNode.StartHeight; + this.LastBlockIndex = fullNode?.StartHeight ?? 0; } } } diff --git a/src/neo/Network/UPnP.cs b/src/neo/Network/UPnP.cs index 6ec770271c..1a5eec4a29 100644 --- a/src/neo/Network/UPnP.cs +++ b/src/neo/Network/UPnP.cs @@ -107,7 +107,7 @@ public static void ForwardPort(int port, ProtocolType protocol, string descripti { if (string.IsNullOrEmpty(_serviceUrl)) throw new Exception("No UPnP service available or Discover() has not been called"); - XmlDocument xdoc = SOAPRequest(_serviceUrl, "" + + SOAPRequest(_serviceUrl, "" + "" + port.ToString() + "" + protocol.ToString().ToUpper() + "" + "" + port.ToString() + "" + Dns.GetHostAddresses(Dns.GetHostName()).First(p => p.AddressFamily == AddressFamily.InterNetwork).ToString() + "1" + description + @@ -118,7 +118,7 @@ public static void DeleteForwardingRule(int port, ProtocolType protocol) { if (string.IsNullOrEmpty(_serviceUrl)) throw new Exception("No UPnP service available or Discover() has not been called"); - XmlDocument xdoc = SOAPRequest(_serviceUrl, + SOAPRequest(_serviceUrl, "" + "" + "" + diff --git a/src/neo/SmartContract/ApplicationEngine.cs b/src/neo/SmartContract/ApplicationEngine.cs index 61ec30d55a..cd114e9bb7 100644 --- a/src/neo/SmartContract/ApplicationEngine.cs +++ b/src/neo/SmartContract/ApplicationEngine.cs @@ -49,9 +49,9 @@ private class InvocationState public long GasConsumed { get; private set; } = 0; public long GasLeft => gas_amount - GasConsumed; public Exception FaultException { get; private set; } - public UInt160 CurrentScriptHash => CurrentContext?.GetState().ScriptHash; + public UInt160 CurrentScriptHash => CurrentContext?.GetScriptHash(); public UInt160 CallingScriptHash => CurrentContext?.GetState().CallingScriptHash; - public UInt160 EntryScriptHash => EntryContext?.GetState().ScriptHash; + public UInt160 EntryScriptHash => EntryContext?.GetScriptHash(); public IReadOnlyList Notifications => notifications ?? (IReadOnlyList)Array.Empty(); protected ApplicationEngine(TriggerType trigger, IVerifiable container, StoreView snapshot, long gas) diff --git a/tests/neo.UnitTests/Consensus/UT_ChangeViewPayloadCompact.cs b/tests/neo.UnitTests/Consensus/UT_ChangeViewPayloadCompact.cs new file mode 100644 index 0000000000..419c9bb4a1 --- /dev/null +++ b/tests/neo.UnitTests/Consensus/UT_ChangeViewPayloadCompact.cs @@ -0,0 +1,46 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Consensus; +using Neo.IO; +using Neo.Network.P2P.Payloads; + +namespace Neo.UnitTests.Consensus +{ + [TestClass] + public class UT_ChangeViewPayloadCompact + { + [TestMethod] + public void Size_Get() + { + var test = new RecoveryMessage.ChangeViewPayloadCompact() { Timestamp = 1, ValidatorIndex = 1, InvocationScript = new byte[0], OriginalViewNumber = 1 }; + ((ISerializable)test).Size.Should().Be(12); + + test = new RecoveryMessage.ChangeViewPayloadCompact() { Timestamp = 1, ValidatorIndex = 1, InvocationScript = new byte[1024], OriginalViewNumber = 1 }; + ((ISerializable)test).Size.Should().Be(1038); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new RecoveryMessage.ChangeViewPayloadCompact() { Timestamp = 1, ValidatorIndex = 2, InvocationScript = new byte[] { 1, 2, 3 }, OriginalViewNumber = 3 }; + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Timestamp, clone.Timestamp); + Assert.AreEqual(test.ValidatorIndex, clone.ValidatorIndex); + Assert.AreEqual(test.OriginalViewNumber, clone.OriginalViewNumber); + CollectionAssert.AreEqual(test.InvocationScript, clone.InvocationScript); + + clone = RecoveryMessage.ChangeViewPayloadCompact.FromPayload(new ConsensusPayload() + { + Data = new ChangeView() { Timestamp = 1, ViewNumber = 3 }.ToArray(), + ValidatorIndex = 2, + Witness = new Witness() { InvocationScript = new byte[] { 1, 2, 3 } } + }); + + Assert.AreEqual(test.Timestamp, clone.Timestamp); + Assert.AreEqual(test.ValidatorIndex, clone.ValidatorIndex); + Assert.AreEqual(test.OriginalViewNumber, clone.OriginalViewNumber); + CollectionAssert.AreEqual(test.InvocationScript, clone.InvocationScript); + } + } +} diff --git a/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs b/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs index ca12f676a0..10984867b8 100644 --- a/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs +++ b/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs @@ -6,7 +6,6 @@ using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract.Native; -using Neo.VM.Types; using Neo.Wallets; using System; using System.Linq; diff --git a/tests/neo.UnitTests/Consensus/UT_RecoveryRequest.cs b/tests/neo.UnitTests/Consensus/UT_RecoveryRequest.cs new file mode 100644 index 0000000000..de89ba2fb2 --- /dev/null +++ b/tests/neo.UnitTests/Consensus/UT_RecoveryRequest.cs @@ -0,0 +1,29 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Consensus; +using Neo.IO; + +namespace Neo.UnitTests.Consensus +{ + [TestClass] + public class UT_RecoveryRequest + { + [TestMethod] + public void Size_Get() + { + var test = new RecoveryRequest() { Timestamp = 1, ViewNumber = 1 }; + test.Size.Should().Be(10); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new RecoveryRequest() { ViewNumber = 1, Timestamp = 123 }; + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Timestamp, clone.Timestamp); + Assert.AreEqual(test.Type, clone.Type); + Assert.AreEqual(test.ViewNumber, clone.ViewNumber); + } + } +} diff --git a/tests/neo.UnitTests/Cryptography/ECC/UT_ECDSA.cs b/tests/neo.UnitTests/Cryptography/ECC/UT_ECDSA.cs new file mode 100644 index 0000000000..a29cd3cbe2 --- /dev/null +++ b/tests/neo.UnitTests/Cryptography/ECC/UT_ECDSA.cs @@ -0,0 +1,29 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Cryptography.ECC; +using System; +using ECCurve = Neo.Cryptography.ECC.ECCurve; + +namespace Neo.UnitTests.Cryptography.ECC +{ + [TestClass] + public class UT_ECDSA + { + [TestMethod] + public void GenerateSignature() + { + var ecdsa = new ECDsa(ECCurve.Secp256k1.Infinity); + Assert.ThrowsException(() => ecdsa.GenerateSignature(new byte[0])); + + var pk = new byte[32]; + for (int x = 0; x < pk.Length; x++) pk[x] = (byte)x; + + ecdsa = new ECDsa(pk, ECCurve.Secp256k1); + var sig = ecdsa.GenerateSignature(new byte[] { 1 }); + + Assert.IsTrue(ecdsa.VerifySignature(new byte[] { 1 }, sig[0], sig[1])); + Assert.IsFalse(ecdsa.VerifySignature(new byte[] { 2 }, sig[0], sig[1])); + Assert.IsFalse(ecdsa.VerifySignature(new byte[] { 1 }, sig[0] + 1, sig[1])); + Assert.IsFalse(ecdsa.VerifySignature(new byte[] { 1 }, sig[0], sig[1] + 1)); + } + } +} diff --git a/tests/neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs b/tests/neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs index 725fc46962..a52753c2cf 100644 --- a/tests/neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs +++ b/tests/neo.UnitTests/Cryptography/ECC/UT_ECFieldElement.cs @@ -21,6 +21,9 @@ public void TestECFieldElementConstructor() input = ECCurve.Secp256k1.Q; action = () => new ECFieldElement(input, ECCurve.Secp256k1); action.Should().Throw(); + + action = () => new ECFieldElement(input, null); + action.Should().Throw(); } [TestMethod] diff --git a/tests/neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs b/tests/neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs index 9a8232d9fb..8f0b5f4c84 100644 --- a/tests/neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs +++ b/tests/neo.UnitTests/Cryptography/ECC/UT_ECPoint.cs @@ -14,7 +14,7 @@ namespace Neo.UnitTests.Cryptography.ECC [TestClass] public class UT_ECPoint { - public static byte[] generatePrivateKey(int privateKeyLength) + public static byte[] GeneratePrivateKey(int privateKeyLength) { byte[] privateKey = new byte[privateKeyLength]; for (int i = 0; i < privateKeyLength; i++) @@ -184,17 +184,17 @@ public void TestFromBytes() ECPoint.FromBytes(input3, ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G); ECPoint.FromBytes(input2.Skip(1).ToArray(), ECCurve.Secp256k1).Should().Be(ECCurve.Secp256k1.G); - byte[] input4 = generatePrivateKey(72); + byte[] input4 = GeneratePrivateKey(72); ECPoint.FromBytes(input4, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("3634473727541135791764834762056624681715094789735830699031648" + "273128038409767"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("18165245710263168158644330920009617039772504630129940696140050972160274286151"), ECCurve.Secp256k1), ECCurve.Secp256k1)); - byte[] input5 = generatePrivateKey(96); + byte[] input5 = GeneratePrivateKey(96); ECPoint.FromBytes(input5, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("1780731860627700044960722568376592200742329637303199754547598" + "369979440671"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("14532552714582660066924456880521368950258152170031413196862950297402215317055"), ECCurve.Secp256k1), ECCurve.Secp256k1)); - byte[] input6 = generatePrivateKey(104); + byte[] input6 = GeneratePrivateKey(104); ECPoint.FromBytes(input6, ECCurve.Secp256k1).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("3634473727541135791764834762056624681715094789735830699031648" + "273128038409767"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("18165245710263168158644330920009617039772504630129940696140050972160274286151"), ECCurve.Secp256k1), ECCurve.Secp256k1)); @@ -231,17 +231,17 @@ public void TestMultiply() ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("16721517996619732311261078486295444964227498319433363271180755596201863690708"), ECCurve.Secp256k1), ECCurve.Secp256k1)); - k = new BigInteger(generatePrivateKey(100)); + k = new BigInteger(GeneratePrivateKey(100)); ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("19222995016448259376216431079553428738726180595337971417371897285865264889977"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("6637081904924493791520919212064582313497884724460823966446023080706723904419"), ECCurve.Secp256k1), ECCurve.Secp256k1)); - k = new BigInteger(generatePrivateKey(120)); + k = new BigInteger(GeneratePrivateKey(120)); ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("79652345192111851576650978679091010173409410384772942769927955775006682639778"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("6460429961979335115790346961011058418773289452368186110818621539624566803831"), ECCurve.Secp256k1), ECCurve.Secp256k1)); - k = new BigInteger(generatePrivateKey(300)); + k = new BigInteger(GeneratePrivateKey(300)); ECPoint.Multiply(p, k).Should().Be(new ECPoint(new ECFieldElement(BigInteger.Parse("105331914562708556186724786757483927866790351460145374033180496740107603569412"), ECCurve.Secp256k1), new ECFieldElement(BigInteger.Parse("60523670886755698512704385951571322569877668383890769288780681319304421873758"), ECCurve.Secp256k1), ECCurve.Secp256k1)); diff --git a/tests/neo.UnitTests/Cryptography/MPT/UT_MPTTrie.cs b/tests/neo.UnitTests/Cryptography/MPT/UT_MPTTrie.cs index 014a10e6d2..556d338ca8 100644 --- a/tests/neo.UnitTests/Cryptography/MPT/UT_MPTTrie.cs +++ b/tests/neo.UnitTests/Cryptography/MPT/UT_MPTTrie.cs @@ -234,6 +234,9 @@ public void TestGetProof() Assert.IsTrue(proof.Contains(r.Encode())); Assert.IsTrue(proof.Contains(l1.Encode())); Assert.IsTrue(proof.Contains(v1.Encode())); + + proof = mpt.GetProof(Array.Empty()); + Assert.IsNull(proof); } [TestMethod] diff --git a/tests/neo.UnitTests/IO/Caching/UT_HashSetCache.cs b/tests/neo.UnitTests/IO/Caching/UT_HashSetCache.cs index 5f227c7e35..440df23462 100644 --- a/tests/neo.UnitTests/IO/Caching/UT_HashSetCache.cs +++ b/tests/neo.UnitTests/IO/Caching/UT_HashSetCache.cs @@ -16,7 +16,8 @@ public void TestHashSetCache() var bucket = new HashSetCache(10); for (int i = 1; i <= 100; i++) { - bucket.Add(i); + Assert.IsTrue(bucket.Add(i)); + Assert.IsFalse(bucket.Add(i)); } bucket.Count.Should().Be(100); @@ -131,6 +132,8 @@ public void TestExceptWith() }; set.ExceptWith(new UInt256[] { b, c }); CollectionAssert.AreEqual(set.ToArray(), new UInt256[] { a }); + set.ExceptWith(new UInt256[] { a }); + CollectionAssert.AreEqual(set.ToArray(), new UInt256[] { }); set = new HashSetCache(10) { diff --git a/tests/neo.UnitTests/IO/UT_ByteArrayEqualityComparer.cs b/tests/neo.UnitTests/IO/UT_ByteArrayEqualityComparer.cs new file mode 100644 index 0000000000..6b7152c239 --- /dev/null +++ b/tests/neo.UnitTests/IO/UT_ByteArrayEqualityComparer.cs @@ -0,0 +1,45 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using System; +using System.Linq; + +namespace Neo.UnitTests +{ + [TestClass] + public class UT_ByteArrayEqualityComparer + { + [TestMethod] + public void TestEqual() + { + var a = new byte[] { 1, 2, 3, 4, 1, 2, 3, 4, 5 }; + var b = new byte[] { 1, 2, 3, 4, 1, 2, 3, 4, 5 }; + var check = ByteArrayEqualityComparer.Default; + + Assert.IsTrue(check.Equals(a, a)); + Assert.IsTrue(check.Equals(a, b)); + Assert.IsFalse(check.Equals(null, b)); + Assert.IsFalse(check.Equals(a, null)); + Assert.IsTrue(check.Equals(null, null)); + + Assert.IsFalse(check.Equals(a, new byte[] { 1, 2, 3 })); + Assert.IsTrue(check.Equals(Array.Empty(), Array.Empty())); + + b[8]++; + Assert.IsFalse(check.Equals(a, b)); + b[8]--; + b[0]--; + Assert.IsFalse(check.Equals(a, b)); + } + + [TestMethod] + public void TestGetHashCode() + { + var a = new byte[] { 1, 2, 3, 4, 1, 2, 3, 4, 5 }; + var b = new byte[] { 1, 2, 3, 4, 1, 2, 3, 4, 5 }; + var check = ByteArrayEqualityComparer.Default; + + Assert.AreEqual(check.GetHashCode(a), check.GetHashCode(b)); + Assert.AreNotEqual(check.GetHashCode(a), check.GetHashCode(b.Take(8).ToArray())); + } + } +} diff --git a/tests/neo.UnitTests/IO/UT_ReferenceEqualityComparer.cs b/tests/neo.UnitTests/IO/UT_ReferenceEqualityComparer.cs new file mode 100644 index 0000000000..1db8dcabb9 --- /dev/null +++ b/tests/neo.UnitTests/IO/UT_ReferenceEqualityComparer.cs @@ -0,0 +1,37 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Neo.UnitTests +{ + [TestClass] + public class UT_ReferenceEqualityComparer + { + private class FakeEquals : IEquatable + { + public bool Equals([AllowNull] FakeEquals other) + { + return true; + } + + public override int GetHashCode() + { + return 123; + } + } + + [TestMethod] + public void TestEqual() + { + var a = new FakeEquals(); + var b = new FakeEquals(); + var check = ReferenceEqualityComparer.Default; + + Assert.IsFalse(check.Equals(a, b)); + Assert.AreNotEqual(check.GetHashCode(a), check.GetHashCode(b)); + Assert.AreNotEqual(123, check.GetHashCode(a)); + Assert.AreNotEqual(123, check.GetHashCode(b)); + } + } +} diff --git a/tests/neo.UnitTests/IO/UT_SerializableWrapper.cs b/tests/neo.UnitTests/IO/UT_SerializableWrapper.cs index 5a1ec884ed..0f73c40c38 100644 --- a/tests/neo.UnitTests/IO/UT_SerializableWrapper.cs +++ b/tests/neo.UnitTests/IO/UT_SerializableWrapper.cs @@ -14,6 +14,16 @@ public void TestGetSize() Assert.AreEqual(4, temp.Size); } + [TestMethod] + public void TestCast() + { + SerializableWrapper tempA = (SerializableWrapper)123; + SerializableWrapper tempB = tempA.ToArray().AsSerializable>(); + + Assert.IsTrue(tempA.Equals(tempB)); + Assert.AreEqual((uint)123, (uint)tempA); + } + [TestMethod] public void TestEqualsOtherObject() { diff --git a/tests/neo.UnitTests/Ledger/UT_ContractIdState.cs b/tests/neo.UnitTests/Ledger/UT_ContractIdState.cs new file mode 100644 index 0000000000..d6300eb13b --- /dev/null +++ b/tests/neo.UnitTests/Ledger/UT_ContractIdState.cs @@ -0,0 +1,48 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Ledger; +using System; + +namespace Neo.UnitTests.Ledger +{ + [TestClass] + public class UT_ContractIdState + { + [TestMethod] + public void Size_Get() + { + var test = new ContractIdState() { NextId = 1 }; + ((ISerializable)test).Size.Should().Be(4); + + test = new ContractIdState() { NextId = int.MaxValue }; + ((ISerializable)test).Size.Should().Be(4); + } + + [TestMethod] + public void Clone() + { + var test = new ContractIdState() { NextId = 1 }; + var clone = ((ICloneable)test).Clone(); + + Assert.AreEqual(test.NextId, clone.NextId); + + clone = new ContractIdState() { NextId = 2 }; + ((ICloneable)clone).FromReplica(test); + + Assert.AreEqual(test.NextId, clone.NextId); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new ContractIdState() { NextId = int.MaxValue }; + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.NextId, clone.NextId); + + test = new ContractIdState() { NextId = -1 }; + Assert.ThrowsException(() => test.ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Ledger/UT_PoolItem.cs b/tests/neo.UnitTests/Ledger/UT_PoolItem.cs index 4c4c406c62..6933bfb292 100644 --- a/tests/neo.UnitTests/Ledger/UT_PoolItem.cs +++ b/tests/neo.UnitTests/Ledger/UT_PoolItem.cs @@ -58,13 +58,27 @@ public void PoolItem_CompareTo_Hash() int sizeFixed = 51; int netFeeSatoshiFixed = 1; + var tx1 = GenerateTxWithFirstByteOfHashGreaterThanOrEqualTo(0x80, netFeeSatoshiFixed, sizeFixed); + var tx2 = GenerateTxWithFirstByteOfHashLessThanOrEqualTo(0x79, netFeeSatoshiFixed, sizeFixed); + + tx1.Attributes = new TransactionAttribute[] { new HighPriorityAttribute() }; + + PoolItem pitem1 = new PoolItem(tx1); + PoolItem pitem2 = new PoolItem(tx2); + + // Different priority + pitem2.CompareTo(pitem1).Should().Be(-1); + + // Bulk test for (int testRuns = 0; testRuns < 30; testRuns++) { - var tx1 = GenerateTxWithFirstByteOfHashGreaterThanOrEqualTo(0x80, netFeeSatoshiFixed, sizeFixed); - var tx2 = GenerateTxWithFirstByteOfHashLessThanOrEqualTo(0x79, netFeeSatoshiFixed, sizeFixed); + tx1 = GenerateTxWithFirstByteOfHashGreaterThanOrEqualTo(0x80, netFeeSatoshiFixed, sizeFixed); + tx2 = GenerateTxWithFirstByteOfHashLessThanOrEqualTo(0x79, netFeeSatoshiFixed, sizeFixed); + + pitem1 = new PoolItem(tx1); + pitem2 = new PoolItem(tx2); - PoolItem pitem1 = new PoolItem(tx1); - PoolItem pitem2 = new PoolItem(tx2); + pitem2.CompareTo((Transaction)null).Should().Be(1); // pitem2.tx.Hash < pitem1.tx.Hash => 1 descending order pitem2.CompareTo(pitem1).Should().Be(1); @@ -87,6 +101,7 @@ public void PoolItem_CompareTo_Equals() // pitem1 == pitem2 (fee) => 0 pitem1.CompareTo(pitem2).Should().Be(0); pitem2.CompareTo(pitem1).Should().Be(0); + pitem2.CompareTo((PoolItem)null).Should().Be(1); } public Transaction GenerateTxWithFirstByteOfHashGreaterThanOrEqualTo(byte firstHashByte, long networkFee, int size) diff --git a/tests/neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs b/tests/neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs new file mode 100644 index 0000000000..0c18c1fb44 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Capabilities/UT_FullNodeCapability.cs @@ -0,0 +1,34 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Capabilities; +using System.IO; + +namespace Neo.UnitTests.Network.P2P.Capabilities +{ + [TestClass] + public class UT_FullNodeCapability + { + [TestMethod] + public void Size_Get() + { + var test = new FullNodeCapability() { StartHeight = 1 }; + test.Size.Should().Be(5); + + test = new FullNodeCapability(2); + test.Size.Should().Be(5); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new FullNodeCapability() { StartHeight = uint.MaxValue }; + var buffer = test.ToArray(); + + using var br = new BinaryReader(new MemoryStream(buffer)); + var clone = (FullNodeCapability)NodeCapability.DeserializeFrom(br); + + Assert.AreEqual(test.StartHeight, clone.StartHeight); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs b/tests/neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs new file mode 100644 index 0000000000..f0769d31be --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Capabilities/UT_ServerCapability.cs @@ -0,0 +1,55 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Capabilities; +using System; +using System.IO; + +namespace Neo.UnitTests.Network.P2P.Capabilities +{ + [TestClass] + public class UT_ServerCapability + { + [TestMethod] + public void Size_Get() + { + var test = new ServerCapability(NodeCapabilityType.TcpServer) { Port = 1 }; + test.Size.Should().Be(3); + + test = new ServerCapability(NodeCapabilityType.WsServer) { Port = 2 }; + test.Size.Should().Be(3); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new ServerCapability(NodeCapabilityType.WsServer) { Port = 2 }; + var buffer = test.ToArray(); + + using var br = new BinaryReader(new MemoryStream(buffer)); + var clone = (ServerCapability)ServerCapability.DeserializeFrom(br); + + Assert.AreEqual(test.Port, clone.Port); + Assert.AreEqual(test.Type, clone.Type); + + clone = new ServerCapability(NodeCapabilityType.WsServer, 123); + br.BaseStream.Seek(0, SeekOrigin.Begin); + ((ISerializable)clone).Deserialize(br); + + Assert.AreEqual(test.Port, clone.Port); + Assert.AreEqual(test.Type, clone.Type); + + clone = new ServerCapability(NodeCapabilityType.TcpServer, 123); + + br.BaseStream.Seek(0, SeekOrigin.Begin); + Assert.ThrowsException(() => ((ISerializable)clone).Deserialize(br)); + Assert.ThrowsException(() => new ServerCapability(NodeCapabilityType.FullNode)); + + // Wrog type + br.BaseStream.Seek(0, SeekOrigin.Begin); + br.BaseStream.WriteByte(0xFF); + br.BaseStream.Seek(0, SeekOrigin.Begin); + Assert.ThrowsException(() => ServerCapability.DeserializeFrom(br)); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs new file mode 100644 index 0000000000..fa19860ff2 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs @@ -0,0 +1,40 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; +using System; +using System.Linq; +using System.Net; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_AddrPayload + { + [TestMethod] + public void Size_Get() + { + var test = new AddrPayload() { AddressList = new NetworkAddressWithTime[0] }; + test.Size.Should().Be(1); + + test = AddrPayload.Create(new NetworkAddressWithTime[] { new NetworkAddressWithTime() { Address = IPAddress.Any, Capabilities = new Neo.Network.P2P.Capabilities.NodeCapability[0], Timestamp = 1 } }); + test.Size.Should().Be(22); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = AddrPayload.Create(new NetworkAddressWithTime[] { new NetworkAddressWithTime() + { + Address = IPAddress.Any, + Capabilities = new Neo.Network.P2P.Capabilities.NodeCapability[0], Timestamp = 1 + } + }); + var clone = test.ToArray().AsSerializable(); + + CollectionAssert.AreEqual(test.AddressList.Select(u => u.EndPoint).ToArray(), clone.AddressList.Select(u => u.EndPoint).ToArray()); + + Assert.ThrowsException(() => new AddrPayload() { AddressList = new NetworkAddressWithTime[0] }.ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs new file mode 100644 index 0000000000..6a0afc6cdf --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterAddPayload.cs @@ -0,0 +1,30 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_FilterAddPayload + { + [TestMethod] + public void Size_Get() + { + var test = new FilterAddPayload() { Data = new byte[0] }; + test.Size.Should().Be(1); + + test = new FilterAddPayload() { Data = new byte[] { 1, 2, 3 } }; + test.Size.Should().Be(4); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new FilterAddPayload() { Data = new byte[] { 1, 2, 3 } }; + var clone = test.ToArray().AsSerializable(); + + CollectionAssert.AreEqual(test.Data, clone.Data); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs new file mode 100644 index 0000000000..1b1832d8d9 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_FilterLoadPayload.cs @@ -0,0 +1,35 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; +using System; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_FilterLoadPayload + { + [TestMethod] + public void Size_Get() + { + var test = new FilterLoadPayload() { Filter = new byte[0], K = 1, Tweak = uint.MaxValue }; + test.Size.Should().Be(6); + + test = FilterLoadPayload.Create(new Neo.Cryptography.BloomFilter(8, 10, 123456)); + test.Size.Should().Be(7); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = FilterLoadPayload.Create(new Neo.Cryptography.BloomFilter(8, 10, 123456)); + var clone = test.ToArray().AsSerializable(); + + CollectionAssert.AreEqual(test.Filter, clone.Filter); + Assert.AreEqual(test.K, clone.K); + Assert.AreEqual(test.Tweak, clone.Tweak); + + Assert.ThrowsException(() => new FilterLoadPayload() { Filter = new byte[0], K = 51, Tweak = uint.MaxValue }.ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs new file mode 100644 index 0000000000..76ed1df9f9 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlockByIndexPayload.cs @@ -0,0 +1,41 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; +using System; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_GetBlockByIndexPayload + { + [TestMethod] + public void Size_Get() + { + var test = new GetBlockByIndexPayload() { Count = 5, IndexStart = 5 }; + test.Size.Should().Be(6); + + test = GetBlockByIndexPayload.Create(1, short.MaxValue); + test.Size.Should().Be(6); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new GetBlockByIndexPayload() { Count = -1, IndexStart = int.MaxValue }; + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Count, clone.Count); + Assert.AreEqual(test.IndexStart, clone.IndexStart); + + test = new GetBlockByIndexPayload() { Count = -2, IndexStart = int.MaxValue }; + Assert.ThrowsException(() => test.ToArray().AsSerializable()); + + test = new GetBlockByIndexPayload() { Count = 0, IndexStart = int.MaxValue }; + Assert.ThrowsException(() => test.ToArray().AsSerializable()); + + test = new GetBlockByIndexPayload() { Count = HeadersPayload.MaxHeadersCount + 1, IndexStart = int.MaxValue }; + Assert.ThrowsException(() => test.ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs new file mode 100644 index 0000000000..4c09147d8d --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_GetBlocksPayload.cs @@ -0,0 +1,37 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; +using System; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_GetBlocksPayload + { + [TestMethod] + public void Size_Get() + { + var test = new GetBlocksPayload() { Count = 5, HashStart = UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff01") }; + test.Size.Should().Be(34); + + test = new GetBlocksPayload() { Count = 1, HashStart = UInt256.Zero }; + test.Size.Should().Be(34); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = GetBlocksPayload.Create(UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff01"), 5); + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Count, clone.Count); + Assert.AreEqual(test.HashStart, clone.HashStart); + Assert.AreEqual(5, clone.Count); + Assert.AreEqual("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff01", clone.HashStart.ToString()); + + Assert.ThrowsException(() => GetBlocksPayload.Create(UInt256.Zero, -2).ToArray().AsSerializable()); + Assert.ThrowsException(() => GetBlocksPayload.Create(UInt256.Zero, 0).ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Header.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Header.cs index 4db51e9bef..afec8fd41c 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Header.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Header.cs @@ -27,6 +27,31 @@ public void Size_Get() uut.Size.Should().Be(105); } + [TestMethod] + public void GetHashCodeTest() + { + UInt256 val256 = UInt256.Zero; + TestUtils.SetupHeaderWithValues(uut, val256, out _, out _, out _, out _, out _); + uut.GetHashCode().Should().Be(uut.Hash.GetHashCode()); + } + + [TestMethod] + public void TrimTest() + { + UInt256 val256 = UInt256.Zero; + TestUtils.SetupHeaderWithValues(uut, val256, out _, out _, out _, out _, out _); + var trim = uut.Trim(); + + trim.Version.Should().Be(uut.Version); + trim.PrevHash.Should().Be(uut.PrevHash); + trim.MerkleRoot.Should().Be(uut.MerkleRoot); + trim.Timestamp.Should().Be(uut.Timestamp); + trim.Index.Should().Be(uut.Index); + trim.NextConsensus.Should().Be(uut.NextConsensus); + trim.Witness.Should().Be(uut.Witness); + trim.Hashes.Length.Should().Be(0); + } + [TestMethod] public void Deserialize() { diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs.cs new file mode 100644 index 0000000000..eeb76705a9 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_HeadersPayload.cs.cs @@ -0,0 +1,35 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_HeadersPayload + { + [TestMethod] + public void Size_Get() + { + var header = new Header(); + TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRoot, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal); + + var test = HeadersPayload.Create(); + test.Size.Should().Be(1); + test = HeadersPayload.Create(header); + test.Size.Should().Be(1 + header.Size); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var header = new Header(); + TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRoot, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal); + var test = HeadersPayload.Create(header); + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Headers.Length, clone.Headers.Length); + Assert.AreEqual(test.Headers[0], clone.Headers[0]); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs new file mode 100644 index 0000000000..645e599cce --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_HighPriorityAttribute.cs @@ -0,0 +1,80 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Ledger; +using Neo.Network.P2P.Payloads; +using Neo.SmartContract.Native; +using System; +using System.IO; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_HighPriorityAttribute + { + [TestInitialize] + public void Init() + { + TestBlockchain.InitializeMockNeoSystem(); + } + + [TestMethod] + public void Size_Get() + { + var test = new HighPriorityAttribute(); + test.Size.Should().Be(1); + } + + [TestMethod] + public void ToJson() + { + var test = new HighPriorityAttribute(); + var json = test.ToJson().ToString(); + Assert.AreEqual(@"{""type"":""HighPriority""}", json); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = new HighPriorityAttribute(); + + var clone = test.ToArray().AsSerializable(); + Assert.AreEqual(clone.Type, test.Type); + + // As transactionAttribute + + using var msRead = new MemoryStream(); + using var msWrite = new MemoryStream(); + using (var stream = new BinaryWriter(msWrite)) + { + var data = (test as TransactionAttribute).ToArray(); + msRead.Write(data); + msRead.Seek(0, SeekOrigin.Begin); + } + + using var reader = new BinaryReader(msRead); + clone = TransactionAttribute.DeserializeFrom(reader) as HighPriorityAttribute; + Assert.AreEqual(clone.Type, test.Type); + + // Wrong type + + msRead.Seek(0, SeekOrigin.Begin); + msRead.WriteByte(0xff); + msRead.Seek(0, SeekOrigin.Begin); + Assert.ThrowsException(() => TransactionAttribute.DeserializeFrom(reader)); + msRead.Seek(0, SeekOrigin.Begin); + Assert.ThrowsException(() => new HighPriorityAttribute().Deserialize(reader)); + } + + [TestMethod] + public void Verify() + { + var test = new HighPriorityAttribute(); + var snapshot = Blockchain.Singleton.GetSnapshot(); + + Assert.IsFalse(test.Verify(snapshot, new Transaction() { Signers = new Signer[] { } })); + Assert.IsFalse(test.Verify(snapshot, new Transaction() { Signers = new Signer[] { new Signer() { Account = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01") } } })); + Assert.IsTrue(test.Verify(snapshot, new Transaction() { Signers = new Signer[] { new Signer() { Account = NativeContract.NEO.GetCommitteeAddress(snapshot) } } })); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs new file mode 100644 index 0000000000..9bd5127af9 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_InvPayload.cs @@ -0,0 +1,56 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Payloads; +using System; +using System.Linq; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_InvPayload + { + [TestMethod] + public void Size_Get() + { + var test = InvPayload.Create(InventoryType.TX, UInt256.Zero); + test.Size.Should().Be(34); + + test = InvPayload.Create(InventoryType.TX, UInt256.Zero, UInt256.Parse("01ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00a4")); + test.Size.Should().Be(66); + } + + [TestMethod] + public void CreateGroup() + { + var hashes = new UInt256[InvPayload.MaxHashesCount + 1]; + + for (int x = 0; x < hashes.Length; x++) + { + byte[] data = new byte[32]; + Array.Copy(BitConverter.GetBytes(x), data, 4); + hashes[x] = new UInt256(data); + } + + var array = InvPayload.CreateGroup(InventoryType.TX, hashes).ToArray(); + + Assert.AreEqual(2, array.Length); + Assert.AreEqual(InventoryType.TX, array[0].Type); + Assert.AreEqual(InventoryType.TX, array[1].Type); + CollectionAssert.AreEqual(hashes.Take(InvPayload.MaxHashesCount).ToArray(), array[0].Hashes); + CollectionAssert.AreEqual(hashes.Skip(InvPayload.MaxHashesCount).ToArray(), array[1].Hashes); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = InvPayload.Create(InventoryType.TX, UInt256.Zero, UInt256.Parse("01ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00a4")); + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.Type, clone.Type); + CollectionAssert.AreEqual(test.Hashes, clone.Hashes); + + Assert.ThrowsException(() => InvPayload.Create((InventoryType)0xff, UInt256.Zero).ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs new file mode 100644 index 0000000000..eb8cae51ed --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_MerkleBlockPayload.cs @@ -0,0 +1,41 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Ledger; +using Neo.Network.P2P.Payloads; +using System.Collections; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_MerkleBlockPayload + { + [TestInitialize] + public void TestSetup() + { + TestBlockchain.InitializeMockNeoSystem(); + } + + [TestMethod] + public void Size_Get() + { + var test = MerkleBlockPayload.Create(Blockchain.GenesisBlock, new BitArray(1024, false)); + test.Size.Should().Be(302); + + test = MerkleBlockPayload.Create(Blockchain.GenesisBlock, new BitArray(0, false)); + test.Size.Should().Be(174); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = MerkleBlockPayload.Create(Blockchain.GenesisBlock, new BitArray(2, false)); + var clone = test.ToArray().AsSerializable(); + + Assert.AreEqual(test.ContentCount, clone.ContentCount); + Assert.AreEqual(test.Hashes.Length, clone.ContentCount); + CollectionAssert.AreEqual(test.Hashes, clone.Hashes); + CollectionAssert.AreEqual(test.Flags, clone.Flags); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs new file mode 100644 index 0000000000..239896acf8 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_NetworkAddressWithTime.cs @@ -0,0 +1,46 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Capabilities; +using Neo.Network.P2P.Payloads; +using System; +using System.Net; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_NetworkAddressWithTime + { + [TestMethod] + public void SizeAndEndPoint_Get() + { + var test = new NetworkAddressWithTime() { Capabilities = new NodeCapability[0], Address = IPAddress.Any, Timestamp = 1 }; + test.Size.Should().Be(21); + + Assert.AreEqual(test.EndPoint.Port, 0); + + test = NetworkAddressWithTime.Create(IPAddress.Any, 1, new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) }); + test.Size.Should().Be(24); + + Assert.AreEqual(test.EndPoint.Port, 22); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = NetworkAddressWithTime.Create(IPAddress.Any, 1, new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) }); + var clone = test.ToArray().AsSerializable(); + + CollectionAssert.AreEqual(test.Capabilities.ToByteArray(), clone.Capabilities.ToByteArray()); + Assert.AreEqual(test.EndPoint.ToString(), clone.EndPoint.ToString()); + Assert.AreEqual(test.Timestamp, clone.Timestamp); + Assert.AreEqual(test.Address, clone.Address); + + Assert.ThrowsException(() => NetworkAddressWithTime.Create(IPAddress.Any, 1, + new NodeCapability[] { + new ServerCapability(NodeCapabilityType.TcpServer, 22) , + new ServerCapability(NodeCapabilityType.TcpServer, 22) + }).ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs index 4238e68122..9f80f21e22 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs @@ -34,6 +34,25 @@ public void Script_Get() uut.Script.Should().BeNull(); } + [TestMethod] + public void FromStackItem() + { + Assert.ThrowsException(() => ((IInteroperable)uut).FromStackItem(VM.Types.StackItem.Null)); + } + + [TestMethod] + public void TestEquals() + { + Assert.IsTrue(uut.Equals(uut)); + Assert.IsFalse(uut.Equals(null)); + } + + [TestMethod] + public void InventoryType_Get() + { + ((IInventory)uut).InventoryType.Should().Be(InventoryType.TX); + } + [TestMethod] public void Script_Set() { diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs new file mode 100644 index 0000000000..ebe39427d1 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_VersionPayload.cs @@ -0,0 +1,42 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; +using Neo.Network.P2P.Capabilities; +using Neo.Network.P2P.Payloads; +using System; + +namespace Neo.UnitTests.Network.P2P.Payloads +{ + [TestClass] + public class UT_VersionPayload + { + [TestMethod] + public void SizeAndEndPoint_Get() + { + var test = new VersionPayload() { Capabilities = new NodeCapability[0], UserAgent = "neo3" }; + test.Size.Should().Be(22); + + test = VersionPayload.Create(123, "neo3", new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) }); + test.Size.Should().Be(25); + } + + [TestMethod] + public void DeserializeAndSerialize() + { + var test = VersionPayload.Create(123, "neo3", new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) }); + var clone = test.ToArray().AsSerializable(); + + CollectionAssert.AreEqual(test.Capabilities.ToByteArray(), clone.Capabilities.ToByteArray()); + Assert.AreEqual(test.UserAgent, clone.UserAgent); + Assert.AreEqual(test.Nonce, clone.Nonce); + Assert.AreEqual(test.Timestamp, clone.Timestamp); + CollectionAssert.AreEqual(test.Capabilities.ToByteArray(), clone.Capabilities.ToByteArray()); + + Assert.ThrowsException(() => VersionPayload.Create(123, "neo3", + new NodeCapability[] { + new ServerCapability(NodeCapabilityType.TcpServer, 22) , + new ServerCapability(NodeCapabilityType.TcpServer, 22) + }).ToArray().AsSerializable()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/UT_ChannelsConfig.cs b/tests/neo.UnitTests/Network/P2P/UT_ChannelsConfig.cs new file mode 100644 index 0000000000..5613364319 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/UT_ChannelsConfig.cs @@ -0,0 +1,35 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Network.P2P; +using System.Net; + +namespace Neo.UnitTests.Network.P2P +{ + [TestClass] + public class UT_ChannelsConfig + { + [TestMethod] + public void CreateTest() + { + var config = new ChannelsConfig(); + + config.Tcp.Should().BeNull(); + config.WebSocket.Should().BeNull(); + config.MinDesiredConnections.Should().Be(10); + config.MaxConnections.Should().Be(40); + config.MaxConnectionsPerAddress.Should().Be(3); + + config.Tcp = config.WebSocket = new IPEndPoint(IPAddress.Any, 21); + config.MaxConnectionsPerAddress++; + config.MaxConnections++; + config.MinDesiredConnections++; + + config.Tcp.Should().BeSameAs(config.WebSocket); + config.Tcp.Address.Should().BeEquivalentTo(IPAddress.Any); + config.Tcp.Port.Should().Be(21); + config.MinDesiredConnections.Should().Be(11); + config.MaxConnections.Should().Be(41); + config.MaxConnectionsPerAddress.Should().Be(4); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/UT_LocalNode.cs b/tests/neo.UnitTests/Network/P2P/UT_LocalNode.cs new file mode 100644 index 0000000000..81b610ab14 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/UT_LocalNode.cs @@ -0,0 +1,34 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Network.P2P; +using System; +using System.Linq; +using System.Net; + +namespace Neo.UnitTests.Network.P2P +{ + [TestClass] + public class UT_LocalNode + { + private static NeoSystem testBlockchain; + + [TestInitialize] + public void Init() + { + testBlockchain = TestBlockchain.TheNeoSystem; + } + + [TestMethod] + public void TestDefaults() + { + Assert.AreEqual(0, LocalNode.Singleton.ListenerTcpPort); + Assert.AreEqual(0, LocalNode.Singleton.ListenerWsPort); + Assert.AreEqual(3, LocalNode.Singleton.MaxConnectionsPerAddress); + Assert.AreEqual(10, LocalNode.Singleton.MinDesiredConnections); + Assert.AreEqual(40, LocalNode.Singleton.MaxConnections); + Assert.AreEqual(0, LocalNode.Singleton.UnconnectedCount); + + CollectionAssert.AreEqual(Array.Empty(), LocalNode.Singleton.GetRemoteNodes().ToArray()); + CollectionAssert.AreEqual(Array.Empty(), LocalNode.Singleton.GetUnconnectedPeers().ToArray()); + } + } +} diff --git a/tests/neo.UnitTests/Network/P2P/UT_Message.cs b/tests/neo.UnitTests/Network/P2P/UT_Message.cs index 6f194ea862..36c14831f0 100644 --- a/tests/neo.UnitTests/Network/P2P/UT_Message.cs +++ b/tests/neo.UnitTests/Network/P2P/UT_Message.cs @@ -5,6 +5,8 @@ using Neo.Network.P2P; using Neo.Network.P2P.Capabilities; using Neo.Network.P2P.Payloads; +using System; +using System.Linq; namespace Neo.UnitTests.Network.P2P { @@ -22,6 +24,7 @@ public void Serialize_Deserialize() copy.Command.Should().Be(msg.Command); copy.Flags.Should().Be(msg.Flags); + msg.Size.Should().Be(payload.Size + 3); payloadCopy.LastBlockIndex.Should().Be(payload.LastBlockIndex); payloadCopy.Nonce.Should().Be(payload.Nonce); @@ -74,6 +77,53 @@ public void Serialize_Deserialize_WithoutPayload_ByteString() buffer.Count.Should().Be(length); } + [TestMethod] + public void MultipleSizes() + { + var msg = Message.Create(MessageCommand.GetAddr); + var buffer = msg.ToArray(); + + var length = Message.TryDeserialize(ByteString.Empty, out var copy); + Assert.AreEqual(0, length); + Assert.IsNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer), out copy); + Assert.AreEqual(buffer.Length, length); + Assert.IsNotNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFD }).ToArray()), out copy); + Assert.AreEqual(0, length); + Assert.IsNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFD, buffer[2], 0x00 }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(buffer.Length + 2, length); + Assert.IsNotNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFD, 0x01, 0x00 }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(0, length); + Assert.IsNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFE }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(0, length); + Assert.IsNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFE, buffer[2], 0x00, 0x00, 0x00 }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(buffer.Length + 4, length); + Assert.IsNotNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFF }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(0, length); + Assert.IsNull(copy); + + length = Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFF, buffer[2], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).Concat(buffer.Skip(3)).ToArray()), out copy); + Assert.AreEqual(buffer.Length + 8, length); + Assert.IsNotNull(copy); + + // Big message + + Assert.ThrowsException(() => Message.TryDeserialize(ByteString.CopyFrom(buffer.Take(2).Concat(new byte[] { 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }).Concat(buffer.Skip(3)).ToArray()), out copy)); + } + [TestMethod] public void Compression() { diff --git a/tests/neo.UnitTests/Network/P2P/UT_TaskSession.cs b/tests/neo.UnitTests/Network/P2P/UT_TaskSession.cs new file mode 100644 index 0000000000..6ae403a946 --- /dev/null +++ b/tests/neo.UnitTests/Network/P2P/UT_TaskSession.cs @@ -0,0 +1,37 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Network.P2P; +using Neo.Network.P2P.Capabilities; +using Neo.Network.P2P.Payloads; +using System; +using Xunit.Sdk; + +namespace Neo.UnitTests.Network.P2P +{ + [TestClass] + public class UT_TaskSession + { + [TestMethod] + public void CreateTest() + { + Assert.ThrowsException(() => new TaskSession(null)); + + var ses = new TaskSession(new VersionPayload() { Capabilities = new NodeCapability[] { new FullNodeCapability(123) } }); + + Assert.IsTrue(ses.IsFullNode); + Assert.AreEqual((uint)123, ses.LastBlockIndex); + Assert.AreEqual(0, ses.IndexTasks.Count); + Assert.AreEqual(0, ses.InvTasks.Count); + Assert.AreEqual((uint)0, ses.TimeoutTimes); + Assert.AreEqual((uint)0, ses.InvalidBlockCount); + + ses = new TaskSession(new VersionPayload() { Capabilities = new NodeCapability[0] }); + + Assert.IsFalse(ses.IsFullNode); + Assert.AreEqual((uint)0, ses.LastBlockIndex); + Assert.AreEqual(0, ses.IndexTasks.Count); + Assert.AreEqual(0, ses.InvTasks.Count); + Assert.AreEqual((uint)0, ses.TimeoutTimes); + Assert.AreEqual((uint)0, ses.InvalidBlockCount); + } + } +} diff --git a/tests/neo.UnitTests/Network/UT_UPnP.cs b/tests/neo.UnitTests/Network/UT_UPnP.cs new file mode 100644 index 0000000000..897d48ffa2 --- /dev/null +++ b/tests/neo.UnitTests/Network/UT_UPnP.cs @@ -0,0 +1,24 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Network; +using System; + +namespace Neo.UnitTests.Network +{ + [TestClass] + public class UT_UPnP + { + [TestMethod] + public void GetTimeOut() + { + Assert.AreEqual(3, UPnP.TimeOut.TotalSeconds); + } + + [TestMethod] + public void NoService() + { + Assert.ThrowsException(() => UPnP.ForwardPort(1, System.Net.Sockets.ProtocolType.Tcp, "")); + Assert.ThrowsException(() => UPnP.DeleteForwardingRule(1, System.Net.Sockets.ProtocolType.Tcp)); + Assert.ThrowsException(() => UPnP.GetExternalIP()); + } + } +} diff --git a/tests/neo.UnitTests/Persistence/UT_MemoryStore.cs b/tests/neo.UnitTests/Persistence/UT_MemoryStore.cs new file mode 100644 index 0000000000..101ed0bdfc --- /dev/null +++ b/tests/neo.UnitTests/Persistence/UT_MemoryStore.cs @@ -0,0 +1,29 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Caching; +using Neo.Persistence; +using System.Linq; + +namespace Neo.UnitTests.Persistence +{ + [TestClass] + public class UT_MemoryStore + { + [TestMethod] + public void StoreTest() + { + using var store = new MemoryStore(); + + store.Delete(0, new byte[] { 1 }); + Assert.AreEqual(null, store.TryGet(1, new byte[] { 1 })); + store.Put(1, new byte[] { 1 }, new byte[] { 1, 2, 3 }); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, store.TryGet(1, new byte[] { 1 })); + + store.Put(1, new byte[] { 2 }, new byte[] { 4, 5, 6 }); + CollectionAssert.AreEqual(new byte[] { 1 }, store.Seek(1, new byte[] { }, SeekDirection.Forward).Select(u => u.Key).First()); + CollectionAssert.AreEqual(new byte[] { 2 }, store.Seek(1, new byte[] { }, SeekDirection.Backward).Select(u => u.Key).First()); + CollectionAssert.AreEqual(new byte[] { 1 }, store.Seek(1, new byte[] { 1 }, SeekDirection.Backward).Select(u => u.Key).First()); + + store.Delete(0, new byte[] { 1 }); + } + } +} diff --git a/tests/neo.UnitTests/Persistence/UT_ReadOnlyView.cs b/tests/neo.UnitTests/Persistence/UT_ReadOnlyView.cs new file mode 100644 index 0000000000..40a0fe8a70 --- /dev/null +++ b/tests/neo.UnitTests/Persistence/UT_ReadOnlyView.cs @@ -0,0 +1,35 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Persistence; +using System; +using System.Linq; + +namespace Neo.UnitTests.Persistence +{ + [TestClass] + public class UT_ReadOnlyView + { + [TestMethod] + public void CommitException() + { + var r = new ReadOnlyView(new MemoryStore()); + Assert.ThrowsException(() => r.Commit()); + } + + [TestMethod] + public void Stores() + { + var r = new ReadOnlyView(new MemoryStore()); + + Assert.AreEqual(uint.MaxValue, r.BlockHashIndex.Get().Index); + Assert.AreEqual(UInt256.Zero, r.BlockHashIndex.Get().Hash); + Assert.AreEqual(uint.MaxValue, r.HeaderHashIndex.Get().Index); + Assert.AreEqual(UInt256.Zero, r.HeaderHashIndex.Get().Hash); + Assert.AreEqual(0, r.ContractId.Get().NextId); + Assert.AreEqual(0, r.Blocks.Find().Count()); + Assert.AreEqual(0, r.Transactions.Find().Count()); + Assert.AreEqual(0, r.Contracts.Find().Count()); + Assert.AreEqual(0, r.Storages.Find().Count()); + Assert.AreEqual(0, r.HeaderHashList.Find().Count()); + } + } +} diff --git a/tests/neo.UnitTests/Plugins/UT_Plugin.cs b/tests/neo.UnitTests/Plugins/UT_Plugin.cs index cee7194c47..d56dcd8c15 100644 --- a/tests/neo.UnitTests/Plugins/UT_Plugin.cs +++ b/tests/neo.UnitTests/Plugins/UT_Plugin.cs @@ -10,6 +10,31 @@ public class UT_Plugin { private static readonly object locker = new object(); + private class DummyP2PPlugin : IP2PPlugin { } + private class dummyPersistencePlugin : IPersistencePlugin { } + + [TestMethod] + public void TestIP2PPlugin() + { + var pp = new DummyP2PPlugin() as IP2PPlugin; + + Assert.IsTrue(pp.OnConsensusMessage(null)); + Assert.IsTrue(pp.OnP2PMessage(null)); + } + + [TestMethod] + public void TestIPersistencePlugin() + { + var pp = new dummyPersistencePlugin() as IPersistencePlugin; + + Assert.IsFalse(pp.ShouldThrowExceptionFromCommit(null)); + + // With empty default implementation + + pp.OnCommit(null); + pp.OnPersist(null, null); + } + [TestMethod] public void TestGetConfigFile() { diff --git a/tests/neo.UnitTests/SmartContract/Callbacks/UT_MethodCallback.cs b/tests/neo.UnitTests/SmartContract/Callbacks/UT_MethodCallback.cs new file mode 100644 index 0000000000..a26a69be60 --- /dev/null +++ b/tests/neo.UnitTests/SmartContract/Callbacks/UT_MethodCallback.cs @@ -0,0 +1,67 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Ledger; +using Neo.SmartContract; +using Neo.SmartContract.Callbacks; +using Neo.SmartContract.Manifest; +using System; + +namespace Neo.UnitTests.SmartContract.Callbacks +{ + [TestClass] + public class UT_MethodCallback + { + [TestInitialize] + public void Init() + { + TestBlockchain.InitializeMockNeoSystem(); + } + + [TestMethod] + public void GetHashData() + { + var snapshot = Blockchain.Singleton.GetSnapshot().Clone(); + var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); + + Assert.ThrowsException(() => new MethodCallback(engine, UInt160.Zero, "_test")); + + var contract = new ContractState() + { + Manifest = new ContractManifest() + { + Permissions = new ContractPermission[0], + Groups = new ContractGroup[0], + Trusts = WildcardContainer.Create(), + Abi = new ContractAbi() + { + Methods = new ContractMethodDescriptor[] + { + new ContractMethodDescriptor(){ Name="test", Parameters=new ContractParameterDefinition[0]} + }, + Events = new ContractEventDescriptor[0], + }, + }, + Script = new byte[] { 1, 2, 3 }, + }; + contract.Manifest.Abi.Hash = contract.ScriptHash; + engine.LoadScript(contract.Script); + snapshot.Contracts.Add(contract.ScriptHash, contract); + + Assert.ThrowsException(() => new MethodCallback(engine, contract.ScriptHash, "test")); + + contract.Manifest.Permissions = new ContractPermission[] { + new ContractPermission() { Contract = ContractPermissionDescriptor.Create(contract.ScriptHash), + Methods= WildcardContainer.Create("test") } }; + var data = new MethodCallback(engine, contract.ScriptHash, "test"); + + Assert.AreEqual(0, engine.CurrentContext.EvaluationStack.Count); + var array = new VM.Types.Array(); + + data.LoadContext(engine, array); + + Assert.AreEqual(3, engine.CurrentContext.EvaluationStack.Count); + Assert.AreEqual("9bc4860bb936abf262d7a51f74b4304833fee3b2", engine.Pop().GetSpan().ToHexString()); + Assert.AreEqual("test", engine.Pop().GetString()); + Assert.IsTrue(engine.Pop() == array); + } + } +} diff --git a/tests/neo.UnitTests/SmartContract/Manifest/UT_ContractGroup.cs b/tests/neo.UnitTests/SmartContract/Manifest/UT_ContractGroup.cs index 8b6330cde1..bd5b635ba1 100644 --- a/tests/neo.UnitTests/SmartContract/Manifest/UT_ContractGroup.cs +++ b/tests/neo.UnitTests/SmartContract/Manifest/UT_ContractGroup.cs @@ -10,6 +10,23 @@ namespace Neo.UnitTests.SmartContract.Manifest [TestClass] public class UT_ContractGroup { + [TestMethod] + public void TestClone() + { + Random random = new Random(); + byte[] privateKey = new byte[32]; + random.NextBytes(privateKey); + KeyPair keyPair = new KeyPair(privateKey); + ContractGroup contractGroup = new ContractGroup + { + PubKey = keyPair.PublicKey, + Signature = new byte[20] + }; + + var clone = contractGroup.Clone(); + Assert.AreEqual(clone.ToJson().ToString(), contractGroup.ToJson().ToString()); + } + [TestMethod] public void TestIsValid() { diff --git a/tests/neo.UnitTests/SmartContract/Native/UT_KeyBuilder.cs b/tests/neo.UnitTests/SmartContract/Native/UT_KeyBuilder.cs new file mode 100644 index 0000000000..96552dc12e --- /dev/null +++ b/tests/neo.UnitTests/SmartContract/Native/UT_KeyBuilder.cs @@ -0,0 +1,35 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.SmartContract.Native; + +namespace Neo.UnitTests.SmartContract.Native +{ + [TestClass] + public class UT_KeyBuilder + { + private struct a + { + public int x; + } + + [TestMethod] + public void Test() + { + var key = new KeyBuilder(1, 2); + + Assert.AreEqual("0100000002", key.ToArray().ToHexString()); + + key = new KeyBuilder(1, 2); + key = key.Add(new byte[] { 3, 4 }); + Assert.AreEqual("01000000020304", key.ToArray().ToHexString()); + + key = new KeyBuilder(1, 2); + key = key.Add(new byte[] { 3, 4 }); + key = key.Add(UInt160.Zero); + Assert.AreEqual("010000000203040000000000000000000000000000000000000000", key.ToArray().ToHexString()); + + key = new KeyBuilder(1, 2); + key = key.Add(new a() { x = 123 }); + Assert.AreEqual("01000000027b000000", key.ToArray().ToHexString()); + } + } +} diff --git a/tests/neo.UnitTests/SmartContract/Native/UT_NativeContract.cs b/tests/neo.UnitTests/SmartContract/Native/UT_NativeContract.cs index 3188bddb4c..498dfbafeb 100644 --- a/tests/neo.UnitTests/SmartContract/Native/UT_NativeContract.cs +++ b/tests/neo.UnitTests/SmartContract/Native/UT_NativeContract.cs @@ -1,11 +1,13 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO; using Neo.Ledger; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM.Types; using System; using System.Collections.Generic; +using System.Numerics; using VMArray = Neo.VM.Types.Array; namespace Neo.UnitTests.SmartContract.Native @@ -28,6 +30,71 @@ public void TestInitialize() testNativeContract.Initialize(ae); } + private class DummyNative : NativeContract + { + public override string Name => "Dummy"; + public override int Id => 1; + + [ContractMethod(0, CallFlags.None)] + public void NetTypes( + bool p1, sbyte p2, byte p3, short p4, ushort p5, int p6, uint p7, long p8, ulong p9, BigInteger p10, + byte[] p11, string p12, IInteroperable p13, ISerializable p14, int[] p15, ContractParameterType p16, + object p17) + { } + + [ContractMethod(0, CallFlags.None)] + public void VMTypes( + VM.Types.Boolean p1, VM.Types.Integer p2, VM.Types.ByteString p3, VM.Types.Buffer p4, + VM.Types.Array p5, VM.Types.Struct p6, VM.Types.Map p7, VM.Types.StackItem p8 + ) + { } + } + + [TestMethod] + public void TestToParameter() + { + var manifest = new DummyNative().Manifest; + var netTypes = manifest.Abi.GetMethod("netTypes"); + + Assert.AreEqual(netTypes.ReturnType, ContractParameterType.Void); + Assert.AreEqual(netTypes.Parameters[0].Type, ContractParameterType.Boolean); + Assert.AreEqual(netTypes.Parameters[1].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[2].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[3].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[4].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[5].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[6].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[7].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[8].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[9].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[10].Type, ContractParameterType.ByteArray); + Assert.AreEqual(netTypes.Parameters[11].Type, ContractParameterType.String); + Assert.AreEqual(netTypes.Parameters[12].Type, ContractParameterType.Array); + Assert.AreEqual(netTypes.Parameters[13].Type, ContractParameterType.ByteArray); + Assert.AreEqual(netTypes.Parameters[14].Type, ContractParameterType.Array); + Assert.AreEqual(netTypes.Parameters[15].Type, ContractParameterType.Integer); + Assert.AreEqual(netTypes.Parameters[16].Type, ContractParameterType.Any); + + var vmTypes = manifest.Abi.GetMethod("vMTypes"); + + Assert.AreEqual(vmTypes.ReturnType, ContractParameterType.Void); + Assert.AreEqual(vmTypes.Parameters[0].Type, ContractParameterType.Boolean); + Assert.AreEqual(vmTypes.Parameters[1].Type, ContractParameterType.Integer); + Assert.AreEqual(vmTypes.Parameters[2].Type, ContractParameterType.ByteArray); + Assert.AreEqual(vmTypes.Parameters[3].Type, ContractParameterType.ByteArray); + Assert.AreEqual(vmTypes.Parameters[4].Type, ContractParameterType.Array); + Assert.AreEqual(vmTypes.Parameters[5].Type, ContractParameterType.Array); + Assert.AreEqual(vmTypes.Parameters[6].Type, ContractParameterType.Map); + Assert.AreEqual(vmTypes.Parameters[7].Type, ContractParameterType.Any); + } + + [TestMethod] + public void TestGetContract() + { + Assert.IsTrue(NativeContract.NEO == NativeContract.GetContract(NativeContract.NEO.Name)); + Assert.IsTrue(NativeContract.NEO == NativeContract.GetContract(NativeContract.NEO.Hash)); + } + [TestMethod] public void TestInvoke() { diff --git a/tests/neo.UnitTests/SmartContract/UT_ApplicationEngine.cs b/tests/neo.UnitTests/SmartContract/UT_ApplicationEngine.cs index ed661a27a7..b2810f2571 100644 --- a/tests/neo.UnitTests/SmartContract/UT_ApplicationEngine.cs +++ b/tests/neo.UnitTests/SmartContract/UT_ApplicationEngine.cs @@ -17,11 +17,26 @@ public void TestSetup() TestBlockchain.InitializeMockNeoSystem(); } + [TestMethod] + public void TestBinary() + { + using var snapshot = Blockchain.Singleton.GetSnapshot(); + using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); + + var data = new byte[0]; + CollectionAssert.AreEqual(data, engine.Base64Decode(engine.Base64Encode(data))); + + data = new byte[] { 1, 2, 3 }; + CollectionAssert.AreEqual(data, engine.Base64Decode(engine.Base64Encode(data))); + + Assert.AreEqual("AQIDBA==", engine.Base64Encode(new byte[] { 1, 2, 3, 4 })); + } + [TestMethod] public void TestNotify() { - var snapshot = Blockchain.Singleton.GetSnapshot(); - var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); + using var snapshot = Blockchain.Singleton.GetSnapshot(); + using var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); ApplicationEngine.Notify += Test_Notify1; const string notifyEvent = "TestEvent"; diff --git a/tests/neo.UnitTests/SmartContract/UT_DeployedContract.cs b/tests/neo.UnitTests/SmartContract/UT_DeployedContract.cs new file mode 100644 index 0000000000..1642ec64f2 --- /dev/null +++ b/tests/neo.UnitTests/SmartContract/UT_DeployedContract.cs @@ -0,0 +1,61 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.Ledger; +using Neo.SmartContract; +using System; + +namespace Neo.UnitTests.SmartContract +{ + [TestClass] + public class UT_DeployedContract + { + [TestMethod] + public void TestGetAddress() + { + var contract = new DeployedContract(new ContractState() + { + Manifest = new Neo.SmartContract.Manifest.ContractManifest() + { + Abi = new Neo.SmartContract.Manifest.ContractAbi() + { + Methods = new Neo.SmartContract.Manifest.ContractMethodDescriptor[] + { + new Neo.SmartContract.Manifest.ContractMethodDescriptor() + { + Name="verify", + Parameters=new Neo.SmartContract.Manifest.ContractParameterDefinition[0] + } + } + } + }, + Script = new byte[] { 1, 2, 3 } + }); + + Assert.AreEqual("0xb2e3fe334830b4741fa5d762f2ab36b90b86c49b", contract.ScriptHash.ToString()); + Assert.AreEqual("Na7bMBy8KWZKSFBWTxeSKth1Je9AcWTpQM", contract.Address); + } + + [TestMethod] + public void TestErrors() + { + Assert.ThrowsException(() => new DeployedContract(null)); + Assert.ThrowsException(() => new DeployedContract(new ContractState() + { + Manifest = new Neo.SmartContract.Manifest.ContractManifest() + { + Abi = new Neo.SmartContract.Manifest.ContractAbi() + { + Methods = new Neo.SmartContract.Manifest.ContractMethodDescriptor[] + { + new Neo.SmartContract.Manifest.ContractMethodDescriptor() + { + Name="noverify", + Parameters=new Neo.SmartContract.Manifest.ContractParameterDefinition[0] + } + } + } + }, + Script = new byte[] { 1, 2, 3 } + })); + } + } +} diff --git a/tests/neo.UnitTests/SmartContract/UT_JsonSerializer.cs b/tests/neo.UnitTests/SmartContract/UT_JsonSerializer.cs index 220627d5d0..471f31656e 100644 --- a/tests/neo.UnitTests/SmartContract/UT_JsonSerializer.cs +++ b/tests/neo.UnitTests/SmartContract/UT_JsonSerializer.cs @@ -206,6 +206,12 @@ public void Serialize_Number() Assert.ThrowsException(() => JsonSerializer.Serialize(entry)); } + [TestMethod] + public void Serialize_Null() + { + Assert.AreEqual(JObject.Null, JsonSerializer.Serialize(StackItem.Null)); + } + [TestMethod] public void Deserialize_EmptyObject() { diff --git a/tests/neo.UnitTests/UT_Helper.cs b/tests/neo.UnitTests/UT_Helper.cs index 51e74d3750..50964a3ce9 100644 --- a/tests/neo.UnitTests/UT_Helper.cs +++ b/tests/neo.UnitTests/UT_Helper.cs @@ -1,9 +1,12 @@ using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Caching; using Neo.Network.P2P; using Neo.SmartContract; using Neo.Wallets; using System; +using System.Collections.Generic; +using System.Linq; using System.Net; using System.Numerics; using System.Security.Cryptography; @@ -45,16 +48,27 @@ public void TestGetLowestSetBit() var big2 = new BigInteger(512); big2.GetLowestSetBit().Should().Be(9); + + var big3 = new BigInteger(int.MinValue); + big3.GetLowestSetBit().Should().Be(31); + + var big4 = new BigInteger(long.MinValue); + big4.GetLowestSetBit().Should().Be(63); } [TestMethod] public void TestGetBitLength() { - var b1 = new BigInteger(100); - b1.GetBitLength().Should().Be(7); - - var b2 = new BigInteger(-100); - b2.GetBitLength().Should().Be(7); + new BigInteger(100).GetBitLength().Should().Be(7); + new BigInteger(-100).GetBitLength().Should().Be(7); + new BigInteger(0).GetBitLength().Should().Be(8); + new BigInteger(512).GetBitLength().Should().Be(10); + new BigInteger(short.MinValue).GetBitLength().Should().Be(15); + new BigInteger(short.MaxValue).GetBitLength().Should().Be(15); + new BigInteger(int.MinValue).GetBitLength().Should().Be(31); + new BigInteger(int.MaxValue).GetBitLength().Should().Be(31); + new BigInteger(long.MinValue).GetBitLength().Should().Be(63); + new BigInteger(long.MaxValue).GetBitLength().Should().Be(63); } [TestMethod] @@ -72,6 +86,128 @@ public void TestHexToBytes() bytes.ToHexString().Should().Be(new byte[] { 0x01, 0x02 }.ToHexString()); } + [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()); + } + + [TestMethod] + public void TestRemoveHashsetHashSetCache() + { + var a = new HashSet + { + 1, + 2, + 3 + }; + + var b = new HashSetCache(10) + { + 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()); + } + + [TestMethod] + public void TestToHexString() + { + byte[] nullStr = null; + Assert.ThrowsException(() => nullStr.ToHexString()); + byte[] empty = new byte[0]; + 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() + { + string version = typeof(TestMethodAttribute).Assembly.GetVersion(); + version.Should().Be("14.0.4701.02"); + + // 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(); + version = asm?.GetVersion() ?? ""; + 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() { diff --git a/tests/neo.UnitTests/UT_Utility.cs b/tests/neo.UnitTests/UT_Utility.cs new file mode 100644 index 0000000000..85f4c00c97 --- /dev/null +++ b/tests/neo.UnitTests/UT_Utility.cs @@ -0,0 +1,22 @@ +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; + +namespace Neo.UnitTests +{ + [TestClass] + public class UT_Utility + { + [TestMethod] + public void LoadConfig() + { + Assert.IsFalse(File.Exists("test.json")); + Utility.LoadConfig("test").GetSection("test").Value.Should().BeNull(); + + File.WriteAllText("test.json", @"{""test"":1}"); + Assert.IsTrue(File.Exists("test.json")); + Utility.LoadConfig("test").GetSection("test").Value.Should().Be("1"); + File.Delete("test.json"); + } + } +}