From c4799e9f65830fe4f7cde2784b8435487395d0a5 Mon Sep 17 00:00:00 2001 From: Shargon Date: Sat, 11 Jul 2020 11:24:24 +0200 Subject: [PATCH] Sender from signers (#1752) * Sender from signers * Remove co- * Move signers outside attributes * Fix UT and remove Signers class * Fix UT * Add FeeOnly scope * Remove orderBy * Remove _signersCache * Fix Signers * Fix WitnessScope * Fix Sender * Update TransactionAttributeType.cs * Update Wallet.cs * Fix Wallet * Rename * Update Wallet.cs * Update Wallet.cs * Partial UT fix * More UT fixes * Fix Sender's WitnessScope * Fix Wallet * Fix UT * Explicit FeeOnly for DeployNativeContracts * Same order as serialization * Test FeeOnly * dotnet format * format Co-authored-by: Erik Zhang --- src/neo/Ledger/Blockchain.cs | 9 +- .../P2P/Payloads/{Cosigner.cs => Signer.cs} | 20 +- src/neo/Network/P2P/Payloads/Transaction.cs | 58 +++--- .../P2P/Payloads/TransactionAttributeType.cs | 4 - src/neo/Network/P2P/Payloads/WitnessScope.cs | 13 +- .../ApplicationEngine.Runtime.cs | 15 +- src/neo/Wallets/Wallet.cs | 49 +++-- .../Consensus/UT_ConsensusContext.cs | 4 +- .../Cryptography/UT_Cryptography_Helper.cs | 2 +- .../neo.UnitTests/IO/Caching/UT_RelayCache.cs | 5 +- tests/neo.UnitTests/Ledger/UT_Blockchain.cs | 51 +++-- tests/neo.UnitTests/Ledger/UT_MemoryPool.cs | 8 +- tests/neo.UnitTests/Ledger/UT_PoolItem.cs | 4 +- .../Ledger/UT_SendersFeeMonitor.cs | 2 +- .../Ledger/UT_TransactionState.cs | 2 +- tests/neo.UnitTests/Ledger/UT_TrimmedBlock.cs | 14 +- .../Network/P2P/Payloads/UT_Block.cs | 26 +-- .../{UT_Cosigner.cs => UT_Signers.cs} | 42 ++-- .../Network/P2P/Payloads/UT_Transaction.cs | 179 ++++++++++-------- .../Network/P2P/Payloads/UT_Witness.cs | 6 +- .../UT_ContractParameterContext.cs | 29 ++- .../SmartContract/UT_InteropService.cs | 4 +- .../SmartContract/UT_Syscalls.cs | 4 +- tests/neo.UnitTests/TestUtils.cs | 14 +- tests/neo.UnitTests/Wallets/UT_Wallet.cs | 13 +- 25 files changed, 319 insertions(+), 258 deletions(-) rename src/neo/Network/P2P/Payloads/{Cosigner.cs => Signer.cs} (77%) rename tests/neo.UnitTests/Network/P2P/Payloads/{UT_Cosigner.cs => UT_Signers.cs} (66%) diff --git a/src/neo/Ledger/Blockchain.cs b/src/neo/Ledger/Blockchain.cs index 50cee9509d..092309a5a7 100644 --- a/src/neo/Ledger/Blockchain.cs +++ b/src/neo/Ledger/Blockchain.cs @@ -166,8 +166,15 @@ private static Transaction DeployNativeContracts() { Version = 0, Script = script, - Sender = (new[] { (byte)OpCode.PUSH1 }).ToScriptHash(), SystemFee = 0, + Signers = new[] + { + new Signer + { + Account = (new[] { (byte)OpCode.PUSH1 }).ToScriptHash(), + Scopes = WitnessScope.FeeOnly + } + }, Attributes = Array.Empty(), Witnesses = new[] { diff --git a/src/neo/Network/P2P/Payloads/Cosigner.cs b/src/neo/Network/P2P/Payloads/Signer.cs similarity index 77% rename from src/neo/Network/P2P/Payloads/Cosigner.cs rename to src/neo/Network/P2P/Payloads/Signer.cs index ba8a6fa3dd..4be59a349f 100644 --- a/src/neo/Network/P2P/Payloads/Cosigner.cs +++ b/src/neo/Network/P2P/Payloads/Signer.cs @@ -1,12 +1,13 @@ using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; +using System; using System.IO; using System.Linq; namespace Neo.Network.P2P.Payloads { - public class Cosigner : TransactionAttribute + public class Signer : ISerializable { // This limits maximum number of AllowedContracts or AllowedGroups here private const int MaxSubitems = 16; @@ -16,19 +17,20 @@ public class Cosigner : TransactionAttribute public UInt160[] AllowedContracts; public ECPoint[] AllowedGroups; - public override TransactionAttributeType Type => TransactionAttributeType.Cosigner; - public override bool AllowMultiple => true; - - public override int Size => base.Size + + public int Size => /*Account*/ UInt160.Length + /*Scopes*/ sizeof(WitnessScope) + /*AllowedContracts*/ (Scopes.HasFlag(WitnessScope.CustomContracts) ? AllowedContracts.GetVarSize() : 0) + /*AllowedGroups*/ (Scopes.HasFlag(WitnessScope.CustomGroups) ? AllowedGroups.GetVarSize() : 0); - protected override void DeserializeWithoutType(BinaryReader reader) + public void Deserialize(BinaryReader reader) { Account = reader.ReadSerializable(); Scopes = (WitnessScope)reader.ReadByte(); + if ((Scopes & ~(WitnessScope.CalledByEntry | WitnessScope.CustomContracts | WitnessScope.CustomGroups | WitnessScope.Global)) != 0) + throw new FormatException(); + if (Scopes.HasFlag(WitnessScope.Global) && Scopes != WitnessScope.Global) + throw new FormatException(); AllowedContracts = Scopes.HasFlag(WitnessScope.CustomContracts) ? reader.ReadSerializableArray(MaxSubitems) : new UInt160[0]; @@ -37,7 +39,7 @@ protected override void DeserializeWithoutType(BinaryReader reader) : new ECPoint[0]; } - protected override void SerializeWithoutType(BinaryWriter writer) + public void Serialize(BinaryWriter writer) { writer.Write(Account); writer.Write((byte)Scopes); @@ -47,9 +49,9 @@ protected override void SerializeWithoutType(BinaryWriter writer) writer.Write(AllowedGroups); } - public override JObject ToJson() + public JObject ToJson() { - JObject json = base.ToJson(); + var json = new JObject(); json["account"] = Account.ToString(); json["scopes"] = Scopes; if (Scopes.HasFlag(WitnessScope.CustomContracts)) diff --git a/src/neo/Network/P2P/Payloads/Transaction.cs b/src/neo/Network/P2P/Payloads/Transaction.cs index 127f56cb17..5aab07af65 100644 --- a/src/neo/Network/P2P/Payloads/Transaction.cs +++ b/src/neo/Network/P2P/Payloads/Transaction.cs @@ -28,10 +28,10 @@ public class Transaction : IEquatable, IInventory, IInteroperable private byte version; private uint nonce; - private UInt160 sender; private long sysfee; private long netfee; private uint validUntilBlock; + private Signer[] _signers; private TransactionAttribute[] attributes; private byte[] script; private Witness[] witnesses; @@ -39,7 +39,6 @@ public class Transaction : IEquatable, IInventory, IInteroperable public const int HeaderSize = sizeof(byte) + //Version sizeof(uint) + //Nonce - 20 + //Sender sizeof(long) + //SystemFee sizeof(long) + //NetworkFee sizeof(uint); //ValidUntilBlock @@ -47,12 +46,9 @@ public class Transaction : IEquatable, IInventory, IInteroperable public TransactionAttribute[] Attributes { get => attributes; - set { attributes = value; _cosigners = null; _hash = null; _size = 0; } + set { attributes = value; _hash = null; _size = 0; } } - private Dictionary _cosigners; - public IReadOnlyDictionary Cosigners => _cosigners ??= attributes.OfType().ToDictionary(p => p.Account); - /// /// The NetworkFee for the transaction divided by its Size. /// Note that this property must be used with care. Getting the value of this property multiple times will return the same result. The value of this property can only be obtained after the transaction has been completely built (no longer modified). @@ -95,10 +91,15 @@ public byte[] Script set { script = value; _hash = null; _size = 0; } } - public UInt160 Sender + /// + /// Correspond with the first entry of Signers + /// + public UInt160 Sender => _signers[0].Account; + + public Signer[] Signers { - get => sender; - set { sender = value; _hash = null; } + get => _signers; + set { _signers = value; _hash = null; _size = 0; } } private int _size; @@ -109,6 +110,7 @@ public int Size if (_size == 0) { _size = HeaderSize + + Signers.GetVarSize() + // Signers Attributes.GetVarSize() + // Attributes Script.GetVarSize() + // Script Witnesses.GetVarSize(); // Witnesses @@ -155,9 +157,9 @@ void ISerializable.Deserialize(BinaryReader reader) _size = (int)reader.BaseStream.Position - startPosition; } - private static IEnumerable DeserializeAttributes(BinaryReader reader) + private static IEnumerable DeserializeAttributes(BinaryReader reader, int maxCount) { - int count = (int)reader.ReadVarInt(MaxTransactionAttributes); + int count = (int)reader.ReadVarInt((ulong)maxCount); HashSet hashset = new HashSet(); while (count-- > 0) { @@ -168,27 +170,35 @@ private static IEnumerable DeserializeAttributes(BinaryRea } } + private static IEnumerable DeserializeSigners(BinaryReader reader, int maxCount) + { + int count = (int)reader.ReadVarInt((ulong)maxCount); + if (count == 0) throw new FormatException(); + HashSet hashset = new HashSet(); + for (int i = 0; i < count; i++) + { + Signer signer = reader.ReadSerializable(); + if (i > 0 && signer.Scopes == WitnessScope.FeeOnly) + throw new FormatException(); + if (!hashset.Add(signer.Account)) + throw new FormatException(); + yield return signer; + } + } + public void DeserializeUnsigned(BinaryReader reader) { Version = reader.ReadByte(); if (Version > 0) throw new FormatException(); Nonce = reader.ReadUInt32(); - Sender = reader.ReadSerializable(); SystemFee = reader.ReadInt64(); if (SystemFee < 0) throw new FormatException(); NetworkFee = reader.ReadInt64(); if (NetworkFee < 0) throw new FormatException(); if (SystemFee + NetworkFee < SystemFee) throw new FormatException(); ValidUntilBlock = reader.ReadUInt32(); - Attributes = DeserializeAttributes(reader).ToArray(); - try - { - _ = Cosigners; - } - catch (ArgumentException) - { - throw new FormatException(); - } + Signers = DeserializeSigners(reader, MaxTransactionAttributes).ToArray(); + Attributes = DeserializeAttributes(reader, MaxTransactionAttributes - Signers.Length).ToArray(); Script = reader.ReadVarBytes(ushort.MaxValue); if (Script.Length == 0) throw new FormatException(); } @@ -217,8 +227,7 @@ public override int GetHashCode() public UInt160[] GetScriptHashesForVerifying(StoreView snapshot) { - var hashes = new HashSet(Cosigners.Keys) { Sender }; - return hashes.OrderBy(p => p).ToArray(); + return Signers.Select(p => p.Account).ToArray(); } void ISerializable.Serialize(BinaryWriter writer) @@ -231,10 +240,10 @@ void IVerifiable.SerializeUnsigned(BinaryWriter writer) { writer.Write(Version); writer.Write(Nonce); - writer.Write(Sender); writer.Write(SystemFee); writer.Write(NetworkFee); writer.Write(ValidUntilBlock); + writer.Write(Signers); writer.Write(Attributes); writer.WriteVarBytes(Script); } @@ -250,6 +259,7 @@ public JObject ToJson() json["sysfee"] = SystemFee.ToString(); json["netfee"] = NetworkFee.ToString(); json["validuntilblock"] = ValidUntilBlock; + json["signers"] = Signers.Select(p => p.ToJson()).ToArray(); json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray(); json["script"] = Convert.ToBase64String(Script); json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray(); diff --git a/src/neo/Network/P2P/Payloads/TransactionAttributeType.cs b/src/neo/Network/P2P/Payloads/TransactionAttributeType.cs index f1e2d704da..c3f32ddecf 100644 --- a/src/neo/Network/P2P/Payloads/TransactionAttributeType.cs +++ b/src/neo/Network/P2P/Payloads/TransactionAttributeType.cs @@ -1,10 +1,6 @@ -using Neo.IO.Caching; - namespace Neo.Network.P2P.Payloads { public enum TransactionAttributeType : byte { - [ReflectionCache(typeof(Cosigner))] - Cosigner = 0x01 } } diff --git a/src/neo/Network/P2P/Payloads/WitnessScope.cs b/src/neo/Network/P2P/Payloads/WitnessScope.cs index f35e550a34..9cc3cd99fd 100644 --- a/src/neo/Network/P2P/Payloads/WitnessScope.cs +++ b/src/neo/Network/P2P/Payloads/WitnessScope.cs @@ -6,10 +6,9 @@ namespace Neo.Network.P2P.Payloads public enum WitnessScope : byte { /// - /// Global allows this witness in all contexts (default Neo2 behavior) - /// This cannot be combined with other flags + /// It's only valid for be a sender, it can't be used during the execution /// - Global = 0x00, + FeeOnly = 0, /// /// CalledByEntry means that this condition must hold: EntryScriptHash == CallingScriptHash @@ -26,6 +25,12 @@ public enum WitnessScope : byte /// /// Custom pubkey for group members /// - CustomGroups = 0x20 + CustomGroups = 0x20, + + /// + /// Global allows this witness in all contexts (default Neo2 behavior) + /// This cannot be combined with other flags + /// + Global = 0x80 } } diff --git a/src/neo/SmartContract/ApplicationEngine.Runtime.cs b/src/neo/SmartContract/ApplicationEngine.Runtime.cs index a000f06e34..c670971937 100644 --- a/src/neo/SmartContract/ApplicationEngine.Runtime.cs +++ b/src/neo/SmartContract/ApplicationEngine.Runtime.cs @@ -104,23 +104,24 @@ internal bool CheckWitnessInternal(UInt160 hash) { if (ScriptContainer is Transaction tx) { - if (!tx.Cosigners.TryGetValue(hash, out Cosigner cosigner)) return false; - if (cosigner.Scopes == WitnessScope.Global) return true; - if (cosigner.Scopes.HasFlag(WitnessScope.CalledByEntry)) + Signer signer = tx.Signers.FirstOrDefault(p => p.Account.Equals(hash)); + if (signer is null) return false; + if (signer.Scopes == WitnessScope.Global) return true; + if (signer.Scopes.HasFlag(WitnessScope.CalledByEntry)) { if (CallingScriptHash == EntryScriptHash) return true; } - if (cosigner.Scopes.HasFlag(WitnessScope.CustomContracts)) + if (signer.Scopes.HasFlag(WitnessScope.CustomContracts)) { - if (cosigner.AllowedContracts.Contains(CurrentScriptHash)) + if (signer.AllowedContracts.Contains(CurrentScriptHash)) return true; } - if (cosigner.Scopes.HasFlag(WitnessScope.CustomGroups)) + if (signer.Scopes.HasFlag(WitnessScope.CustomGroups)) { var contract = Snapshot.Contracts[CallingScriptHash]; // check if current group is the required one - if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(cosigner.AllowedGroups).Any()) + if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(signer.AllowedGroups).Any()) return true; } return false; diff --git a/src/neo/Wallets/Wallet.cs b/src/neo/Wallets/Wallet.cs index d18abbc9f1..d77532abb9 100644 --- a/src/neo/Wallets/Wallet.cs +++ b/src/neo/Wallets/Wallet.cs @@ -192,6 +192,26 @@ public static byte[] GetPrivateKeyFromWIF(string wif) return privateKey; } + private static Signer[] GetSigners(UInt160 sender, Signer[] cosigners) + { + for (int i = 0; i < cosigners.Length; i++) + { + if (cosigners[i].Account.Equals(sender)) + { + if (i == 0) return cosigners; + List list = new List(cosigners); + list.RemoveAt(i); + list.Insert(0, cosigners[i]); + return list.ToArray(); + } + } + return cosigners.Prepend(new Signer + { + Account = sender, + Scopes = WitnessScope.FeeOnly + }).ToArray(); + } + public virtual WalletAccount Import(X509Certificate2 cert) { byte[] privateKey; @@ -277,19 +297,18 @@ public Transaction MakeTransaction(TransferOutput[] outputs, UInt160 from = null if (balances_gas is null) balances_gas = accounts.Select(p => (Account: p, Value: NativeContract.GAS.BalanceOf(snapshot, p))).Where(p => p.Value.Sign > 0).ToList(); - var cosigners = cosignerList.Select(p => - new Cosigner() - { - // default access for transfers should be valid only for first invocation - Scopes = WitnessScope.CalledByEntry, - Account = new UInt160(p.ToArray()) - }).ToArray(); + var cosigners = cosignerList.Select(p => new Signer() + { + // default access for transfers should be valid only for first invocation + Scopes = WitnessScope.CalledByEntry, + Account = p + }).ToArray(); - return MakeTransaction(snapshot, script, cosigners, balances_gas); + return MakeTransaction(snapshot, script, cosigners, Array.Empty(), balances_gas); } } - public Transaction MakeTransaction(byte[] script, UInt160 sender = null, TransactionAttribute[] attributes = null) + public Transaction MakeTransaction(byte[] script, UInt160 sender = null, Signer[] cosigners = null, TransactionAttribute[] attributes = null) { UInt160[] accounts; if (sender is null) @@ -299,17 +318,17 @@ public Transaction MakeTransaction(byte[] script, UInt160 sender = null, Transac else { if (!Contains(sender)) - throw new ArgumentException($"The address {sender.ToString()} was not found in the wallet"); + throw new ArgumentException($"The address {sender} was not found in the wallet"); accounts = new[] { sender }; } using (SnapshotView snapshot = Blockchain.Singleton.GetSnapshot()) { var balances_gas = accounts.Select(p => (Account: p, Value: NativeContract.GAS.BalanceOf(snapshot, p))).Where(p => p.Value.Sign > 0).ToList(); - return MakeTransaction(snapshot, script, attributes ?? new TransactionAttribute[0], balances_gas); + return MakeTransaction(snapshot, script, cosigners ?? Array.Empty(), attributes ?? Array.Empty(), balances_gas); } } - private Transaction MakeTransaction(StoreView snapshot, byte[] script, TransactionAttribute[] attributes, List<(UInt160 Account, BigInteger Value)> balances_gas) + private Transaction MakeTransaction(StoreView snapshot, byte[] script, Signer[] cosigners, TransactionAttribute[] attributes, List<(UInt160 Account, BigInteger Value)> balances_gas) { Random rand = new Random(); foreach (var (account, value) in balances_gas) @@ -319,8 +338,8 @@ private Transaction MakeTransaction(StoreView snapshot, byte[] script, Transacti Version = 0, Nonce = (uint)rand.Next(), Script = script, - Sender = account, ValidUntilBlock = snapshot.Height + Transaction.MaxValidUntilBlockIncrement, + Signers = GetSigners(account, cosigners), Attributes = attributes, }; @@ -336,8 +355,8 @@ private Transaction MakeTransaction(StoreView snapshot, byte[] script, Transacti UInt160[] hashes = tx.GetScriptHashesForVerifying(snapshot); - // base size for transaction: includes const_header + attributes + script + hashes - int size = Transaction.HeaderSize + tx.Attributes.GetVarSize() + script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); + // base size for transaction: includes const_header + signers + attributes + script + hashes + int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Attributes.GetVarSize() + script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); foreach (UInt160 hash in hashes) { diff --git a/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs b/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs index 2f32b4b7ff..ca12f676a0 100644 --- a/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs +++ b/tests/neo.UnitTests/Consensus/UT_ConsensusContext.cs @@ -125,10 +125,10 @@ private Transaction CreateTransactionWithSize(int v) var tx = new Transaction() { Attributes = System.Array.Empty(), + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, NetworkFee = 0, Nonce = (uint)Environment.TickCount, Script = new byte[0], - Sender = UInt160.Zero, SystemFee = 0, ValidUntilBlock = (uint)r.Next(), Version = 0, @@ -145,10 +145,10 @@ private Transaction CreateTransactionWithSytemFee(long fee) var tx = new Transaction() { Attributes = System.Array.Empty(), + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, NetworkFee = 0, Nonce = (uint)Environment.TickCount, Script = new byte[0], - Sender = UInt160.Zero, SystemFee = fee, ValidUntilBlock = int.MaxValue, Version = 0, diff --git a/tests/neo.UnitTests/Cryptography/UT_Cryptography_Helper.cs b/tests/neo.UnitTests/Cryptography/UT_Cryptography_Helper.cs index b2c5775903..65aa81e0c0 100644 --- a/tests/neo.UnitTests/Cryptography/UT_Cryptography_Helper.cs +++ b/tests/neo.UnitTests/Cryptography/UT_Cryptography_Helper.cs @@ -152,8 +152,8 @@ public void TestTest() Transaction tx = new Transaction { Script = TestUtils.GetByteArray(32, 0x42), - Sender = UInt160.Zero, SystemFee = 4200000000, + Signers = Array.Empty(), Attributes = Array.Empty(), Witnesses = new[] { diff --git a/tests/neo.UnitTests/IO/Caching/UT_RelayCache.cs b/tests/neo.UnitTests/IO/Caching/UT_RelayCache.cs index d442a018e9..659b7f5797 100644 --- a/tests/neo.UnitTests/IO/Caching/UT_RelayCache.cs +++ b/tests/neo.UnitTests/IO/Caching/UT_RelayCache.cs @@ -24,16 +24,15 @@ public void TestGetKeyForItem() { Version = 0, Nonce = 1, - Sender = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"), SystemFee = 0, NetworkFee = 0, ValidUntilBlock = 100, Attributes = Array.Empty(), + Signers = Array.Empty(), Script = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04 }, - Witnesses = new Witness[0] + Witnesses = Array.Empty() }; relayCache.Add(tx); - relayCache.Contains(tx).Should().BeTrue(); relayCache.TryGet(tx.Hash, out IInventory tmp).Should().BeTrue(); (tmp is Transaction).Should().BeTrue(); diff --git a/tests/neo.UnitTests/Ledger/UT_Blockchain.cs b/tests/neo.UnitTests/Ledger/UT_Blockchain.cs index 7e04dfe229..a94bd98984 100644 --- a/tests/neo.UnitTests/Ledger/UT_Blockchain.cs +++ b/tests/neo.UnitTests/Ledger/UT_Blockchain.cs @@ -73,13 +73,13 @@ public void TestContainsTransaction() [TestMethod] public void TestGetCurrentBlockHash() { - Blockchain.Singleton.CurrentBlockHash.Should().Be(UInt256.Parse("0x3843c6d0dd2082a801cf3da0fe0e847ba8d5571e0606c5018f9a35ce49c55e18")); + Blockchain.Singleton.CurrentBlockHash.Should().Be(UInt256.Parse("0xecaee33262f1bc7c7c28f2b25b54a5d61d50670871f45c0c6fe755a40cbde4a8")); } [TestMethod] public void TestGetCurrentHeaderHash() { - Blockchain.Singleton.CurrentHeaderHash.Should().Be(UInt256.Parse("0x3843c6d0dd2082a801cf3da0fe0e847ba8d5571e0606c5018f9a35ce49c55e18")); + Blockchain.Singleton.CurrentHeaderHash.Should().Be(UInt256.Parse("0xecaee33262f1bc7c7c28f2b25b54a5d61d50670871f45c0c6fe755a40cbde4a8")); } [TestMethod] @@ -91,7 +91,7 @@ public void TestGetBlock() [TestMethod] public void TestGetBlockHash() { - Blockchain.Singleton.GetBlockHash(0).Should().Be(UInt256.Parse("0x3843c6d0dd2082a801cf3da0fe0e847ba8d5571e0606c5018f9a35ce49c55e18")); + Blockchain.Singleton.GetBlockHash(0).Should().Be(UInt256.Parse("0xecaee33262f1bc7c7c28f2b25b54a5d61d50670871f45c0c6fe755a40cbde4a8")); Blockchain.Singleton.GetBlockHash(10).Should().BeNull(); } @@ -109,33 +109,29 @@ public void TestValidTransaction() var snapshot = Blockchain.Singleton.GetSnapshot(); var walletA = TestUtils.GenerateTestWallet(); - using (var unlockA = walletA.Unlock("123")) - { - var acc = walletA.CreateAccount(); - - // Fake balance + using var unlockA = walletA.Unlock("123"); + var acc = walletA.CreateAccount(); - var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash); - var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem(new AccountState())); + // Fake balance - entry.GetInteroperable().Balance = 100_000_000 * NativeContract.GAS.Factor; + var key = new KeyBuilder(NativeContract.GAS.Id, 20).Add(acc.ScriptHash); + var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem(new AccountState())); + entry.GetInteroperable().Balance = 100_000_000 * NativeContract.GAS.Factor; + snapshot.Commit(); - snapshot.Commit(); + typeof(Blockchain) + .GetMethod("UpdateCurrentSnapshot", BindingFlags.Instance | BindingFlags.NonPublic) + .Invoke(Blockchain.Singleton, null); - typeof(Blockchain) - .GetMethod("UpdateCurrentSnapshot", BindingFlags.Instance | BindingFlags.NonPublic) - .Invoke(Blockchain.Singleton, null); + // Make transaction - // Make transaction + var tx = CreateValidTx(walletA, acc.ScriptHash, 0); - var tx = CreateValidTx(walletA, acc.ScriptHash, 0); + senderProbe.Send(system.Blockchain, tx); + senderProbe.ExpectMsg(p => p.Result == VerifyResult.Succeed); - senderProbe.Send(system.Blockchain, tx); - senderProbe.ExpectMsg(p => p.Result == VerifyResult.Succeed); - - senderProbe.Send(system.Blockchain, tx); - senderProbe.ExpectMsg(p => p.Result == VerifyResult.AlreadyExists); - } + senderProbe.Send(system.Blockchain, tx); + senderProbe.ExpectMsg(p => p.Result == VerifyResult.AlreadyExists); } [TestMethod] @@ -145,10 +141,10 @@ public void TestInvalidTransactionInPersist() var tx = new Transaction() { Attributes = Array.Empty(), + Signers = Array.Empty(), NetworkFee = 0, Nonce = (uint)Environment.TickCount, Script = new byte[] { 1 }, - Sender = UInt160.Zero, SystemFee = 0, ValidUntilBlock = Blockchain.GenesisBlock.Index + 1, Version = 0, @@ -184,9 +180,9 @@ private Transaction CreateValidTx(NEP6Wallet wallet, UInt160 account, uint nonce { new TransferOutput() { - AssetId = NativeContract.GAS.Hash, - ScriptHash = account, - Value = new BigDecimal(1,8) + AssetId = NativeContract.GAS.Hash, + ScriptHash = account, + Value = new BigDecimal(1,8) } }, account); @@ -198,7 +194,6 @@ private Transaction CreateValidTx(NEP6Wallet wallet, UInt160 account, uint nonce Assert.IsTrue(data.Completed); tx.Witnesses = data.GetWitnesses(); - return tx; } } diff --git a/tests/neo.UnitTests/Ledger/UT_MemoryPool.cs b/tests/neo.UnitTests/Ledger/UT_MemoryPool.cs index 4e96605b7b..4fd9617e63 100644 --- a/tests/neo.UnitTests/Ledger/UT_MemoryPool.cs +++ b/tests/neo.UnitTests/Ledger/UT_MemoryPool.cs @@ -77,9 +77,9 @@ private Transaction CreateTransactionWithFee(long fee) mock.Setup(p => p.VerifyForEachBlock(It.IsAny(), It.IsAny())).Returns(VerifyResult.Succeed); mock.Setup(p => p.Verify(It.IsAny(), It.IsAny())).Returns(VerifyResult.Succeed); mock.Object.Script = randomBytes; - mock.Object.Sender = UInt160.Zero; mock.Object.NetworkFee = fee; mock.Object.Attributes = Array.Empty(); + mock.Object.Signers = new Signer[] { new Signer() { Account = UInt160.Zero, Scopes = WitnessScope.FeeOnly } }; mock.Object.Witnesses = new[] { new Witness @@ -97,13 +97,13 @@ private Transaction CreateTransactionWithFeeAndBalanceVerify(long fee) var randomBytes = new byte[16]; random.NextBytes(randomBytes); Mock mock = new Mock(); - UInt160 sender = UInt160.Zero; - mock.Setup(p => p.VerifyForEachBlock(It.IsAny(), It.IsAny())).Returns((StoreView snapshot, BigInteger amount) => NativeContract.GAS.BalanceOf(snapshot, sender) >= amount + fee ? VerifyResult.Succeed : VerifyResult.InsufficientFunds); + mock.Setup(p => p.VerifyForEachBlock(It.IsAny(), It.IsAny())).Returns((StoreView snapshot, BigInteger amount) => + NativeContract.GAS.BalanceOf(snapshot, UInt160.Zero) >= amount + fee ? VerifyResult.Succeed : VerifyResult.InsufficientFunds); mock.Setup(p => p.Verify(It.IsAny(), It.IsAny())).Returns(VerifyResult.Succeed); mock.Object.Script = randomBytes; - mock.Object.Sender = sender; mock.Object.NetworkFee = fee; mock.Object.Attributes = Array.Empty(); + mock.Object.Signers = new Signer[] { new Signer() { Account = UInt160.Zero, Scopes = WitnessScope.FeeOnly } }; mock.Object.Witnesses = new[] { new Witness diff --git a/tests/neo.UnitTests/Ledger/UT_PoolItem.cs b/tests/neo.UnitTests/Ledger/UT_PoolItem.cs index 09b6e71fba..4c4c406c62 100644 --- a/tests/neo.UnitTests/Ledger/UT_PoolItem.cs +++ b/tests/neo.UnitTests/Ledger/UT_PoolItem.cs @@ -118,9 +118,9 @@ public static Transaction GenerateTx(long networkFee, int size, byte[] overrideS { Nonce = (uint)TestRandom.Next(), Script = overrideScriptBytes ?? new byte[0], - Sender = UInt160.Zero, NetworkFee = networkFee, Attributes = Array.Empty(), + Signers = Array.Empty(), Witnesses = new[] { new Witness @@ -132,7 +132,7 @@ public static Transaction GenerateTx(long networkFee, int size, byte[] overrideS }; tx.Attributes.Length.Should().Be(0); - tx.Cosigners.Count.Should().Be(0); + tx.Signers.Length.Should().Be(0); int diff = size - tx.Size; if (diff < 0) throw new ArgumentException(); diff --git a/tests/neo.UnitTests/Ledger/UT_SendersFeeMonitor.cs b/tests/neo.UnitTests/Ledger/UT_SendersFeeMonitor.cs index cd8a5af463..4c9e2fa333 100644 --- a/tests/neo.UnitTests/Ledger/UT_SendersFeeMonitor.cs +++ b/tests/neo.UnitTests/Ledger/UT_SendersFeeMonitor.cs @@ -21,10 +21,10 @@ private Transaction CreateTransactionWithFee(long networkFee, long systemFee) mock.Setup(p => p.VerifyForEachBlock(It.IsAny(), It.IsAny())).Returns(VerifyResult.Succeed); mock.Setup(p => p.Verify(It.IsAny(), It.IsAny())).Returns(VerifyResult.Succeed); mock.Object.Script = randomBytes; - mock.Object.Sender = UInt160.Zero; mock.Object.NetworkFee = networkFee; mock.Object.SystemFee = systemFee; mock.Object.Attributes = Array.Empty(); + mock.Object.Signers = new Signer[] { new Signer() { Account = UInt160.Zero, Scopes = WitnessScope.FeeOnly } }; mock.Object.Witnesses = new[] { new Witness diff --git a/tests/neo.UnitTests/Ledger/UT_TransactionState.cs b/tests/neo.UnitTests/Ledger/UT_TransactionState.cs index 9446b954d2..e30416a136 100644 --- a/tests/neo.UnitTests/Ledger/UT_TransactionState.cs +++ b/tests/neo.UnitTests/Ledger/UT_TransactionState.cs @@ -61,7 +61,7 @@ public void TestDeserialize() [TestMethod] public void TestGetSize() { - ((ISerializable)origin).Size.Should().Be(61); + ((ISerializable)origin).Size.Should().Be(63); } } } diff --git a/tests/neo.UnitTests/Ledger/UT_TrimmedBlock.cs b/tests/neo.UnitTests/Ledger/UT_TrimmedBlock.cs index b74a0b2a9e..c8b0e30fb8 100644 --- a/tests/neo.UnitTests/Ledger/UT_TrimmedBlock.cs +++ b/tests/neo.UnitTests/Ledger/UT_TrimmedBlock.cs @@ -35,7 +35,7 @@ public static TrimmedBlock GetTrimmedBlockWithNoTransaction() public void TestGetIsBlock() { TrimmedBlock block = GetTrimmedBlockWithNoTransaction(); - block.Hashes = new UInt256[] { TestUtils.GetTransaction().Hash }; + block.Hashes = new UInt256[] { TestUtils.GetTransaction(UInt160.Zero).Hash }; block.IsBlock.Should().BeTrue(); } @@ -43,7 +43,7 @@ public void TestGetIsBlock() public void TestGetBlock() { var snapshot = Blockchain.Singleton.GetSnapshot(); - var tx1 = TestUtils.GetTransaction(); + var tx1 = TestUtils.GetTransaction(UInt160.Zero); tx1.Script = new byte[] { 0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01, @@ -53,7 +53,7 @@ public void TestGetBlock() Transaction = tx1, BlockIndex = 1 }; - var tx2 = TestUtils.GetTransaction(); + var tx2 = TestUtils.GetTransaction(UInt160.Zero); tx2.Script = new byte[] { 0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01, @@ -89,7 +89,7 @@ public void TestGetHeader() public void TestGetSize() { TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction(); - tblock.Hashes = new UInt256[] { TestUtils.GetTransaction().Hash }; + tblock.Hashes = new UInt256[] { TestUtils.GetTransaction(UInt160.Zero).Hash }; tblock.Size.Should().Be(146); } @@ -97,7 +97,7 @@ public void TestGetSize() public void TestDeserialize() { TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction(); - tblock.Hashes = new UInt256[] { TestUtils.GetTransaction().Hash }; + tblock.Hashes = new UInt256[] { TestUtils.GetTransaction(UInt160.Zero).Hash }; var newBlock = new TrimmedBlock(); using (MemoryStream ms = new MemoryStream(1024)) using (BinaryWriter writer = new BinaryWriter(ms)) @@ -119,7 +119,7 @@ public void TestDeserialize() public void TestClone() { TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction(); - tblock.Hashes = new UInt256[] { TestUtils.GetTransaction().Hash }; + tblock.Hashes = new UInt256[] { TestUtils.GetTransaction(UInt160.Zero).Hash }; ICloneable cloneable = tblock; var clonedBlock = cloneable.Clone(); clonedBlock.ToJson().ToString().Should().Be(tblock.ToJson().ToString()); @@ -129,7 +129,7 @@ public void TestClone() public void TestFromReplica() { TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction(); - tblock.Hashes = new UInt256[] { TestUtils.GetTransaction().Hash }; + tblock.Hashes = new UInt256[] { TestUtils.GetTransaction(UInt160.Zero).Hash }; ICloneable cloneable = new TrimmedBlock(); cloneable.FromReplica(tblock); ((TrimmedBlock)cloneable).ToJson().ToString().Should().Be(tblock.ToJson().ToString()); diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Block.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Block.cs index 1efd90a3a8..0d5208de5a 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Block.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Block.cs @@ -56,10 +56,10 @@ public void Size_Get_1_Transaction() uut.Transactions = new[] { - TestUtils.GetTransaction() + TestUtils.GetTransaction(UInt160.Zero) }; - uut.Size.Should().Be(165); + uut.Size.Should().Be(167); } [TestMethod] @@ -70,12 +70,12 @@ public void Size_Get_3_Transaction() uut.Transactions = new[] { - TestUtils.GetTransaction(), - TestUtils.GetTransaction(), - TestUtils.GetTransaction() + TestUtils.GetTransaction(UInt160.Zero), + TestUtils.GetTransaction(UInt160.Zero), + TestUtils.GetTransaction(UInt160.Zero) }; - uut.Size.Should().Be(267); + uut.Size.Should().Be(273); } [TestMethod] @@ -84,7 +84,7 @@ public void Serialize() UInt256 val256 = UInt256.Zero; TestUtils.SetupBlockWithValues(uut, val256, out var _, out var _, out var _, out var _, out var _, out var _, 1); - var hex = "000000000000000000000000000000000000000000000000000000000000000000000000bc72014eb4f1fcdd27831b79c42ffa71e1b949086a97c87654a644585dd616f6e913ff854c0000000000000000000000000000000000000000000000000000000100011102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100010000"; + var hex = "000000000000000000000000000000000000000000000000000000000000000000000000add6632f6f3d29cdf94555bb191fb5296683e5446f9937c56bb94c8608023044e913ff854c00000000000000000000000000000000000000000000000000000001000111020000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000001000100010000"; uut.ToArray().ToHexString().Should().Be(hex); } @@ -94,7 +94,7 @@ public void Deserialize() UInt256 val256 = UInt256.Zero; TestUtils.SetupBlockWithValues(new Block(), val256, out var merkRoot, out var val160, out var timestampVal, out var indexVal, out var scriptVal, out var transactionsVal, 1); - var hex = "000000000000000000000000000000000000000000000000000000000000000000000000bc72014eb4f1fcdd27831b79c42ffa71e1b949086a97c87654a644585dd616f6e913ff854c0000000000000000000000000000000000000000000000000000000100011102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100010000"; + var hex = "000000000000000000000000000000000000000000000000000000000000000000000000add6632f6f3d29cdf94555bb191fb5296683e5446f9937c56bb94c8608023044e913ff854c00000000000000000000000000000000000000000000000000000001000111020000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000001000100010000"; using (MemoryStream ms = new MemoryStream(hex.HexToBytes(), false)) using (BinaryReader reader = new BinaryReader(ms)) @@ -199,11 +199,11 @@ public void ToJson() JObject jObj = uut.ToJson(); jObj.Should().NotBeNull(); - jObj["hash"].AsString().Should().Be("0xac84cebc5825cbe78941b301789bc43e8906bb9d86edd80cc94591088a26d9cc"); - jObj["size"].AsNumber().Should().Be(165); + jObj["hash"].AsString().Should().Be("0x9a164d5b9a1ab8745c97dbaaaef8eb30b0d80a00205acdc82daf502bee69bc20"); + jObj["size"].AsNumber().Should().Be(167); jObj["version"].AsNumber().Should().Be(0); jObj["previousblockhash"].AsString().Should().Be("0x0000000000000000000000000000000000000000000000000000000000000000"); - jObj["merkleroot"].AsString().Should().Be("0xf616d65d5844a65476c8976a0849b9e171fa2fc4791b8327ddfcf1b44e0172bc"); + jObj["merkleroot"].AsString().Should().Be("0x44300208864cb96bc537996f44e5836629b51f19bb5545f9cd293d6f2f63d6ad"); jObj["time"].AsNumber().Should().Be(328665601001); jObj["index"].AsNumber().Should().Be(0); jObj["nextconsensus"].AsString().Should().Be("NKuyBkoGdZZSLyPbJEetheRhMjeznFZszf"); @@ -214,8 +214,8 @@ public void ToJson() jObj["tx"].Should().NotBeNull(); JArray txObj = (JArray)jObj["tx"]; - txObj[0]["hash"].AsString().Should().Be("0x5f9b7409b6cf21fb0bf63c3890f62cccfe5fb9c3277ea33935e0a09f4255407c"); - txObj[0]["size"].AsNumber().Should().Be(51); + txObj[0]["hash"].AsString().Should().Be("0x995ce8ff19c30f6b0d6b03e5ed8bd30b08027c92177923782d3a64f573421931"); + txObj[0]["size"].AsNumber().Should().Be(53); txObj[0]["version"].AsNumber().Should().Be(0); ((JArray)txObj[0]["attributes"]).Count.Should().Be(0); txObj[0]["netfee"].AsString().Should().Be("0"); diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Cosigner.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Signers.cs similarity index 66% rename from tests/neo.UnitTests/Network/P2P/Payloads/UT_Cosigner.cs rename to tests/neo.UnitTests/Network/P2P/Payloads/UT_Signers.cs index 22ca14cb82..82799f233f 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Cosigner.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Signers.cs @@ -7,21 +7,21 @@ namespace Neo.UnitTests.Network.P2P.Payloads { [TestClass] - public class UT_Cosigner + public class UT_Signers { [TestMethod] public void Serialize_Deserialize_Global() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.Global, Account = UInt160.Zero }; - var hex = "01000000000000000000000000000000000000000000"; + var hex = "000000000000000000000000000000000000000080"; attr.ToArray().ToHexString().Should().Be(hex); - var copy = hex.HexToBytes().AsSerializable(); + var copy = hex.HexToBytes().AsSerializable(); Assert.AreEqual(attr.Scopes, copy.Scopes); Assert.AreEqual(attr.Account, copy.Account); @@ -30,16 +30,16 @@ public void Serialize_Deserialize_Global() [TestMethod] public void Serialize_Deserialize_CalledByEntry() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CalledByEntry, Account = UInt160.Zero }; - var hex = "01000000000000000000000000000000000000000001"; + var hex = "000000000000000000000000000000000000000001"; attr.ToArray().ToHexString().Should().Be(hex); - var copy = hex.HexToBytes().AsSerializable(); + var copy = hex.HexToBytes().AsSerializable(); Assert.AreEqual(attr.Scopes, copy.Scopes); Assert.AreEqual(attr.Account, copy.Account); @@ -48,17 +48,17 @@ public void Serialize_Deserialize_CalledByEntry() [TestMethod] public void Serialize_Deserialize_CustomContracts() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { UInt160.Zero }, Account = UInt160.Zero }; - var hex = "01000000000000000000000000000000000000000010010000000000000000000000000000000000000000"; + var hex = "000000000000000000000000000000000000000010010000000000000000000000000000000000000000"; attr.ToArray().ToHexString().Should().Be(hex); - var copy = hex.HexToBytes().AsSerializable(); + var copy = hex.HexToBytes().AsSerializable(); Assert.AreEqual(attr.Scopes, copy.Scopes); CollectionAssert.AreEqual(attr.AllowedContracts, copy.AllowedContracts); @@ -68,17 +68,17 @@ public void Serialize_Deserialize_CustomContracts() [TestMethod] public void Serialize_Deserialize_CustomGroups() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CustomGroups, AllowedGroups = new[] { ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1) }, Account = UInt160.Zero }; - var hex = "010000000000000000000000000000000000000000200103b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c"; + var hex = "0000000000000000000000000000000000000000200103b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c"; attr.ToArray().ToHexString().Should().Be(hex); - var copy = hex.HexToBytes().AsSerializable(); + var copy = hex.HexToBytes().AsSerializable(); Assert.AreEqual(attr.Scopes, copy.Scopes); CollectionAssert.AreEqual(attr.AllowedGroups, copy.AllowedGroups); @@ -88,54 +88,54 @@ public void Serialize_Deserialize_CustomGroups() [TestMethod] public void Json_Global() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.Global, Account = UInt160.Zero }; - var json = "{\"type\":\"Cosigner\",\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"Global\"}"; + var json = "{\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"Global\"}"; attr.ToJson().ToString().Should().Be(json); } [TestMethod] public void Json_CalledByEntry() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CalledByEntry, Account = UInt160.Zero }; - var json = "{\"type\":\"Cosigner\",\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CalledByEntry\"}"; + var json = "{\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CalledByEntry\"}"; attr.ToJson().ToString().Should().Be(json); } [TestMethod] public void Json_CustomContracts() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CustomContracts, AllowedContracts = new[] { UInt160.Zero }, Account = UInt160.Zero }; - var json = "{\"type\":\"Cosigner\",\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CustomContracts\",\"allowedcontracts\":[\"0x0000000000000000000000000000000000000000\"]}"; + var json = "{\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CustomContracts\",\"allowedcontracts\":[\"0x0000000000000000000000000000000000000000\"]}"; attr.ToJson().ToString().Should().Be(json); } [TestMethod] public void Json_CustomGroups() { - var attr = new Cosigner() + var attr = new Signer() { Scopes = WitnessScope.CustomGroups, AllowedGroups = new[] { ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1) }, Account = UInt160.Zero }; - var json = "{\"type\":\"Cosigner\",\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CustomGroups\",\"allowedgroups\":[\"03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c\"]}"; + var json = "{\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CustomGroups\",\"allowedgroups\":[\"03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c\"]}"; attr.ToJson().ToString().Should().Be(json); } } diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs index 61ea913867..bf11da269f 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs @@ -64,7 +64,7 @@ public void Gas_Set() public void Size_Get() { uut.Script = TestUtils.GetByteArray(32, 0x42); - uut.Sender = UInt160.Zero; + uut.Signers = Array.Empty(); uut.Attributes = Array.Empty(); uut.Witnesses = new[] { @@ -78,7 +78,7 @@ public void Size_Get() uut.Version.Should().Be(0); uut.Script.Length.Should().Be(32); uut.Script.GetVarSize().Should().Be(33); - uut.Size.Should().Be(82); + uut.Size.Should().Be(63); } [TestMethod] @@ -158,8 +158,8 @@ public void FeeIsMultiSigContract() var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); Assert.AreEqual(2000810, verificationGas); - Assert.AreEqual(367000, sizeGas); - Assert.AreEqual(2367810, tx.NetworkFee); + Assert.AreEqual(347000, sizeGas); + Assert.AreEqual(2347810, tx.NetworkFee); } } @@ -200,7 +200,7 @@ public void FeeIsSignatureContractDetailed() Assert.IsNull(tx.Witnesses); // check pre-computed network fee (already guessing signature sizes) - tx.NetworkFee.Should().Be(1264390); + tx.NetworkFee.Should().Be(1244390L); // ---- // Sign @@ -242,32 +242,32 @@ public void FeeIsSignatureContractDetailed() // ------------------ // check tx_size cost // ------------------ - Assert.AreEqual(264, tx.Size); + Assert.AreEqual(244, tx.Size); // will verify tx size, step by step // Part I - Assert.AreEqual(45, Transaction.HeaderSize); + Assert.AreEqual(25, Transaction.HeaderSize); // Part II - Assert.AreEqual(23, tx.Attributes.GetVarSize()); - Assert.AreEqual(1, tx.Attributes.Length); - Assert.AreEqual(1, tx.Cosigners.Count); - Assert.AreEqual(23, tx.Cosigners.Values.ToArray().GetVarSize()); + Assert.AreEqual(1, tx.Attributes.GetVarSize()); + Assert.AreEqual(0, tx.Attributes.Length); + Assert.AreEqual(1, tx.Signers.Length); // Note that Data size and Usage size are different (because of first byte on GetVarSize()) - Assert.AreEqual(22, tx.Cosigners.Values.First().Size); + Assert.AreEqual(22, tx.Signers.GetVarSize()); // Part III Assert.AreEqual(86, tx.Script.GetVarSize()); // Part IV Assert.AreEqual(110, tx.Witnesses.GetVarSize()); // I + II + III + IV - Assert.AreEqual(45 + 23 + 86 + 110, tx.Size); + Assert.AreEqual(25 + 22 + 1 + 86 + 110, tx.Size); Assert.AreEqual(1000, NativeContract.Policy.GetFeePerByte(snapshot)); var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); - Assert.AreEqual(264000, sizeGas); - // final check on sum: verification_cost + tx_size - Assert.AreEqual(1264390, verificationGas + sizeGas); + // final check: verification_cost and tx_size + Assert.AreEqual(244000, sizeGas); + Assert.AreEqual(1000390, verificationGas); + // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -301,14 +301,14 @@ public void FeeIsSignatureContract_TestScope_Global() using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS - System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; + BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope - var cosigners = new Cosigner[]{ new Cosigner + var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.Global @@ -316,7 +316,7 @@ public void FeeIsSignatureContract_TestScope_Global() // using this... - var tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners); + var tx = wallet.MakeTransaction(script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); @@ -353,7 +353,7 @@ public void FeeIsSignatureContract_TestScope_Global() // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size - Assert.AreEqual(1264390, verificationGas + sizeGas); + Assert.AreEqual(1244390, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -387,14 +387,14 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_GAS() using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS - System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; + BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying global scope - var cosigners = new Cosigner[]{ new Cosigner + var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, @@ -403,7 +403,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_GAS() // using this... - var tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners); + var tx = wallet.MakeTransaction(script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); @@ -440,7 +440,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_GAS() // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size - Assert.AreEqual(1285390, verificationGas + sizeGas); + Assert.AreEqual(1265390, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -481,7 +481,7 @@ public void FeeIsSignatureContract_TestScope_CalledByEntry_Plus_GAS() } // trying CalledByEntry together with GAS - var cosigners = new Cosigner[]{ new Cosigner + var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, // This combination is supposed to actually be an OR, @@ -493,7 +493,7 @@ public void FeeIsSignatureContract_TestScope_CalledByEntry_Plus_GAS() // using this... - var tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners); + var tx = wallet.MakeTransaction(script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); @@ -530,7 +530,7 @@ public void FeeIsSignatureContract_TestScope_CalledByEntry_Plus_GAS() // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size - Assert.AreEqual(1285390, verificationGas + sizeGas); + Assert.AreEqual(1265390, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -569,7 +569,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_FAULT() } // trying global scope - var cosigners = new Cosigner[]{ new Cosigner + var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, @@ -581,7 +581,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_FAULT() // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; - Assert.ThrowsException(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners)); + Assert.ThrowsException(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, signers)); Assert.IsNull(tx); } } @@ -614,14 +614,14 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS - System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; + BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } // trying two custom hashes, for same target account - var cosigners = new Cosigner[]{ new Cosigner + var signers = new Signer[]{ new Signer { Account = acc.ScriptHash, Scopes = WitnessScope.CustomContracts, @@ -630,7 +630,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() // using this... - var tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners); + var tx = wallet.MakeTransaction(script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); @@ -648,9 +648,9 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() // only a single witness should exist tx.Witnesses.Length.Should().Be(1); // no attributes must exist - tx.Attributes.Length.Should().Be(1); + tx.Attributes.Length.Should().Be(0); // one cosigner must exist - tx.Cosigners.Count.Should().Be(1); + tx.Signers.Length.Should().Be(1); // Fast check Assert.IsTrue(tx.VerifyWitnesses(snapshot, tx.NetworkFee)); @@ -672,7 +672,7 @@ public void FeeIsSignatureContract_TestScope_CurrentHash_NEO_GAS() // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size - Assert.AreEqual(1305390, verificationGas + sizeGas); + Assert.AreEqual(1285390, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -704,7 +704,7 @@ public void FeeIsSignatureContract_TestScope_NoScopeFAULT() using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS - System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; + BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); @@ -713,12 +713,19 @@ public void FeeIsSignatureContract_TestScope_NoScopeFAULT() // trying with no scope var attributes = new TransactionAttribute[] { }; + var signers = new Signer[]{ new Signer + { + Account = acc.ScriptHash, + Scopes = (WitnessScope) 0xFF, + AllowedContracts = new[] { NativeContract.NEO.Hash, NativeContract.GAS.Hash } + } }; + // using this... // expects FAULT on execution of 'transfer' Application script // due to lack of a valid witness validation Transaction tx = null; - Assert.ThrowsException(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, attributes)); + Assert.ThrowsException(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, signers, attributes)); Assert.IsNull(tx); } } @@ -731,13 +738,12 @@ public void Transaction_Reverify_Hashes_Length_Unequal_To_Witnesses_Length() { Version = 0x00, Nonce = 0x01020304, - Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, - Attributes = new[] - { - new Cosigner + Attributes = Array.Empty(), + Signers = new[]{ + new Signer { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global @@ -747,7 +753,7 @@ public void Transaction_Reverify_Hashes_Length_Unequal_To_Witnesses_Length() Witnesses = new Witness[0] { } }; UInt160[] hashes = txSimple.GetScriptHashesForVerifying(snapshot); - Assert.AreEqual(2, hashes.Length); + Assert.AreEqual(1, hashes.Length); Assert.AreNotEqual(VerifyResult.Succeed, txSimple.VerifyForEachBlock(snapshot, BigInteger.Zero)); } @@ -759,10 +765,10 @@ public void Transaction_Serialize_Deserialize_Simple() { Version = 0x00, Nonce = 0x01020304, - Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, Attributes = Array.Empty(), Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } @@ -771,15 +777,16 @@ public void Transaction_Serialize_Deserialize_Simple() byte[] sTx = txSimple.ToArray(); // detailed hexstring info (basic checking) - sTx.ToHexString().Should().Be("00" + // version - "04030201" + // nonce - "0000000000000000000000000000000000000000" + // sender - "00e1f50500000000" + // system fee (1 GAS) - "0100000000000000" + // network fee (1 satoshi) - "04030201" + // timelimit - "00" + // no attributes - "0111" + // push1 script - "00"); // no witnesses + sTx.ToHexString().Should().Be( + "00" + // version + "04030201" + // nonce + "00e1f50500000000" + // system fee (1 GAS) + "0100000000000000" + // network fee (1 satoshi) + "04030201" + // timelimit + "01000000000000000000000000000000000000000000" + // empty signer + "00" + // no attributes + "0111" + // push1 script + "00"); // no witnesses // try to deserialize Transaction tx2 = Neo.IO.Helper.AsSerializable(sTx); @@ -791,7 +798,14 @@ public void Transaction_Serialize_Deserialize_Simple() tx2.NetworkFee.Should().Be(0x0000000000000001); tx2.ValidUntilBlock.Should().Be(0x01020304); tx2.Attributes.Should().BeEquivalentTo(new TransactionAttribute[0] { }); - tx2.Cosigners.Should().BeEquivalentTo(new Cosigner[0] { }); + tx2.Signers.Should().BeEquivalentTo(new Signer[] { + new Signer() + { + Account = UInt160.Zero, + AllowedContracts = Array.Empty(), + AllowedGroups = Array.Empty() } + } + ); tx2.Script.Should().BeEquivalentTo(new byte[] { (byte)OpCode.PUSH1 }); tx2.Witnesses.Should().BeEquivalentTo(new Witness[0] { }); } @@ -805,18 +819,18 @@ public void Transaction_Serialize_Deserialize_DistinctCosigners() { Version = 0x00, Nonce = 0x01020304, - Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, - Attributes = new[] + Attributes = Array.Empty(), + Signers = new Signer[] { - new Cosigner + new Signer() { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), Scopes = WitnessScope.Global }, - new Cosigner + new Signer() { Account = UInt160.Parse("0x0001020304050607080900010203040506070809"), // same account as above Scopes = WitnessScope.CalledByEntry // different scope, but still, same account (cannot do that) @@ -829,7 +843,7 @@ public void Transaction_Serialize_Deserialize_DistinctCosigners() byte[] sTx = txDoubleCosigners.ToArray(); // no need for detailed hexstring here (see basic tests for it) - sTx.ToHexString().Should().Be("0004030201000000000000000000000000000000000000000000e1f50500000000010000000000000004030201020109080706050403020100090807060504030201000001090807060504030201000908070605040302010001011100"); + sTx.ToHexString().Should().Be("000403020100e1f505000000000100000000000000040302010209080706050403020100090807060504030201008009080706050403020100090807060504030201000100011100"); // back to transaction (should fail, due to non-distinct cosigners) Transaction tx2 = null; @@ -850,15 +864,16 @@ public void Transaction_Serialize_Deserialize_MaxSizeCosigners() // -------------------------------------- // this should pass (respecting max size) - var cosigners1 = new Cosigner[maxCosigners]; + var cosigners1 = new Signer[maxCosigners]; for (int i = 0; i < cosigners1.Length; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); - cosigners1[i] = new Cosigner + cosigners1[i] = new Signer { - Account = UInt160.Parse(hex) + Account = UInt160.Parse(hex), + Scopes = WitnessScope.CalledByEntry }; } @@ -866,11 +881,11 @@ public void Transaction_Serialize_Deserialize_MaxSizeCosigners() { Version = 0x00, Nonce = 0x01020304, - Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, - Attributes = cosigners1, // max + 1 (should fail) + Attributes = Array.Empty(), + Signers = cosigners1, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; @@ -884,13 +899,13 @@ public void Transaction_Serialize_Deserialize_MaxSizeCosigners() // ---------------------------- // this should fail (max + 1) - var cosigners = new Cosigner[maxCosigners + 1]; + var cosigners = new Signer[maxCosigners + 1]; for (var i = 0; i < maxCosigners + 1; i++) { string hex = i.ToString("X4"); while (hex.Length < 40) hex = hex.Insert(0, "0"); - cosigners[i] = new Cosigner + cosigners[i] = new Signer { Account = UInt160.Parse(hex) }; @@ -900,11 +915,11 @@ public void Transaction_Serialize_Deserialize_MaxSizeCosigners() { Version = 0x00, Nonce = 0x01020304, - Sender = UInt160.Zero, SystemFee = (long)BigInteger.Pow(10, 8), // 1 GAS NetworkFee = 0x0000000000000001, ValidUntilBlock = 0x01020304, - Attributes = cosigners, // max + 1 (should fail) + Attributes = Array.Empty(), + Signers = cosigners, // max + 1 (should fail) Script = new byte[] { (byte)OpCode.PUSH1 }, Witnesses = new Witness[0] { } }; @@ -920,12 +935,12 @@ public void Transaction_Serialize_Deserialize_MaxSizeCosigners() } [TestMethod] - public void FeeIsSignatureContract_TestScope_Global_Default() + public void FeeIsSignatureContract_TestScope_FeeOnly_Default() { // Global is supposed to be default - Cosigner cosigner = new Cosigner(); - cosigner.Scopes.Should().Be(WitnessScope.Global); + Signer cosigner = new Signer(); + cosigner.Scopes.Should().Be(WitnessScope.FeeOnly); var wallet = TestUtils.GenerateTestWallet(); var snapshot = Blockchain.Singleton.GetSnapshot(); @@ -952,21 +967,25 @@ public void FeeIsSignatureContract_TestScope_Global_Default() using (ScriptBuilder sb = new ScriptBuilder()) { // self-transfer of 1e-8 GAS - System.Numerics.BigInteger value = (new BigDecimal(1, 8)).Value; + BigInteger value = (new BigDecimal(1, 8)).Value; sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value); sb.Emit(OpCode.ASSERT); script = sb.ToArray(); } - // default to global scope - var cosigners = new Cosigner[]{ new Cosigner + // try to use fee only inside the smart contract + var signers = new Signer[]{ new Signer { - Account = acc.ScriptHash + Account = acc.ScriptHash, + Scopes = WitnessScope.FeeOnly } }; - // using this... + Assert.ThrowsException(() => wallet.MakeTransaction(script, acc.ScriptHash, signers)); + + // change to global scope + signers[0].Scopes = WitnessScope.Global; - var tx = wallet.MakeTransaction(script, acc.ScriptHash, cosigners); + var tx = wallet.MakeTransaction(script, acc.ScriptHash, signers); Assert.IsNotNull(tx); Assert.IsNull(tx.Witnesses); @@ -1003,7 +1022,7 @@ public void FeeIsSignatureContract_TestScope_Global_Default() // get sizeGas var sizeGas = tx.Size * NativeContract.Policy.GetFeePerByte(snapshot); // final check on sum: verification_cost + tx_size - Assert.AreEqual(1264390, verificationGas + sizeGas); + Assert.AreEqual(1244390, verificationGas + sizeGas); // final assert Assert.AreEqual(tx.NetworkFee, verificationGas + sizeGas); } @@ -1013,8 +1032,8 @@ public void FeeIsSignatureContract_TestScope_Global_Default() public void ToJson() { uut.Script = TestUtils.GetByteArray(32, 0x42); - uut.Sender = UInt160.Zero; uut.SystemFee = 4200000000; + uut.Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }; uut.Attributes = Array.Empty(); uut.Witnesses = new[] { @@ -1027,8 +1046,8 @@ public void ToJson() JObject jObj = uut.ToJson(); jObj.Should().NotBeNull(); - jObj["hash"].AsString().Should().Be("0xfe08a23db645733a95914622ead5e738b03918680e927e00928116395e571758"); - jObj["size"].AsNumber().Should().Be(82); + jObj["hash"].AsString().Should().Be("0xe17382d26702bde77b00a9f23ea156b77c418764cbc45b2692088b5fde0336e3"); + jObj["size"].AsNumber().Should().Be(84); jObj["version"].AsNumber().Should().Be(0); ((JArray)jObj["attributes"]).Count.Should().Be(0); jObj["netfee"].AsString().Should().Be("0"); diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Witness.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Witness.cs index a6cc76682f..ff47beef29 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Witness.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Witness.cs @@ -54,8 +54,12 @@ private Witness PrepareDummyWitness(int maxAccounts) var data = new ContractParametersContext(new Transaction() { - Sender = multiSignContract.ScriptHash, Attributes = Array.Empty(), + Signers = new[] {new Signer() + { + Account = multiSignContract.ScriptHash, + Scopes = WitnessScope.CalledByEntry + }}, NetworkFee = 0, Nonce = 0, Script = new byte[0], diff --git a/tests/neo.UnitTests/SmartContract/UT_ContractParameterContext.cs b/tests/neo.UnitTests/SmartContract/UT_ContractParameterContext.cs index 23e474e4b8..b96c06ae3c 100644 --- a/tests/neo.UnitTests/SmartContract/UT_ContractParameterContext.cs +++ b/tests/neo.UnitTests/SmartContract/UT_ContractParameterContext.cs @@ -33,8 +33,7 @@ public static void ClassSetUp(TestContext context) [TestMethod] public void TestGetComplete() { - Transaction tx = TestUtils.GetTransaction(); - tx.Sender = UInt160.Parse("0x1bd5c777ec35768892bd3daab60fb7a1cb905066"); + Transaction tx = TestUtils.GetTransaction(UInt160.Parse("0x1bd5c777ec35768892bd3daab60fb7a1cb905066")); var context = new ContractParametersContext(tx); context.Completed.Should().BeFalse(); } @@ -42,18 +41,17 @@ public void TestGetComplete() [TestMethod] public void TestToString() { - Transaction tx = TestUtils.GetTransaction(); - tx.Sender = UInt160.Parse("0x1bd5c777ec35768892bd3daab60fb7a1cb905066"); + Transaction tx = TestUtils.GetTransaction(UInt160.Parse("0x1bd5c777ec35768892bd3daab60fb7a1cb905066")); var context = new ContractParametersContext(tx); context.Add(contract, 0, new byte[] { 0x01 }); string str = context.ToString(); - str.Should().Be(@"{""type"":""Neo.Network.P2P.Payloads.Transaction"",""hex"":""AAAAAABmUJDLobcPtqo9vZKIdjXsd8fVGwAAAAAAAAAAAAAAAAAAAAAAAAAAAAEA"",""items"":{}}"); + str.Should().Be(@"{""type"":""Neo.Network.P2P.Payloads.Transaction"",""hex"":""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFmUJDLobcPtqo9vZKIdjXsd8fVGwEAAQA="",""items"":{}}"); } [TestMethod] public void TestParse() { - var ret = ContractParametersContext.Parse("{\"type\":\"Neo.Network.P2P.Payloads.Transaction\",\"hex\":\"AAAAAABmUJDLobcPtqo9vZKIdjXsd8fVGwAAAAAAAAAAAAAAAAAAAAAAAAAAAAEA\",\"items\":{\"0xbecaad15c0ea585211faf99738a4354014f177f2\":{\"script\":\"IQJv8DuUkkHOHa3UNRnmlg4KhbQaaaBcMoEDqivOFZTKFmh0dHaq\",\"parameters\":[{\"type\":\"Signature\",\"value\":\"AQ==\"}]}}}"); + var ret = ContractParametersContext.Parse("{\"type\":\"Neo.Network.P2P.Payloads.Transaction\",\"hex\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFmUJDLobcPtqo9vZKIdjXsd8fVGwEAAQA=\",\"items\":{\"0xbecaad15c0ea585211faf99738a4354014f177f2\":{\"script\":\"IQJv8DuUkkHOHa3UNRnmlg4KhbQaaaBcMoEDqivOFZTKFmh0dHaq\",\"parameters\":[{\"type\":\"Signature\",\"value\":\"AQ==\"}]}}}"); ret.ScriptHashes[0].ToString().Should().Be("0x1bd5c777ec35768892bd3daab60fb7a1cb905066"); ((Transaction)ret.Verifiable).Script.ToHexString().Should().Be(new byte[1].ToHexString()); } @@ -68,11 +66,11 @@ public void TestFromJson() [TestMethod] public void TestAdd() { - Transaction tx = TestUtils.GetTransaction(); + Transaction tx = TestUtils.GetTransaction(UInt160.Zero); var context1 = new ContractParametersContext(tx); context1.Add(contract, 0, new byte[] { 0x01 }).Should().BeFalse(); - tx.Sender = UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0"); + tx = TestUtils.GetTransaction(UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0")); var context2 = new ContractParametersContext(tx); context2.Add(contract, 0, new byte[] { 0x01 }).Should().BeTrue(); //test repeatlly createItem @@ -82,8 +80,7 @@ public void TestAdd() [TestMethod] public void TestGetParameter() { - Transaction tx = TestUtils.GetTransaction(); - tx.Sender = UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0"); + Transaction tx = TestUtils.GetTransaction(UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0")); var context = new ContractParametersContext(tx); context.GetParameter(tx.Sender, 0).Should().BeNull(); @@ -95,8 +92,7 @@ public void TestGetParameter() [TestMethod] public void TestGetWitnesses() { - Transaction tx = TestUtils.GetTransaction(); - tx.Sender = UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0"); + Transaction tx = TestUtils.GetTransaction(UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0")); var context = new ContractParametersContext(tx); context.Add(contract, 0, new byte[] { 0x01 }); Witness[] witnesses = context.GetWitnesses(); @@ -108,9 +104,8 @@ public void TestGetWitnesses() [TestMethod] public void TestAddSignature() { - Transaction tx = TestUtils.GetTransaction(); var singleSender = UInt160.Parse("0x282646ee0afa5508bb999318f35074b84a17c9f0"); - tx.Sender = singleSender; + Transaction tx = TestUtils.GetTransaction(singleSender); //singleSign @@ -140,16 +135,16 @@ public void TestAddSignature() key2.PublicKey }); var multiSender = UInt160.Parse("0x3593816cc1085a6328fea2b899c24d78cd0ba372"); - tx.Sender = multiSender; + tx = TestUtils.GetTransaction(multiSender); context = new ContractParametersContext(tx); context.AddSignature(multiSignContract, key.PublicKey, new byte[] { 0x01 }).Should().BeTrue(); context.AddSignature(multiSignContract, key2.PublicKey, new byte[] { 0x01 }).Should().BeTrue(); - tx.Sender = singleSender; + tx = TestUtils.GetTransaction(singleSender); context = new ContractParametersContext(tx); context.AddSignature(multiSignContract, key.PublicKey, new byte[] { 0x01 }).Should().BeFalse(); - tx.Sender = multiSender; + tx = TestUtils.GetTransaction(multiSender); context = new ContractParametersContext(tx); byte[] privateKey3 = new byte[] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, diff --git a/tests/neo.UnitTests/SmartContract/UT_InteropService.cs b/tests/neo.UnitTests/SmartContract/UT_InteropService.cs index 670c2530a5..174aace8f1 100644 --- a/tests/neo.UnitTests/SmartContract/UT_InteropService.cs +++ b/tests/neo.UnitTests/SmartContract/UT_InteropService.cs @@ -250,7 +250,7 @@ public void TestRuntime_CheckWitness() ECPoint pubkey = keyPair.PublicKey; var engine = GetEngine(true); - ((Transaction)engine.ScriptContainer).Sender = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash(); + ((Transaction)engine.ScriptContainer).Signers[0].Account = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash(); engine.CheckWitness(pubkey.EncodePoint(true)).Should().BeFalse(); engine.CheckWitness(((Transaction)engine.ScriptContainer).Sender.ToArray()).Should().BeFalse(); @@ -698,7 +698,7 @@ public static void LogEvent(object sender, LogEventArgs args) private static ApplicationEngine GetEngine(bool hasContainer = false, bool hasSnapshot = false, bool addScript = true) { - var tx = TestUtils.GetTransaction(); + var tx = TestUtils.GetTransaction(UInt160.Zero); var snapshot = Blockchain.Singleton.GetSnapshot(); ApplicationEngine engine; if (hasContainer && hasSnapshot) diff --git a/tests/neo.UnitTests/SmartContract/UT_Syscalls.cs b/tests/neo.UnitTests/SmartContract/UT_Syscalls.cs index 192e7292ff..b32e808f4d 100644 --- a/tests/neo.UnitTests/SmartContract/UT_Syscalls.cs +++ b/tests/neo.UnitTests/SmartContract/UT_Syscalls.cs @@ -26,13 +26,13 @@ public void System_Blockchain_GetBlock() { Script = new byte[] { 0x01 }, Attributes = Array.Empty(), + Signers = Array.Empty(), NetworkFee = 0x02, SystemFee = 0x03, Nonce = 0x04, ValidUntilBlock = 0x05, Version = 0x06, Witnesses = new Witness[] { new Witness() { VerificationScript = new byte[] { 0x07 } } }, - Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), }; var block = new Block() @@ -239,6 +239,7 @@ public void System_ExecutionEngine_GetScriptContainer() var tx = new Transaction() { Script = new byte[] { 0x01 }, + Signers = new Signer[] { new Signer() { Account = UInt160.Zero, Scopes = WitnessScope.FeeOnly } }, Attributes = Array.Empty(), NetworkFee = 0x02, SystemFee = 0x03, @@ -246,7 +247,6 @@ public void System_ExecutionEngine_GetScriptContainer() ValidUntilBlock = 0x05, Version = 0x06, Witnesses = new Witness[] { new Witness() { VerificationScript = new byte[] { 0x07 } } }, - Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), }; engine = new ApplicationEngine(TriggerType.Application, tx, snapshot, 0, true); diff --git a/tests/neo.UnitTests/TestUtils.cs b/tests/neo.UnitTests/TestUtils.cs index 3edc590dae..a97869c8b5 100644 --- a/tests/neo.UnitTests/TestUtils.cs +++ b/tests/neo.UnitTests/TestUtils.cs @@ -81,7 +81,7 @@ public static NEP6Wallet GenerateTestWallet() { JObject wallet = new JObject(); wallet["name"] = "noname"; - wallet["version"] = new System.Version("3.0").ToString(); + wallet["version"] = new Version("3.0").ToString(); wallet["scrypt"] = new ScryptParameters(0, 0, 0).ToJson(); wallet["accounts"] = new JArray(); wallet["extra"] = null; @@ -89,13 +89,17 @@ public static NEP6Wallet GenerateTestWallet() return new NEP6Wallet(wallet); } - public static Transaction GetTransaction() + public static Transaction GetTransaction(UInt160 sender) { return new Transaction { Script = new byte[1], - Sender = UInt160.Zero, Attributes = Array.Empty(), + Signers = new[]{ new Signer() + { + Account = sender, + Scopes = WitnessScope.CalledByEntry + } }, Witnesses = new Witness[]{ new Witness { InvocationScript = new byte[0], @@ -155,7 +159,7 @@ public static void SetupBlockWithValues(Block block, UInt256 val256, out UInt256 { for (int i = 0; i < numberOfTransactions; i++) { - transactionsVal[i] = TestUtils.GetTransaction(); + transactionsVal[i] = TestUtils.GetTransaction(UInt160.Zero); } } @@ -190,8 +194,8 @@ public static Transaction CreateRandomHashTransaction() return new Transaction { Script = randomBytes, - Sender = UInt160.Zero, Attributes = Array.Empty(), + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, Witnesses = new[] { new Witness diff --git a/tests/neo.UnitTests/Wallets/UT_Wallet.cs b/tests/neo.UnitTests/Wallets/UT_Wallet.cs index e63145ff5d..7f4ad69332 100644 --- a/tests/neo.UnitTests/Wallets/UT_Wallet.cs +++ b/tests/neo.UnitTests/Wallets/UT_Wallet.cs @@ -367,8 +367,8 @@ public void TestMakeTransaction1() public void TestMakeTransaction2() { MyWallet wallet = new MyWallet(); - Action action = () => wallet.MakeTransaction(new byte[] { }, UInt160.Zero, new TransactionAttribute[] { }); - action.Should().Throw(); + Action action = () => wallet.MakeTransaction(new byte[] { }, null, null, Array.Empty()); + action.Should().Throw(); Contract contract = Contract.Create(new ContractParameterType[] { ContractParameterType.Boolean }, new byte[] { 1 }); WalletAccount account = wallet.CreateAccount(contract, glkey.PrivateKey); @@ -381,10 +381,15 @@ public void TestMakeTransaction2() entry.GetInteroperable().Balance = 1000000 * NativeContract.GAS.Factor; snapshot.Commit(); - var tx = wallet.MakeTransaction(new byte[] { }, account.ScriptHash, new TransactionAttribute[] { }); + var tx = wallet.MakeTransaction(new byte[] { }, account.ScriptHash, new[]{ new Signer() + { + Account = account.ScriptHash, + Scopes = WitnessScope.CalledByEntry + }}, new TransactionAttribute[] { }); + tx.Should().NotBeNull(); - tx = wallet.MakeTransaction(new byte[] { }, null, new TransactionAttribute[] { }); + tx = wallet.MakeTransaction(new byte[] { }, null, null, Array.Empty()); tx.Should().NotBeNull(); entry = snapshot.Storages.GetAndChange(key, () => new StorageItem(new AccountState()));