From 11cfa30c0f2ddaec3a64a2babe6f804941273728 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 15:55:15 -0700 Subject: [PATCH 01/21] compiling, some stuff stubbed out --- src/RpcClient/ContractClient.cs | 34 +- src/RpcClient/Nep5API.cs | 92 +++--- src/RpcClient/PolicyAPI.cs | 23 +- src/RpcClient/RpcClient.cs | 263 ++++++++------- src/RpcClient/TransactionManager.cs | 20 +- src/RpcClient/WalletAPI.cs | 43 +-- .../UT_ContractClient.cs | 5 +- tests/Neo.Network.RPC.Tests/UT_Nep5API.cs | 25 +- tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs | 17 +- tests/Neo.Network.RPC.Tests/UT_RpcClient.cs | 168 +++++----- .../UT_TransactionManager.cs | 309 +++++++++--------- tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 66 ++-- 12 files changed, 563 insertions(+), 502 deletions(-) diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index 0aa3aff3b..8f59943fc 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading.Tasks; using Neo.Network.P2P.Payloads; using Neo.Network.RPC.Models; using Neo.SmartContract; @@ -30,7 +32,7 @@ public ContractClient(RpcClient rpc) /// contract operation /// operation arguments /// - public RpcInvokeResult TestInvoke(UInt160 scriptHash, string operation, params object[] args) + public Task TestInvoke(UInt160 scriptHash, string operation, params object[] args) { byte[] script = scriptHash.MakeScript(operation, args); return rpcClient.InvokeScript(script); @@ -45,22 +47,24 @@ public RpcInvokeResult TestInvoke(UInt160 scriptHash, string operation, params o /// public Transaction CreateDeployContractTx(byte[] contractScript, ContractManifest manifest, KeyPair key) { - byte[] script; - using (ScriptBuilder sb = new ScriptBuilder()) - { - sb.EmitSysCall(ApplicationEngine.System_Contract_Create, contractScript, manifest.ToString()); - script = sb.ToArray(); - } - UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); - Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + throw new NotImplementedException(); - Transaction tx = new TransactionManager(rpcClient) - .MakeTransaction(script, signers) - .AddSignature(key) - .Sign() - .Tx; + // byte[] script; + // using (ScriptBuilder sb = new ScriptBuilder()) + // { + // sb.EmitSysCall(ApplicationEngine.System_Contract_Create, contractScript, manifest.ToString()); + // script = sb.ToArray(); + // } + // UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); + // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - return tx; + // Transaction tx = new TransactionManager(rpcClient) + // .MakeTransaction(script, signers) + // .AddSignature(key) + // .Sign() + // .Tx; + + // return tx; } } } diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index c700d5c68..bc77ae6bc 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -7,6 +7,7 @@ using System; using System.Linq; using System.Numerics; +using System.Threading.Tasks; using static Neo.Helper; namespace Neo.Network.RPC @@ -28,9 +29,10 @@ public Nep5API(RpcClient rpcClient) : base(rpcClient) { } /// contract script hash /// account script hash /// - public BigInteger BalanceOf(UInt160 scriptHash, UInt160 account) + public async Task BalanceOf(UInt160 scriptHash, UInt160 account) { - BigInteger balance = TestInvoke(scriptHash, "balanceOf", account).Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "balanceOf", account).ConfigureAwait(false); + BigInteger balance = result.Stack.Single().GetInteger(); return balance; } @@ -39,9 +41,10 @@ public BigInteger BalanceOf(UInt160 scriptHash, UInt160 account) /// /// contract script hash /// - public string Name(UInt160 scriptHash) + public async Task Name(UInt160 scriptHash) { - return TestInvoke(scriptHash, "name").Stack.Single().GetString(); + var result = await TestInvoke(scriptHash, "name").ConfigureAwait(false); + return result.Stack.Single().GetString(); } /// @@ -49,9 +52,10 @@ public string Name(UInt160 scriptHash) /// /// contract script hash /// - public string Symbol(UInt160 scriptHash) + public async Task Symbol(UInt160 scriptHash) { - return TestInvoke(scriptHash, "symbol").Stack.Single().GetString(); + var result = await TestInvoke(scriptHash, "symbol").ConfigureAwait(false); + return result.Stack.Single().GetString(); } /// @@ -59,9 +63,10 @@ public string Symbol(UInt160 scriptHash) /// /// contract script hash /// - public byte Decimals(UInt160 scriptHash) + public async Task Decimals(UInt160 scriptHash) { - return (byte)TestInvoke(scriptHash, "decimals").Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "decimals").ConfigureAwait(false); + return (byte)result.Stack.Single().GetInteger(); } /// @@ -69,9 +74,10 @@ public byte Decimals(UInt160 scriptHash) /// /// contract script hash /// - public BigInteger TotalSupply(UInt160 scriptHash) + public async Task TotalSupply(UInt160 scriptHash) { - return TestInvoke(scriptHash, "totalSupply").Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "totalSupply").ConfigureAwait(false); + return result.Stack.Single().GetInteger(); } /// @@ -79,21 +85,22 @@ public BigInteger TotalSupply(UInt160 scriptHash) /// /// contract script hash /// - public RpcNep5TokenInfo GetTokenInfo(UInt160 scriptHash) + public async Task GetTokenInfo(UInt160 scriptHash) { byte[] script = Concat(scriptHash.MakeScript("name"), scriptHash.MakeScript("symbol"), scriptHash.MakeScript("decimals"), scriptHash.MakeScript("totalSupply")); - var result = rpcClient.InvokeScript(script).Stack; + var result = await TestInvoke(scriptHash, "totalSupply").ConfigureAwait(false); + var stack = result.Stack; return new RpcNep5TokenInfo { - Name = result[0].GetString(), - Symbol = result[1].GetString(), - Decimals = (byte)result[2].GetInteger(), - TotalSupply = result[3].GetInteger() + Name = stack[0].GetString(), + Symbol = stack[1].GetString(), + Decimals = (byte)stack[2].GetInteger(), + TotalSupply = stack[3].GetInteger() }; } @@ -107,17 +114,18 @@ public RpcNep5TokenInfo GetTokenInfo(UInt160 scriptHash) /// public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount) { - var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); - Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + throw new NotImplementedException(); + // var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); + // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - Transaction tx = new TransactionManager(rpcClient) - .MakeTransaction(script, signers) - .AddSignature(fromKey) - .Sign() - .Tx; + // byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); + // Transaction tx = new TransactionManager(rpcClient) + // .MakeTransaction(script, signers) + // .AddSignature(fromKey) + // .Sign() + // .Tx; - return tx; + // return tx; } /// @@ -132,19 +140,27 @@ public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 /// public Transaction CreateTransferTx(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount) { - if (m > fromKeys.Length) - throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); - var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash; - Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - - byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - Transaction tx = new TransactionManager(rpcClient) - .MakeTransaction(script, signers) - .AddMultiSig(fromKeys, m, pubKeys) - .Sign() - .Tx; - - return tx; + throw new NotImplementedException(); + + // if (m > fromKeys.Length) + // throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); + // var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash; + // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + + // byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); + // var tm = new TransactionManager(rpcClient); + // Transaction tx = new TransactionManager(rpcClient) + // .MakeTransaction(script, signers) + // .AddMultiSig(fromKeys, m, pubKeys) + // .Sign() + // .Tx; + + + // var tx = await rpcClient.MakeTransaction(script, signers) + // .AddMultiSig(fromKeys, m, pubKeys) + // .SignAsync(); + + // return tx; } } } diff --git a/src/RpcClient/PolicyAPI.cs b/src/RpcClient/PolicyAPI.cs index 073b105b3..8eb004bc0 100644 --- a/src/RpcClient/PolicyAPI.cs +++ b/src/RpcClient/PolicyAPI.cs @@ -1,6 +1,7 @@ using Neo.SmartContract.Native; using Neo.VM; using System.Linq; +using System.Threading.Tasks; namespace Neo.Network.RPC { @@ -21,37 +22,41 @@ public PolicyAPI(RpcClient rpcClient) : base(rpcClient) { } /// Get Max Transactions Count Per Block /// /// - public uint GetMaxTransactionsPerBlock() + public async Task GetMaxTransactionsPerBlock() { - return (uint)TestInvoke(scriptHash, "getMaxTransactionsPerBlock").Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "getMaxTransactionsPerBlock").ConfigureAwait(false); + return (uint)result.Stack.Single().GetInteger(); } /// /// Get Max Block Size /// /// - public uint GetMaxBlockSize() + public async Task GetMaxBlockSize() { - return (uint)TestInvoke(scriptHash, "getMaxBlockSize").Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "getMaxBlockSize").ConfigureAwait(false); + return (uint)result.Stack.Single().GetInteger(); } /// /// Get Network Fee Per Byte /// /// - public long GetFeePerByte() + public async Task GetFeePerByte() { - return (long)TestInvoke(scriptHash, "getFeePerByte").Stack.Single().GetInteger(); + var result = await TestInvoke(scriptHash, "getFeePerByte").ConfigureAwait(false); + return (long)result.Stack.Single().GetInteger(); } /// /// Get Ploicy Blocked Accounts /// /// - public UInt160[] GetBlockedAccounts() + public async Task GetBlockedAccounts() { - var result = (VM.Types.Array)TestInvoke(scriptHash, "getBlockedAccounts").Stack.Single(); - return result.Select(p => new UInt160(p.GetSpan().ToArray())).ToArray(); + var result = await TestInvoke(scriptHash, "getBlockedAccounts").ConfigureAwait(false); + var array = (VM.Types.Array)result.Stack.Single(); + return array.Select(p => new UInt160(p.GetSpan().ToArray())).ToArray(); } } } diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 6448178e2..b4c0009b9 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -20,11 +20,13 @@ namespace Neo.Network.RPC /// public class RpcClient : IDisposable { - private HttpClient httpClient; + private readonly HttpClient httpClient; + private readonly string baseAddress; public RpcClient(string url, string rpcUser = default, string rpcPass = default) { - httpClient = new HttpClient() { BaseAddress = new Uri(url) }; + httpClient = new HttpClient(); + baseAddress = url; if (!string.IsNullOrEmpty(rpcUser) && !string.IsNullOrEmpty(rpcPass)) { string token = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{rpcUser}:{rpcPass}")); @@ -32,9 +34,10 @@ public RpcClient(string url, string rpcUser = default, string rpcPass = default) } } - public RpcClient(HttpClient client) + public RpcClient(HttpClient client, string url) { httpClient = client; + baseAddress = url; } #region IDisposable Support @@ -46,10 +49,9 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - httpClient?.Dispose(); + httpClient.Dispose(); } - httpClient = null; disposedValue = true; } } @@ -62,8 +64,10 @@ public void Dispose() public async Task SendAsync(RpcRequest request) { + if (disposedValue) throw new ObjectDisposedException(nameof(RpcClient)); + var requestJson = request.ToJson().ToString(); - using var result = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(requestJson, Encoding.UTF8)); + using var result = await httpClient.PostAsync(baseAddress, new StringContent(requestJson, Encoding.UTF8)).ConfigureAwait(false); var content = await result.Content.ReadAsStringAsync(); var response = RpcResponse.FromJson(JObject.Parse(content)); response.RawResponse = content; @@ -76,19 +80,7 @@ public async Task SendAsync(RpcRequest request) return response; } - public RpcResponse Send(RpcRequest request) - { - try - { - return SendAsync(request).Result; - } - catch (AggregateException ex) - { - throw ex.GetBaseException(); - } - } - - public virtual JObject RpcSend(string method, params JObject[] paraArgs) + public async Task RpcSendAsync(string method, params JObject[] paraArgs) { var request = new RpcRequest { @@ -97,7 +89,9 @@ public virtual JObject RpcSend(string method, params JObject[] paraArgs) Method = method, Params = paraArgs }; - return Send(request).Result; + + var response = await SendAsync(request).ConfigureAwait(false); + return response.Result; } #region Blockchain @@ -105,82 +99,84 @@ public virtual JObject RpcSend(string method, params JObject[] paraArgs) /// /// Returns the hash of the tallest block in the main chain. /// - public string GetBestBlockHash() + public async Task GetBestBlockHash() { - return RpcSend("getbestblockhash").AsString(); + var result = await RpcSendAsync("getbestblockhash").ConfigureAwait(false); + return result.AsString(); } /// /// Returns the hash of the tallest block in the main chain. /// The serialized information of the block is returned, represented by a hexadecimal string. /// - public string GetBlockHex(string hashOrIndex) + public async Task GetBlockHex(string hashOrIndex) { - if (int.TryParse(hashOrIndex, out int index)) - { - return RpcSend("getblock", index).AsString(); - } - return RpcSend("getblock", hashOrIndex).AsString(); + var result = int.TryParse(hashOrIndex, out int index) + ? await RpcSendAsync("getblock", index).ConfigureAwait(false) + : await RpcSendAsync("getblock", hashOrIndex).ConfigureAwait(false); + return result.AsString(); } /// /// Returns the hash of the tallest block in the main chain. /// - public RpcBlock GetBlock(string hashOrIndex) + public async Task GetBlock(string hashOrIndex) { - if (int.TryParse(hashOrIndex, out int index)) - { - return RpcBlock.FromJson(RpcSend("getblock", index, true)); - } - return RpcBlock.FromJson(RpcSend("getblock", hashOrIndex, true)); + var result = int.TryParse(hashOrIndex, out int index) + ? await RpcSendAsync("getblock", index).ConfigureAwait(false) + : await RpcSendAsync("getblock", hashOrIndex).ConfigureAwait(false); + + return RpcBlock.FromJson(result); } /// /// Gets the number of blocks in the main chain. /// - public uint GetBlockCount() + public async Task GetBlockCount() { - return (uint)RpcSend("getblockcount").AsNumber(); + var result = await RpcSendAsync("getblockcount").ConfigureAwait(false); + return (uint)result.AsNumber(); } /// /// Returns the hash value of the corresponding block, based on the specified index. /// - public string GetBlockHash(int index) + public async Task GetBlockHash(int index) { - return RpcSend("getblockhash", index).AsString(); + var result = await RpcSendAsync("getblockhash").ConfigureAwait(false); + return result.AsString(); } /// /// Returns the corresponding block header information according to the specified script hash. /// - public string GetBlockHeaderHex(string hashOrIndex) + public async Task GetBlockHeaderHex(string hashOrIndex) { - if (int.TryParse(hashOrIndex, out int index)) - { - return RpcSend("getblockheader", index).AsString(); - } - return RpcSend("getblockheader", hashOrIndex).AsString(); + var result = int.TryParse(hashOrIndex, out int index) + ? await RpcSendAsync("getblockheader", index).ConfigureAwait(false) + : await RpcSendAsync("getblockheader", hashOrIndex).ConfigureAwait(false); + return result.AsString(); } /// /// Returns the corresponding block header information according to the specified script hash. /// - public RpcBlockHeader GetBlockHeader(string hashOrIndex) + public async Task GetBlockHeader(string hashOrIndex) { - if (int.TryParse(hashOrIndex, out int index)) - { - return RpcBlockHeader.FromJson(RpcSend("getblockheader", index, true)); - } - return RpcBlockHeader.FromJson(RpcSend("getblockheader", hashOrIndex, true)); + var result = int.TryParse(hashOrIndex, out int index) + ? await RpcSendAsync("getblockheader", index).ConfigureAwait(false) + : await RpcSendAsync("getblockheader", hashOrIndex).ConfigureAwait(false); + + return RpcBlockHeader.FromJson(result); } /// /// Queries contract information, according to the contract script hash. /// - public ContractState GetContractState(string hash) + public async Task GetContractState(string hash) { - return ContractStateFromJson(RpcSend("getcontractstate", hash)); + var result = await RpcSendAsync("getcontractstate", hash).ConfigureAwait(false); + return ContractStateFromJson(result); } public static ContractState ContractStateFromJson(JObject json) @@ -196,64 +192,68 @@ public static ContractState ContractStateFromJson(JObject json) /// /// Obtains the list of unconfirmed transactions in memory. /// - public string[] GetRawMempool() + public async Task GetRawMempool() { - return ((JArray)RpcSend("getrawmempool")).Select(p => p.AsString()).ToArray(); + var result = await RpcSendAsync("getrawmempool").ConfigureAwait(false); + return ((JArray)result).Select(p => p.AsString()).ToArray(); } /// /// Obtains the list of unconfirmed transactions in memory. /// shouldGetUnverified = true /// - public RpcRawMemPool GetRawMempoolBoth() + public async Task GetRawMempoolBoth() { - return RpcRawMemPool.FromJson(RpcSend("getrawmempool", true)); + var result = await RpcSendAsync("getrawmempool", true).ConfigureAwait(false); + return RpcRawMemPool.FromJson(result); } /// /// Returns the corresponding transaction information, based on the specified hash value. /// - public string GetRawTransactionHex(string txHash) + public async Task GetRawTransactionHex(string txHash) { - return RpcSend("getrawtransaction", txHash).AsString(); + var result = await RpcSendAsync("getrawtransaction", txHash).ConfigureAwait(false); + return result.AsString(); } /// /// Returns the corresponding transaction information, based on the specified hash value. /// verbose = true /// - public RpcTransaction GetRawTransaction(string txHash) + public async Task GetRawTransaction(string txHash) { - return RpcTransaction.FromJson(RpcSend("getrawtransaction", txHash, true)); + var result = await RpcSendAsync("getrawtransaction", txHash, true).ConfigureAwait(false); + return RpcTransaction.FromJson(result); } /// /// Returns the stored value, according to the contract script hash (or Id) and the stored key. /// - public string GetStorage(string scriptHashOrId, string key) + public async Task GetStorage(string scriptHashOrId, string key) { - if (int.TryParse(scriptHashOrId, out int id)) - { - return RpcSend("getstorage", id, key).AsString(); - } - - return RpcSend("getstorage", scriptHashOrId, key).AsString(); + var result = int.TryParse(scriptHashOrId, out int id) + ? await RpcSendAsync("getstorage", id, key).ConfigureAwait(false) + : await RpcSendAsync("getstorage", scriptHashOrId, key).ConfigureAwait(false); + return result.AsString(); } /// /// Returns the block index in which the transaction is found. /// - public uint GetTransactionHeight(string txHash) + public async Task GetTransactionHeight(string txHash) { - return uint.Parse(RpcSend("gettransactionheight", txHash).AsString()); + var result = await RpcSendAsync("gettransactionheight", txHash).ConfigureAwait(false); + return uint.Parse(result.AsString()); } /// /// Returns the current NEO consensus nodes information and voting status. /// - public RpcValidator[] GetValidators() + public async Task GetValidators() { - return ((JArray)RpcSend("getvalidators")).Select(p => RpcValidator.FromJson(p)).ToArray(); + var result = await RpcSendAsync("getvalidators").ConfigureAwait(false); + return ((JArray)result).Select(p => RpcValidator.FromJson(p)).ToArray(); } #endregion Blockchain @@ -263,39 +263,43 @@ public RpcValidator[] GetValidators() /// /// Gets the current number of connections for the node. /// - public int GetConnectionCount() + public async Task GetConnectionCount() { - return (int)RpcSend("getconnectioncount").AsNumber(); + var result = await RpcSendAsync("getconnectioncount").ConfigureAwait(false); + return (int)result.AsNumber(); } /// /// Gets the list of nodes that the node is currently connected/disconnected from. /// - public RpcPeers GetPeers() + public async Task GetPeers() { - return RpcPeers.FromJson(RpcSend("getpeers")); + var result = await RpcSendAsync("getpeers").ConfigureAwait(false); + return RpcPeers.FromJson(result); } /// /// Returns the version information about the queried node. /// - public RpcVersion GetVersion() + public async Task GetVersion() { - return RpcVersion.FromJson(RpcSend("getversion")); + var result = await RpcSendAsync("getversion").ConfigureAwait(false); + return RpcVersion.FromJson(result); } /// /// Broadcasts a serialized transaction over the NEO network. /// - public UInt256 SendRawTransaction(byte[] rawTransaction) + public async Task SendRawTransaction(byte[] rawTransaction) { - return UInt256.Parse(RpcSend("sendrawtransaction", rawTransaction.ToHexString())["hash"].AsString()); + var result = await RpcSendAsync("sendrawtransaction", rawTransaction.ToHexString()).ConfigureAwait(false); + return UInt256.Parse(result["hash"].AsString()); } /// /// Broadcasts a transaction over the NEO network. /// - public UInt256 SendRawTransaction(Transaction transaction) + public Task SendRawTransaction(Transaction transaction) { return SendRawTransaction(transaction.ToArray()); } @@ -303,9 +307,10 @@ public UInt256 SendRawTransaction(Transaction transaction) /// /// Broadcasts a serialized block over the NEO network. /// - public UInt256 SubmitBlock(byte[] block) + public async Task SubmitBlock(byte[] block) { - return UInt256.Parse(RpcSend("submitblock", block.ToHexString())["hash"].AsString()); + var result = await RpcSendAsync("submitblock", block.ToHexString()).ConfigureAwait(false); + return UInt256.Parse(result["hash"].AsString()); } #endregion Node @@ -316,33 +321,36 @@ public UInt256 SubmitBlock(byte[] block) /// Returns the result after calling a smart contract at scripthash with the given operation and parameters. /// This RPC call does not affect the blockchain in any way. /// - public RpcInvokeResult InvokeFunction(string scriptHash, string operation, RpcStack[] stacks, params Signer[] signer) + public async Task InvokeFunction(string scriptHash, string operation, RpcStack[] stacks, params Signer[] signer) { List parameters = new List { scriptHash, operation, stacks.Select(p => p.ToJson()).ToArray() }; if (signer.Length > 0) { parameters.Add(signer.Select(p => (JObject)p.ToJson()).ToArray()); } - return RpcInvokeResult.FromJson(RpcSend("invokefunction", parameters.ToArray())); + var result = await RpcSendAsync("invokefunction", parameters.ToArray()).ConfigureAwait(false); + return RpcInvokeResult.FromJson(result); } /// /// Returns the result after passing a script through the VM. /// This RPC call does not affect the blockchain in any way. /// - public RpcInvokeResult InvokeScript(byte[] script, params Signer[] signers) + public async Task InvokeScript(byte[] script, params Signer[] signers) { List parameters = new List { script.ToHexString() }; if (signers.Length > 0) { parameters.Add(signers.Select(p => p.ToJson()).ToArray()); } - return RpcInvokeResult.FromJson(RpcSend("invokescript", parameters.ToArray())); + var result = await RpcSendAsync("invokescript", parameters.ToArray()).ConfigureAwait(false); + return RpcInvokeResult.FromJson(result); } - public RpcUnclaimedGas GetUnclaimedGas(string address) + public async Task GetUnclaimedGas(string address) { - return RpcUnclaimedGas.FromJson(RpcSend("getunclaimedgas", address)); + var result = await RpcSendAsync("getunclaimedgas", address).ConfigureAwait(false); + return RpcUnclaimedGas.FromJson(result); } #endregion SmartContract @@ -352,17 +360,19 @@ public RpcUnclaimedGas GetUnclaimedGas(string address) /// /// Returns a list of plugins loaded by the node. /// - public RpcPlugin[] ListPlugins() + public async Task ListPlugins() { - return ((JArray)RpcSend("listplugins")).Select(p => RpcPlugin.FromJson(p)).ToArray(); + var result = await RpcSendAsync("listplugins").ConfigureAwait(false); + return ((JArray)result).Select(p => RpcPlugin.FromJson(p)).ToArray(); } /// /// Verifies that the address is a correct NEO address. /// - public RpcValidateAddressResult ValidateAddress(string address) + public async Task ValidateAddress(string address) { - return RpcValidateAddressResult.FromJson(RpcSend("validateaddress", address)); + var result = await RpcSendAsync("validateaddress", address).ConfigureAwait(false); + return RpcValidateAddressResult.FromJson(result); } #endregion Utilities @@ -372,25 +382,28 @@ public RpcValidateAddressResult ValidateAddress(string address) /// /// Close the wallet opened by RPC. /// - public bool CloseWallet() + public async Task CloseWallet() { - return RpcSend("closewallet").AsBoolean(); + var result = await RpcSendAsync("closewallet").ConfigureAwait(false); + return result.AsBoolean(); } /// /// Exports the private key of the specified address. /// - public string DumpPrivKey(string address) + public async Task DumpPrivKey(string address) { - return RpcSend("dumpprivkey", address).AsString(); + var result = await RpcSendAsync("dumpprivkey", address).ConfigureAwait(false); + return result.AsString(); } /// /// Creates a new account in the wallet opened by RPC. /// - public string GetNewAddress() + public async Task GetNewAddress() { - return RpcSend("getnewaddress").AsString(); + var result = await RpcSendAsync("getnewaddress").ConfigureAwait(false); + return result.AsString(); } /// @@ -398,60 +411,65 @@ public string GetNewAddress() /// This method applies to assets that conform to NEP-5 standards. /// /// new address as string - public BigDecimal GetWalletBalance(string assetId) + public async Task GetWalletBalance(string assetId) { - byte decimals = new Nep5API(this).Decimals(UInt160.Parse(assetId)); - BigInteger balance = BigInteger.Parse(RpcSend("getwalletbalance", assetId)["balance"].AsString()); + byte decimals = await (new Nep5API(this).Decimals(UInt160.Parse(assetId))); + var result = await RpcSendAsync("getwalletbalance", assetId).ConfigureAwait(false); + BigInteger balance = BigInteger.Parse(result["balance"].AsString()); return new BigDecimal(balance, decimals); } /// /// Gets the amount of unclaimed GAS in the wallet. /// - public BigInteger GetWalletUnclaimedGas() + public async Task GetWalletUnclaimedGas() { - return BigInteger.Parse(RpcSend("getwalletunclaimedgas").AsString()); + var result = await RpcSendAsync("getwalletunclaimedgas").ConfigureAwait(false); + return BigInteger.Parse(result.AsString()); } /// /// Imports the private key to the wallet. /// - public RpcAccount ImportPrivKey(string wif) + public async Task ImportPrivKey(string wif) { - return RpcAccount.FromJson(RpcSend("importprivkey", wif)); + var result = await RpcSendAsync("importprivkey", wif).ConfigureAwait(false); + return RpcAccount.FromJson(result); } /// /// Lists all the accounts in the current wallet. /// - public List ListAddress() + public async Task> ListAddress() { - return ((JArray)RpcSend("listaddress")).Select(p => RpcAccount.FromJson(p)).ToList(); + var result = await RpcSendAsync("listaddress").ConfigureAwait(false); + return ((JArray)result).Select(p => RpcAccount.FromJson(p)).ToList(); } /// /// Open wallet file in the provider's machine. /// By default, this method is disabled by RpcServer config.json. /// - public bool OpenWallet(string path, string password) + public async Task OpenWallet(string path, string password) { - return RpcSend("openwallet", path, password).AsBoolean(); + var result = await RpcSendAsync("openwallet", path, password).ConfigureAwait(false); + return result.AsBoolean(); } /// /// Transfer from the specified address to the destination address. /// /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public JObject SendFrom(string assetId, string fromAddress, string toAddress, string amount) + public async Task SendFrom(string assetId, string fromAddress, string toAddress, string amount) { - return RpcSend("sendfrom", assetId, fromAddress, toAddress, amount); + return await RpcSendAsync("sendfrom", assetId, fromAddress, toAddress, amount).ConfigureAwait(false); } /// /// Bulk transfer order, and you can specify a sender address. /// /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public JObject SendMany(string fromAddress, IEnumerable outputs) + public async Task SendMany(string fromAddress, IEnumerable outputs) { var parameters = new List(); if (!string.IsNullOrEmpty(fromAddress)) @@ -460,16 +478,16 @@ public JObject SendMany(string fromAddress, IEnumerable outputs) } parameters.Add(outputs.Select(p => p.ToJson()).ToArray()); - return RpcSend("sendmany", paraArgs: parameters.ToArray()); + return await RpcSendAsync("sendmany", paraArgs: parameters.ToArray()).ConfigureAwait(false); } /// /// Transfer asset from the wallet to the destination address. /// /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public JObject SendToAddress(string assetId, string address, string amount) + public async Task SendToAddress(string assetId, string address, string amount) { - return RpcSend("sendtoaddress", assetId, address, amount); + return await RpcSendAsync("sendtoaddress", assetId, address, amount).ConfigureAwait(false); } #endregion Wallet @@ -480,9 +498,10 @@ public JObject SendToAddress(string assetId, string address, string amount) /// Returns the contract log based on the specified txHash. The complete contract logs are stored under the ApplicationLogs directory. /// This method is provided by the plugin ApplicationLogs. /// - public RpcApplicationLog GetApplicationLog(string txHash) + public async Task GetApplicationLog(string txHash) { - return RpcApplicationLog.FromJson(RpcSend("getapplicationlog", txHash)); + var result = await RpcSendAsync("getapplicationlog", txHash).ConfigureAwait(false); + return RpcApplicationLog.FromJson(result); } /// @@ -492,20 +511,22 @@ public RpcApplicationLog GetApplicationLog(string txHash) /// The address to query the transaction information. /// The start block Timestamp, default to seven days before UtcNow /// The end block Timestamp, default to UtcNow - public RpcNep5Transfers GetNep5Transfers(string address, ulong? startTimestamp = default, ulong? endTimestamp = default) + public async Task GetNep5Transfers(string address, ulong? startTimestamp = default, ulong? endTimestamp = default) { startTimestamp ??= 0; endTimestamp ??= DateTime.UtcNow.ToTimestampMS(); - return RpcNep5Transfers.FromJson(RpcSend("getnep5transfers", address, startTimestamp, endTimestamp)); + var result = await RpcSendAsync("getnep5transfers", address, startTimestamp, endTimestamp).ConfigureAwait(false); + return RpcNep5Transfers.FromJson(result); } /// /// Returns the balance of all NEP-5 assets in the specified address. /// This method is provided by the plugin RpcNep5Tracker. /// - public RpcNep5Balances GetNep5Balances(string address) + public async Task GetNep5Balances(string address) { - return RpcNep5Balances.FromJson(RpcSend("getnep5balances", address)); + var result = await RpcSendAsync("getnep5balances", address).ConfigureAwait(false); + return RpcNep5Balances.FromJson(result); } #endregion Plugins diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index cd7fe1e1f..4c302d5fb 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; namespace Neo.Network.RPC { @@ -55,10 +56,10 @@ public TransactionManager(RpcClient rpc) /// Transaction Script /// Transaction Attributes /// - public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + public async Task MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) { var random = new Random(); - uint height = rpcClient.GetBlockCount() - 1; + uint height = await rpcClient.GetBlockCount() - 1; Tx = new Transaction { Version = 0, @@ -69,7 +70,7 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null Attributes = attributes ?? Array.Empty(), }; - RpcInvokeResult result = rpcClient.InvokeScript(script, signers); + RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); Tx.SystemFee = long.Parse(result.GasConsumed); context = new ContractParametersContext(Tx); signStore = new List(); @@ -81,7 +82,7 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null /// Calculate NetworkFee /// /// - private long CalculateNetworkFee() + private async Task CalculateNetworkFee() { long networkFee = 0; UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); @@ -96,7 +97,8 @@ private long CalculateNetworkFee() { try { - witness_script = rpcClient.GetContractState(hash.ToString())?.Script; + var contractState = await rpcClient.GetContractState(hash.ToString()).ConfigureAwait(false); + witness_script = contractState?.Script; } catch { } } @@ -104,7 +106,7 @@ private long CalculateNetworkFee() if (witness_script is null) continue; networkFee += Wallet.CalculateNetworkFee(witness_script, ref size); } - networkFee += size * policyAPI.GetFeePerByte(); + networkFee += size * (await policyAPI.GetFeePerByte().ConfigureAwait(false)); return networkFee; } @@ -194,11 +196,11 @@ public TransactionManager AddWitness(UInt160 scriptHash, params object[] paramet /// /// Verify Witness count and add witnesses /// - public TransactionManager Sign() + public async Task Sign() { // Calculate NetworkFee - Tx.NetworkFee = CalculateNetworkFee(); - var gasBalance = nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender); + Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); + var gasBalance = await nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); if (gasBalance < Tx.SystemFee + Tx.NetworkFee) throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); diff --git a/src/RpcClient/WalletAPI.cs b/src/RpcClient/WalletAPI.cs index 014aba6ec..026bd881c 100644 --- a/src/RpcClient/WalletAPI.cs +++ b/src/RpcClient/WalletAPI.cs @@ -37,7 +37,7 @@ public WalletAPI(RpcClient rpc) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public decimal GetUnclaimedGas(string account) + public Task GetUnclaimedGas(string account) { UInt160 accountHash = Utility.GetScriptHash(account); return GetUnclaimedGas(accountHash); @@ -48,11 +48,12 @@ public decimal GetUnclaimedGas(string account) /// /// account scripthash /// - public decimal GetUnclaimedGas(UInt160 account) + public async Task GetUnclaimedGas(UInt160 account) { UInt160 scriptHash = NativeContract.NEO.Hash; - BigInteger balance = nep5API.TestInvoke(scriptHash, "unclaimedGas", account, rpcClient.GetBlockCount() - 1) - .Stack.Single().GetInteger(); + var blockCount = await rpcClient.GetBlockCount().ConfigureAwait(false); + var result = await nep5API.TestInvoke(scriptHash, "unclaimedGas", account, blockCount - 1).ConfigureAwait(false); + BigInteger balance = result.Stack.Single().GetInteger(); return ((decimal)balance) / (long)NativeContract.GAS.Factor; } @@ -62,9 +63,9 @@ public decimal GetUnclaimedGas(UInt160 account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public uint GetNeoBalance(string account) + public async Task GetNeoBalance(string account) { - BigInteger balance = GetTokenBalance(NativeContract.NEO.Hash.ToString(), account); + BigInteger balance = await GetTokenBalance(NativeContract.NEO.Hash.ToString(), account).ConfigureAwait(false); return (uint)balance; } @@ -74,9 +75,9 @@ public uint GetNeoBalance(string account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public decimal GetGasBalance(string account) + public async Task GetGasBalance(string account) { - BigInteger balance = GetTokenBalance(NativeContract.GAS.Hash.ToString(), account); + BigInteger balance = await GetTokenBalance(NativeContract.GAS.Hash.ToString(), account).ConfigureAwait(false); return ((decimal)balance) / (long)NativeContract.GAS.Factor; } @@ -87,7 +88,7 @@ public decimal GetGasBalance(string account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public BigInteger GetTokenBalance(string tokenHash, string account) + public Task GetTokenBalance(string tokenHash, string account) { UInt160 scriptHash = Utility.GetScriptHash(tokenHash); UInt160 accountHash = Utility.GetScriptHash(account); @@ -101,7 +102,7 @@ public BigInteger GetTokenBalance(string tokenHash, string account) /// wif or private key /// Example: WIF ("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"), PrivateKey ("450d6c2a04b5b470339a745427bae6828400cf048400837d73c415063835e005") /// The transaction sended - public Transaction ClaimGas(string key) + public Task ClaimGas(string key) { KeyPair keyPair = Utility.GetKeyPair(key); return ClaimGas(keyPair); @@ -113,12 +114,12 @@ public Transaction ClaimGas(string key) /// /// keyPair /// The transaction sended - public Transaction ClaimGas(KeyPair keyPair) + public async Task ClaimGas(KeyPair keyPair) { UInt160 toHash = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(); - BigInteger balance = nep5API.BalanceOf(NativeContract.NEO.Hash, toHash); + BigInteger balance = await nep5API.BalanceOf(NativeContract.NEO.Hash, toHash).ConfigureAwait(false); Transaction transaction = nep5API.CreateTransferTx(NativeContract.NEO.Hash, keyPair, toHash, balance); - rpcClient.SendRawTransaction(transaction); + await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } @@ -131,15 +132,15 @@ public Transaction ClaimGas(KeyPair keyPair) /// address or account script hash /// token amount /// - public Transaction Transfer(string tokenHash, string fromKey, string toAddress, decimal amount) + public async Task Transfer(string tokenHash, string fromKey, string toAddress, decimal amount) { UInt160 scriptHash = Utility.GetScriptHash(tokenHash); - var decimals = nep5API.Decimals(scriptHash); + var decimals = await nep5API.Decimals(scriptHash).ConfigureAwait(false); KeyPair from = Utility.GetKeyPair(fromKey); UInt160 to = Utility.GetScriptHash(toAddress); BigInteger amountInteger = amount.ToBigInteger(decimals); - return Transfer(scriptHash, from, to, amountInteger); + return await Transfer(scriptHash, from, to, amountInteger).ConfigureAwait(false); } /// @@ -150,10 +151,10 @@ public Transaction Transfer(string tokenHash, string fromKey, string toAddress, /// to account script hash /// transfer amount /// - public Transaction Transfer(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger) + public async Task Transfer(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger) { Transaction transaction = nep5API.CreateTransferTx(scriptHash, from, to, amountInteger); - rpcClient.SendRawTransaction(transaction); + await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } @@ -167,10 +168,10 @@ public Transaction Transfer(UInt160 scriptHash, KeyPair from, UInt160 to, BigInt /// to account /// transfer amount /// - public Transaction Transfer(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger) + public async Task Transfer(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger) { Transaction transaction = nep5API.CreateTransferTx(scriptHash, m, pubKeys, keys, to, amountInteger); - rpcClient.SendRawTransaction(transaction); + await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } @@ -193,7 +194,7 @@ public async Task WaitTransaction(Transaction transaction, int t try { - rpcTx = rpcClient.GetRawTransaction(transaction.Hash.ToString()); + rpcTx = await rpcClient.GetRawTransaction(transaction.Hash.ToString()).ConfigureAwait(false); if (rpcTx == null || rpcTx.Confirmations == null) { await Task.Delay((int)Blockchain.MillisecondsPerBlock / 2); diff --git a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs index dfdbf9990..0208e5cdc 100644 --- a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.SmartContract; @@ -24,13 +25,13 @@ public void TestSetup() } [TestMethod] - public void TestInvoke() + public async Task TestInvoke() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", UInt160.Zero); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.ByteArray, Value = "00e057eb481b".HexToBytes() }); ContractClient contractClient = new ContractClient(rpcClientMock.Object); - var result = contractClient.TestInvoke(NativeContract.GAS.Hash, "balanceOf", UInt160.Zero); + var result = await contractClient.TestInvoke(NativeContract.GAS.Hash, "balanceOf", UInt160.Zero); Assert.AreEqual(30000000000000L, (long)result.Stack[0].GetInteger()); } diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs index 8454d4afa..ba0a5972e 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs @@ -6,6 +6,7 @@ using Neo.Wallets; using System.Linq; using System.Numerics; +using System.Threading.Tasks; namespace Neo.Network.RPC.Tests { @@ -27,57 +28,57 @@ public void TestSetup() } [TestMethod] - public void TestBalanceOf() + public async Task TestBalanceOf() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", UInt160.Zero); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(10000) }); - var balance = nep5API.BalanceOf(NativeContract.GAS.Hash, UInt160.Zero); + var balance = await nep5API.BalanceOf(NativeContract.GAS.Hash, UInt160.Zero); Assert.AreEqual(10000, (int)balance); } [TestMethod] - public void TestGetName() + public async Task TestGetName() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("name"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.String, Value = NativeContract.GAS.Name }); - var result = nep5API.Name(NativeContract.GAS.Hash); + var result = await nep5API.Name(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Name, result); } [TestMethod] - public void TestGetSymbol() + public async Task TestGetSymbol() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("symbol"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.String, Value = NativeContract.GAS.Symbol }); - var result = nep5API.Symbol(NativeContract.GAS.Hash); + var result = await nep5API.Symbol(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Symbol, result); } [TestMethod] - public void TestGetDecimals() + public async Task TestGetDecimals() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("decimals"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(NativeContract.GAS.Decimals) }); - var result = nep5API.Decimals(NativeContract.GAS.Hash); + var result = await nep5API.Decimals(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Decimals, result); } [TestMethod] - public void TestGetTotalSupply() + public async Task TestGetTotalSupply() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("totalSupply"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var result = nep5API.TotalSupply(NativeContract.GAS.Hash); + var result = await nep5API.TotalSupply(NativeContract.GAS.Hash); Assert.AreEqual(1_00000000, (int)result); } [TestMethod] - public void TestGetTokenInfo() + public async Task TestGetTokenInfo() { UInt160 scriptHash = NativeContract.GAS.Hash; byte[] testScript = scriptHash.MakeScript("name") @@ -91,7 +92,7 @@ public void TestGetTokenInfo() new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(NativeContract.GAS.Decimals) }, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var result = nep5API.GetTokenInfo(NativeContract.GAS.Hash); + var result = await nep5API.GetTokenInfo(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Name, result.Name); Assert.AreEqual(NativeContract.GAS.Symbol, result.Symbol); Assert.AreEqual(8, (int)result.Decimals); diff --git a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs index b6a8bdd01..8437f567b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs @@ -5,6 +5,7 @@ using Neo.VM; using Neo.Wallets; using System.Numerics; +using System.Threading.Tasks; namespace Neo.Network.RPC.Tests { @@ -26,42 +27,42 @@ public void TestSetup() } [TestMethod] - public void TestGetMaxTransactionsPerBlock() + public async Task TestGetMaxTransactionsPerBlock() { byte[] testScript = NativeContract.Policy.Hash.MakeScript("getMaxTransactionsPerBlock"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(512) }); - var result = policyAPI.GetMaxTransactionsPerBlock(); + var result = await policyAPI.GetMaxTransactionsPerBlock(); Assert.AreEqual(512u, result); } [TestMethod] - public void TestGetMaxBlockSize() + public async Task TestGetMaxBlockSize() { byte[] testScript = NativeContract.Policy.Hash.MakeScript("getMaxBlockSize"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1024u * 256u) }); - var result = policyAPI.GetMaxBlockSize(); + var result = await policyAPI.GetMaxBlockSize(); Assert.AreEqual(1024u * 256u, result); } [TestMethod] - public void TestGetFeePerByte() + public async Task TestGetFeePerByte() { byte[] testScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1000) }); - var result = policyAPI.GetFeePerByte(); + var result = await policyAPI.GetFeePerByte(); Assert.AreEqual(1000L, result); } [TestMethod] - public void TestGetBlockedAccounts() + public async Task TestGetBlockedAccounts() { byte[] testScript = NativeContract.Policy.Hash.MakeScript("getBlockedAccounts"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Array, Value = new[] { new ContractParameter { Type = ContractParameterType.Hash160, Value = UInt160.Zero } } }); - var result = policyAPI.GetBlockedAccounts(); + var result = await policyAPI.GetBlockedAccounts(); Assert.AreEqual(UInt160.Zero, result[0]); } } diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs index 302040e47..fc0b3e825 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs @@ -27,12 +27,8 @@ public void TestSetup() handlerMock = new Mock(MockBehavior.Strict); // use real http client with mocked handler here - var httpClient = new HttpClient(handlerMock.Object) - { - BaseAddress = new Uri("http://seed1.neo.org:10331"), - }; - - rpc = new RpcClient(httpClient); + var httpClient = new HttpClient(handlerMock.Object); + rpc = new RpcClient(httpClient, "http://seed1.neo.org:10331"); foreach (var test in TestUtils.RpcTestCases) { MockResponse(test.Request, test.Response); @@ -58,12 +54,12 @@ private void MockResponse(RpcRequest request, RpcResponse response) } [TestMethod] - public void TestErrorResponse() + public async Task TestErrorResponse() { var test = TestUtils.RpcTestCases.Find(p => p.Name == (nameof(rpc.SendRawTransaction) + "error").ToLower()); try { - var result = rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); + var result = await rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); } catch (RpcException ex) { @@ -91,137 +87,137 @@ public void TestConstructorWithBasicAuth() #region Blockchain [TestMethod] - public void TestGetBestBlockHash() + public async Task TestGetBestBlockHash() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBestBlockHash).ToLower()); - var result = rpc.GetBestBlockHash(); + var result = await rpc.GetBestBlockHash(); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] - public void TestGetBlockHex() + public async Task TestGetBlockHex() { var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHex).ToLower()); foreach (var test in tests) { - var result = rpc.GetBlockHex(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHex(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } } [TestMethod] - public void TestGetBlock() + public async Task TestGetBlock() { var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlock).ToLower()); foreach (var test in tests) { - var result = rpc.GetBlock(test.Request.Params[0].AsString()); + var result = await rpc.GetBlock(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result.ToJson().ToString()); } } [TestMethod] - public void TestGetBlockCount() + public async Task TestGetBlockCount() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockCount).ToLower()); - var result = rpc.GetBlockCount(); + var result = await rpc.GetBlockCount(); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] - public void TestGetBlockHash() + public async Task TestGetBlockHash() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockHash).ToLower()); - var result = rpc.GetBlockHash((int)test.Request.Params[0].AsNumber()); + var result = await rpc.GetBlockHash((int)test.Request.Params[0].AsNumber()); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] - public void TestGetBlockHeaderHex() + public async Task TestGetBlockHeaderHex() { var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeaderHex).ToLower()); foreach (var test in tests) { - var result = rpc.GetBlockHeaderHex(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHeaderHex(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } } [TestMethod] - public void TestGetBlockHeader() + public async Task TestGetBlockHeader() { var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeader).ToLower()); foreach (var test in tests) { - var result = rpc.GetBlockHeader(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHeader(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } } [TestMethod] - public void TestGetContractState() + public async Task TestGetContractState() { var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetContractState).ToLower()); foreach (var test in tests) { - var result = rpc.GetContractState(test.Request.Params[0].AsString()); + var result = await rpc.GetContractState(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } } [TestMethod] - public void TestGetRawMempool() + public async Task TestGetRawMempool() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempool).ToLower()); - var result = rpc.GetRawMempool(); + var result = await rpc.GetRawMempool(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => (JObject)p).ToArray()).ToString()); } [TestMethod] - public void TestGetRawMempoolBoth() + public async Task TestGetRawMempoolBoth() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempoolBoth).ToLower()); - var result = rpc.GetRawMempoolBoth(); + var result = await rpc.GetRawMempoolBoth(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestGetRawTransactionHex() + public async Task TestGetRawTransactionHex() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransactionHex).ToLower()); - var result = rpc.GetRawTransactionHex(test.Request.Params[0].AsString()); + var result = await rpc.GetRawTransactionHex(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] - public void TestGetRawTransaction() + public async Task TestGetRawTransaction() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransaction).ToLower()); - var result = rpc.GetRawTransaction(test.Request.Params[0].AsString()); + var result = await rpc.GetRawTransaction(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestGetStorage() + public async Task TestGetStorage() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetStorage).ToLower()); - var result = rpc.GetStorage(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); + var result = await rpc.GetStorage(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] - public void TestGetTransactionHeight() + public async Task TestGetTransactionHeight() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetTransactionHeight).ToLower()); - var result = rpc.GetTransactionHeight(test.Request.Params[0].AsString()); + var result = await rpc.GetTransactionHeight(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] - public void TestGetValidators() + public async Task TestGetValidators() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetValidators).ToLower()); - var result = rpc.GetValidators(); + var result = await rpc.GetValidators(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } @@ -230,43 +226,43 @@ public void TestGetValidators() #region Node [TestMethod] - public void TestGetConnectionCount() + public async Task TestGetConnectionCount() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetConnectionCount).ToLower()); - var result = rpc.GetConnectionCount(); + var result = await rpc.GetConnectionCount(); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] - public void TestGetPeers() + public async Task TestGetPeers() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetPeers).ToLower()); - var result = rpc.GetPeers(); + var result = await rpc.GetPeers(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestGetVersion() + public async Task TestGetVersion() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetVersion).ToLower()); - var result = rpc.GetVersion(); + var result = await rpc.GetVersion(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestSendRawTransaction() + public async Task TestSendRawTransaction() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendRawTransaction).ToLower()); - var result = rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); + var result = await rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); Assert.AreEqual(test.Response.Result["hash"].AsString(), result.ToString()); } [TestMethod] - public void TestSubmitBlock() + public async Task TestSubmitBlock() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SubmitBlock).ToLower()); var block = TestUtils.GetBlock(2).Hash; - var result = rpc.SubmitBlock(test.Request.Params[0].AsString().HexToBytes()); + var result = await rpc.SubmitBlock(test.Request.Params[0].AsString().HexToBytes()); Assert.AreEqual(test.Response.Result["hash"].AsString(), result.ToString()); } @@ -275,27 +271,27 @@ public void TestSubmitBlock() #region SmartContract [TestMethod] - public void TestInvokeFunction() + public async Task TestInvokeFunction() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeFunction).ToLower()); - var result = rpc.InvokeFunction(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), + var result = await rpc.InvokeFunction(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), ((JArray)test.Request.Params[2]).Select(p => RpcStack.FromJson(p)).ToArray()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestInvokeScript() + public async Task TestInvokeScript() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeScript).ToLower()); - var result = rpc.InvokeScript(test.Request.Params[0].AsString().HexToBytes()); + var result = await rpc.InvokeScript(test.Request.Params[0].AsString().HexToBytes()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestGetUnclaimedGas() + public async Task TestGetUnclaimedGas() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetUnclaimedGas).ToLower()); - var result = rpc.GetUnclaimedGas(test.Request.Params[0].AsString()); + var result = await rpc.GetUnclaimedGas(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result["unclaimed"].AsString(), result.Unclaimed.ToString()); } @@ -304,18 +300,18 @@ public void TestGetUnclaimedGas() #region Utilities [TestMethod] - public void TestListPlugins() + public async Task TestListPlugins() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListPlugins).ToLower()); - var result = rpc.ListPlugins(); + var result = await rpc.ListPlugins(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } [TestMethod] - public void TestValidateAddress() + public async Task TestValidateAddress() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ValidateAddress).ToLower()); - var result = rpc.ValidateAddress(test.Request.Params[0].AsString()); + var result = await rpc.ValidateAddress(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } @@ -324,91 +320,91 @@ public void TestValidateAddress() #region Wallet [TestMethod] - public void TestCloseWallet() + public async Task TestCloseWallet() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.CloseWallet).ToLower()); - var result = rpc.CloseWallet(); + var result = await rpc.CloseWallet(); Assert.AreEqual(test.Response.Result.AsBoolean(), result); } [TestMethod] - public void TestDumpPrivKey() + public async Task TestDumpPrivKey() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.DumpPrivKey).ToLower()); - var result = rpc.DumpPrivKey(test.Request.Params[0].AsString()); + var result = await rpc.DumpPrivKey(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] - public void TestGetNewAddress() + public async Task TestGetNewAddress() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNewAddress).ToLower()); - var result = rpc.GetNewAddress(); + var result = await rpc.GetNewAddress(); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] - public void TestGetWalletBalance() + public async Task TestGetWalletBalance() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletBalance).ToLower()); - var result = rpc.GetWalletBalance(test.Request.Params[0].AsString()); + var result = await rpc.GetWalletBalance(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result["balance"].AsString(), result.Value.ToString()); } [TestMethod] - public void TestGetWalletUnclaimedGas() + public async Task TestGetWalletUnclaimedGas() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletUnclaimedGas).ToLower()); - var result = rpc.GetWalletUnclaimedGas(); + var result = await rpc.GetWalletUnclaimedGas(); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] - public void TestImportPrivKey() + public async Task TestImportPrivKey() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ImportPrivKey).ToLower()); - var result = rpc.ImportPrivKey(test.Request.Params[0].AsString()); + var result = await rpc.ImportPrivKey(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] - public void TestListAddress() + public async Task TestListAddress() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListAddress).ToLower()); - var result = rpc.ListAddress(); + var result = await rpc.ListAddress(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } [TestMethod] - public void TestOpenWallet() + public async Task TestOpenWallet() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.OpenWallet).ToLower()); - var result = rpc.OpenWallet(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); + var result = await rpc.OpenWallet(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); Assert.AreEqual(test.Response.Result.AsBoolean(), result); } [TestMethod] - public void TestSendFrom() + public async Task TestSendFrom() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendFrom).ToLower()); - var result = rpc.SendFrom(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), + var result = await rpc.SendFrom(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString(), test.Request.Params[3].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] - public void TestSendMany() + public async Task TestSendMany() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendMany).ToLower()); - var result = rpc.SendMany(test.Request.Params[0].AsString(), ((JArray)test.Request.Params[1]).Select(p => RpcTransferOut.FromJson(p))); + var result = await rpc.SendMany(test.Request.Params[0].AsString(), ((JArray)test.Request.Params[1]).Select(p => RpcTransferOut.FromJson(p))); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] - public void TestSendToAddress() + public async Task TestSendToAddress() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendToAddress).ToLower()); - var result = rpc.SendToAddress(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString()); + var result = await rpc.SendToAddress(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } @@ -417,27 +413,27 @@ public void TestSendToAddress() #region Plugins [TestMethod()] - public void GetApplicationLogTest() + public async Task GetApplicationLogTest() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetApplicationLog).ToLower()); - var result = rpc.GetApplicationLog(test.Request.Params[0].AsString()); + var result = await rpc.GetApplicationLog(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod()] - public void GetNep5TransfersTest() + public async Task GetNep5TransfersTest() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5Transfers).ToLower()); - var result = rpc.GetNep5Transfers(test.Request.Params[0].AsString(), (ulong)test.Request.Params[1].AsNumber(), + var result = await rpc.GetNep5Transfers(test.Request.Params[0].AsString(), (ulong)test.Request.Params[1].AsNumber(), (ulong)test.Request.Params[2].AsNumber()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod()] - public void GetNep5BalancesTest() + public async Task GetNep5BalancesTest() { var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5Balances).ToLower()); - var result = rpc.GetNep5Balances(test.Request.Params[0].AsString()); + var result = await rpc.GetNep5Balances(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index b1546a9c7..56b40181b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -41,181 +41,186 @@ public void TestSetup() public static Mock MockRpcClient(UInt160 sender, byte[] script) { - var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); + throw new NotImplementedException(); + // var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); - // MockHeight - mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); + // // MockHeight + // mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); - // MockGasBalance - byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); - var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; + // // MockGasBalance + // byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); + // var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; - MockInvokeScript(mockRpc, balanceScript, balanceResult); + // MockInvokeScript(mockRpc, balanceScript, balanceResult); - // MockFeePerByte - byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); - var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; + // // MockFeePerByte + // byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); + // var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; - MockInvokeScript(mockRpc, policyScript, policyResult); + // MockInvokeScript(mockRpc, policyScript, policyResult); - // MockGasConsumed - var result = new ContractParameter(); - MockInvokeScript(mockRpc, script, result); + // // MockGasConsumed + // var result = new ContractParameter(); + // MockInvokeScript(mockRpc, script, result); - return mockRpc; + // return mockRpc; } public static Mock MockMultiSig(UInt160 multiHash, byte[] script) { - var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); + throw new NotImplementedException(); - // MockHeight - mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); + // var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); - // MockGasBalance - byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash); - var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; + // // MockHeight + // mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); - MockInvokeScript(mockRpc, balanceScript, balanceResult); + // // MockGasBalance + // byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash); + // var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; - // MockFeePerByte - byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); - var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; + // MockInvokeScript(mockRpc, balanceScript, balanceResult); - MockInvokeScript(mockRpc, policyScript, policyResult); + // // MockFeePerByte + // byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); + // var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; - // MockGasConsumed - var result = new ContractParameter(); - MockInvokeScript(mockRpc, script, result); + // MockInvokeScript(mockRpc, policyScript, policyResult); - return mockRpc; - } - - public static void MockInvokeScript(Mock mockClient, byte[] script, params ContractParameter[] parameters) - { - var result = new RpcInvokeResult() - { - Stack = parameters.Select(p => p.ToStackItem()).ToArray(), - GasConsumed = "100", - Script = script.ToHexString(), - State = VMState.HALT - }; - - mockClient.Setup(p => p.RpcSend("invokescript", It.Is(j => j[0].AsString() == script.ToHexString()))) - .Returns(result.ToJson()) - .Verifiable(); - } - - [TestMethod] - public void TestMakeTransaction() - { - txManager = new TransactionManager(rpcClientMock.Object); - - Signer[] signers = new Signer[1] - { - new Signer - { - Account = sender, - Scopes= WitnessScope.Global - } - }; - - byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers); - - var tx = txManager.Tx; - Assert.AreEqual(WitnessScope.Global, tx.Signers[0].Scopes); - } + // // MockGasConsumed + // var result = new ContractParameter(); + // MockInvokeScript(mockRpc, script, result); - [TestMethod] - public void TestSign() - { - txManager = new TransactionManager(rpcClientMock.Object); - - Signer[] signers = new Signer[1] - { - new Signer - { - Account = sender, - Scopes = WitnessScope.Global - } - }; - - byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers) - .AddSignature(keyPair1) - .Sign(); - - // get signature from Witnesses - var tx = txManager.Tx; - byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray(); - - Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey)); - // verify network fee and system fee - long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1; - Assert.AreEqual(networkFee, tx.NetworkFee); - Assert.AreEqual(100, tx.SystemFee); - - // duplicate sign should not add new witness - txManager.AddSignature(keyPair1).Sign(); - Assert.AreEqual(1, txManager.Tx.Witnesses.Length); - - // throw exception when the KeyPair is wrong - Assert.ThrowsException(() => txManager.AddSignature(keyPair2).Sign()); + // return mockRpc; } - [TestMethod] - public void TestSignMulti() + public static void MockInvokeScript(Mock mockClient, byte[] script, params ContractParameter[] parameters) { - txManager = new TransactionManager(multiSigMock.Object); - - // Cosigner needs multi signature - Signer[] signers = new Signer[1] - { - new Signer - { - Account = multiHash, - Scopes = WitnessScope.Global - } - }; - - byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers) - .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey) - .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey) - .Sign(); + throw new NotImplementedException(); + + // var result = new RpcInvokeResult() + // { + // Stack = parameters.Select(p => p.ToStackItem()).ToArray(), + // GasConsumed = "100", + // Script = script.ToHexString(), + // State = VMState.HALT + // }; + + // mockClient.Setup(p => p.RpcSend("invokescript", It.Is(j => j[0].AsString() == script.ToHexString()))) + // .Returns(result.ToJson()) + // .Verifiable(); } - [TestMethod] - public void TestAddWitness() - { - txManager = new TransactionManager(rpcClientMock.Object); - - // Cosigner as contract scripthash - Signer[] signers = new Signer[2] - { - new Signer - { - Account = sender, - Scopes = WitnessScope.Global - }, - new Signer - { - Account = UInt160.Zero, - Scopes = WitnessScope.Global - } - }; - - byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers); - txManager.AddWitness(UInt160.Zero); - txManager.AddSignature(keyPair1); - txManager.Sign(); - - var tx = txManager.Tx; - Assert.AreEqual(2, tx.Witnesses.Length); - Assert.AreEqual(41, tx.Witnesses[0].VerificationScript.Length); - Assert.AreEqual(66, tx.Witnesses[0].InvocationScript.Length); - } + // [TestMethod] + // public void TestMakeTransaction() + // { + // txManager = new TransactionManager(rpcClientMock.Object); + + // Signer[] signers = new Signer[1] + // { + // new Signer + // { + // Account = sender, + // Scopes= WitnessScope.Global + // } + // }; + + // byte[] script = new byte[1]; + // txManager.MakeTransaction(script, signers); + + // var tx = txManager.Tx; + // Assert.AreEqual(WitnessScope.Global, tx.Signers[0].Scopes); + // } + + // [TestMethod] + // public void TestSign() + // { + // txManager = new TransactionManager(rpcClientMock.Object); + + // Signer[] signers = new Signer[1] + // { + // new Signer + // { + // Account = sender, + // Scopes = WitnessScope.Global + // } + // }; + + // byte[] script = new byte[1]; + // txManager.MakeTransaction(script, signers) + // .AddSignature(keyPair1) + // .Sign(); + + // // get signature from Witnesses + // var tx = txManager.Tx; + // byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray(); + + // Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey)); + // // verify network fee and system fee + // long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1; + // Assert.AreEqual(networkFee, tx.NetworkFee); + // Assert.AreEqual(100, tx.SystemFee); + + // // duplicate sign should not add new witness + // txManager.AddSignature(keyPair1).Sign(); + // Assert.AreEqual(1, txManager.Tx.Witnesses.Length); + + // // throw exception when the KeyPair is wrong + // Assert.ThrowsException(() => txManager.AddSignature(keyPair2).Sign()); + // } + + // [TestMethod] + // public void TestSignMulti() + // { + // txManager = new TransactionManager(multiSigMock.Object); + + // // Cosigner needs multi signature + // Signer[] signers = new Signer[1] + // { + // new Signer + // { + // Account = multiHash, + // Scopes = WitnessScope.Global + // } + // }; + + // byte[] script = new byte[1]; + // txManager.MakeTransaction(script, signers) + // .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey) + // .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey) + // .Sign(); + // } + + // [TestMethod] + // public void TestAddWitness() + // { + // txManager = new TransactionManager(rpcClientMock.Object); + + // // Cosigner as contract scripthash + // Signer[] signers = new Signer[2] + // { + // new Signer + // { + // Account = sender, + // Scopes = WitnessScope.Global + // }, + // new Signer + // { + // Account = UInt160.Zero, + // Scopes = WitnessScope.Global + // } + // }; + + // byte[] script = new byte[1]; + // txManager.MakeTransaction(script, signers); + // txManager.AddWitness(UInt160.Zero); + // txManager.AddSignature(keyPair1); + // txManager.Sign(); + + // var tx = txManager.Tx; + // Assert.AreEqual(2, tx.Witnesses.Length); + // Assert.AreEqual(41, tx.Witnesses[0].VerificationScript.Length); + // Assert.AreEqual(66, tx.Witnesses[0].InvocationScript.Length); + // } } } diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 37a0cc181..3acff8bc1 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -8,6 +8,7 @@ using Neo.VM; using Neo.Wallets; using System.Numerics; +using System.Threading.Tasks; namespace Neo.Network.RPC.Tests { @@ -33,42 +34,42 @@ public void TestSetup() } [TestMethod] - public void TestGetUnclaimedGas() + public async Task TestGetUnclaimedGas() { byte[] testScript = NativeContract.NEO.Hash.MakeScript("unclaimedGas", sender, 99); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = walletAPI.GetUnclaimedGas(address1); + var balance = await walletAPI.GetUnclaimedGas(address1); Assert.AreEqual(1.1m, balance); } [TestMethod] - public void TestGetNeoBalance() + public async Task TestGetNeoBalance() { byte[] testScript = NativeContract.NEO.Hash.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var balance = walletAPI.GetNeoBalance(address1); + var balance = await walletAPI.GetNeoBalance(address1); Assert.AreEqual(1_00000000u, balance); } [TestMethod] - public void TestGetGasBalance() + public async Task TestGetGasBalance() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = walletAPI.GetGasBalance(address1); + var balance = await walletAPI.GetGasBalance(address1); Assert.AreEqual(1.1m, balance); } [TestMethod] - public void TestGetTokenBalance() + public async Task TestGetTokenBalance() { byte[] testScript = UInt160.Zero.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = walletAPI.GetTokenBalance(UInt160.Zero.ToString(), address1); + var balance = await walletAPI.GetTokenBalance(UInt160.Zero.ToString(), address1); Assert.AreEqual(1_10000000, balance); } @@ -81,12 +82,13 @@ public void TestClaimGas() byte[] testScript = NativeContract.NEO.Hash.MakeScript("transfer", sender, sender, new BigInteger(1_00000000)); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var json = new JObject(); - json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + Assert.Fail(); + // var json = new JObject(); + // json["hash"] = UInt256.Zero.ToString(); + // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); - var tranaction = walletAPI.ClaimGas(keyPair1.Export()); - Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + // var tranaction = walletAPI.ClaimGas(keyPair1.Export()); + // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] @@ -98,12 +100,14 @@ public void TestTransfer() byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, NativeContract.GAS.Factor * 100); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var json = new JObject(); - json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + Assert.Fail(); - var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); - Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + // var json = new JObject(); + // json["hash"] = UInt256.Zero.ToString(); + // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + + // var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); + // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] @@ -120,24 +124,28 @@ public void TestTransferfromMultiSigAccount() byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var json = new JObject(); - json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + Assert.Fail(); + + // var json = new JObject(); + // json["hash"] = UInt256.Zero.ToString(); + // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); - var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); - Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + // var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); + // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] public void TestWaitTransaction() { - Transaction transaction = TestUtils.GetTransaction(); - rpcClientMock.Setup(p => p.RpcSend("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) - .Returns(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson()); + Assert.Fail(); + + // Transaction transaction = TestUtils.GetTransaction(); + // rpcClientMock.Setup(p => p.RpcSend("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) + // .Returns(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson()); - var tx = walletAPI.WaitTransaction(transaction).Result; - Assert.AreEqual(VMState.HALT, tx.VMState); - Assert.AreEqual(UInt256.Zero, tx.BlockHash); + // var tx = walletAPI.WaitTransaction(transaction).Result; + // Assert.AreEqual(VMState.HALT, tx.VMState); + // Assert.AreEqual(UInt256.Zero, tx.BlockHash); } } } From dd6614039a2e01b09e5d548979a789935618ead3 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 16:08:52 -0700 Subject: [PATCH 02/21] more tests working --- src/RpcClient/RpcClient.cs | 2 +- .../UT_TransactionManager.cs | 88 +++++++++---------- tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 57 ++++++------ 3 files changed, 68 insertions(+), 79 deletions(-) diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index b4c0009b9..894c7da81 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -80,7 +80,7 @@ public async Task SendAsync(RpcRequest request) return response; } - public async Task RpcSendAsync(string method, params JObject[] paraArgs) + public virtual async Task RpcSendAsync(string method, params JObject[] paraArgs) { var request = new RpcRequest { diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 56b40181b..803c37e7d 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -14,6 +14,7 @@ using System; using System.Linq; using System.Numerics; +using System.Threading.Tasks; namespace Neo.Network.RPC.Tests { @@ -41,74 +42,69 @@ public void TestSetup() public static Mock MockRpcClient(UInt160 sender, byte[] script) { - throw new NotImplementedException(); - // var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); + var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); - // // MockHeight - // mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); + // MockHeight + mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).Returns(Task.FromResult((JObject)100)).Verifiable(); - // // MockGasBalance - // byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); - // var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; + // MockGasBalance + byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); + var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; - // MockInvokeScript(mockRpc, balanceScript, balanceResult); + MockInvokeScript(mockRpc, balanceScript, balanceResult); - // // MockFeePerByte - // byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); - // var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; + // MockFeePerByte + byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); + var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; - // MockInvokeScript(mockRpc, policyScript, policyResult); + MockInvokeScript(mockRpc, policyScript, policyResult); - // // MockGasConsumed - // var result = new ContractParameter(); - // MockInvokeScript(mockRpc, script, result); + // MockGasConsumed + var result = new ContractParameter(); + MockInvokeScript(mockRpc, script, result); - // return mockRpc; + return mockRpc; } public static Mock MockMultiSig(UInt160 multiHash, byte[] script) { - throw new NotImplementedException(); + var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); - // var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); + // MockHeight + mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).Returns(Task.FromResult((JObject)100)).Verifiable(); - // // MockHeight - // mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable(); + // MockGasBalance + byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash); + var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; - // // MockGasBalance - // byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash); - // var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; + MockInvokeScript(mockRpc, balanceScript, balanceResult); - // MockInvokeScript(mockRpc, balanceScript, balanceResult); + // MockFeePerByte + byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); + var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; - // // MockFeePerByte - // byte[] policyScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); - // var policyResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("1000") }; + MockInvokeScript(mockRpc, policyScript, policyResult); - // MockInvokeScript(mockRpc, policyScript, policyResult); + // MockGasConsumed + var result = new ContractParameter(); + MockInvokeScript(mockRpc, script, result); - // // MockGasConsumed - // var result = new ContractParameter(); - // MockInvokeScript(mockRpc, script, result); - - // return mockRpc; + return mockRpc; } public static void MockInvokeScript(Mock mockClient, byte[] script, params ContractParameter[] parameters) { - throw new NotImplementedException(); - - // var result = new RpcInvokeResult() - // { - // Stack = parameters.Select(p => p.ToStackItem()).ToArray(), - // GasConsumed = "100", - // Script = script.ToHexString(), - // State = VMState.HALT - // }; - - // mockClient.Setup(p => p.RpcSend("invokescript", It.Is(j => j[0].AsString() == script.ToHexString()))) - // .Returns(result.ToJson()) - // .Verifiable(); + var result = new RpcInvokeResult() + { + Stack = parameters.Select(p => p.ToStackItem()).ToArray(), + GasConsumed = "100", + Script = script.ToHexString(), + State = VMState.HALT + }; + + mockClient.Setup(p => p.RpcSendAsync("invokescript", It.Is(j => j[0].AsString() == script.ToHexString()))) + .Returns(Task.FromResult(result.ToJson())) + .Verifiable(); } // [TestMethod] diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 3acff8bc1..5ecead29b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -74,7 +74,7 @@ public async Task TestGetTokenBalance() } [TestMethod] - public void TestClaimGas() + public async Task TestClaimGas() { byte[] balanceScript = NativeContract.NEO.Hash.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, balanceScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); @@ -82,17 +82,16 @@ public void TestClaimGas() byte[] testScript = NativeContract.NEO.Hash.MakeScript("transfer", sender, sender, new BigInteger(1_00000000)); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - Assert.Fail(); - // var json = new JObject(); - // json["hash"] = UInt256.Zero.ToString(); - // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + var json = new JObject(); + json["hash"] = UInt256.Zero.ToString(); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); - // var tranaction = walletAPI.ClaimGas(keyPair1.Export()); - // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + var tranaction = await walletAPI.ClaimGas(keyPair1.Export()); + Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] - public void TestTransfer() + public async Task TestTransfer() { byte[] decimalsScript = NativeContract.GAS.Hash.MakeScript("decimals"); UT_TransactionManager.MockInvokeScript(rpcClientMock, decimalsScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(8) }); @@ -100,18 +99,16 @@ public void TestTransfer() byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, NativeContract.GAS.Factor * 100); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - Assert.Fail(); + var json = new JObject(); + json["hash"] = UInt256.Zero.ToString(); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); - // var json = new JObject(); - // json["hash"] = UInt256.Zero.ToString(); - // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); - - // var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); - // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); + Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] - public void TestTransferfromMultiSigAccount() + public async Task TestTransferfromMultiSigAccount() { byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiSender); var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") }; @@ -124,28 +121,24 @@ public void TestTransferfromMultiSigAccount() byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - Assert.Fail(); - - // var json = new JObject(); - // json["hash"] = UInt256.Zero.ToString(); - // rpcClientMock.Setup(p => p.RpcSend("sendrawtransaction", It.IsAny())).Returns(json); + var json = new JObject(); + json["hash"] = UInt256.Zero.ToString(); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); - // var tranaction = walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); - // Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); + var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); + Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } [TestMethod] - public void TestWaitTransaction() + public async Task TestWaitTransaction() { - Assert.Fail(); - - // Transaction transaction = TestUtils.GetTransaction(); - // rpcClientMock.Setup(p => p.RpcSend("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) - // .Returns(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson()); + Transaction transaction = TestUtils.GetTransaction(); + rpcClientMock.Setup(p => p.RpcSendAsync("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) + .Returns(Task.FromResult(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson())); - // var tx = walletAPI.WaitTransaction(transaction).Result; - // Assert.AreEqual(VMState.HALT, tx.VMState); - // Assert.AreEqual(UInt256.Zero, tx.BlockHash); + var tx = await walletAPI.WaitTransaction(transaction); + Assert.AreEqual(VMState.HALT, tx.VMState); + Assert.AreEqual(UInt256.Zero, tx.BlockHash); } } } From c02058bd7bc16f48629ad1862af0371989dc580f Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 16:51:19 -0700 Subject: [PATCH 03/21] MakeTxContext --- src/RpcClient/ContractClient.cs | 31 +- src/RpcClient/Nep5API.cs | 52 +- src/RpcClient/TransactionManager.cs | 471 ++++++++++++------ src/RpcClient/Utility.cs | 5 + src/RpcClient/WalletAPI.cs | 6 +- .../UT_TransactionManager.cs | 2 +- 6 files changed, 369 insertions(+), 198 deletions(-) diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index 8f59943fc..5964fad8c 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -45,26 +45,23 @@ public Task TestInvoke(UInt160 scriptHash, string operation, pa /// contract manifest /// sender KeyPair /// - public Transaction CreateDeployContractTx(byte[] contractScript, ContractManifest manifest, KeyPair key) + public async Task CreateDeployContractTx(byte[] contractScript, ContractManifest manifest, KeyPair key) { - throw new NotImplementedException(); + byte[] script; + using (ScriptBuilder sb = new ScriptBuilder()) + { + sb.EmitSysCall(ApplicationEngine.System_Contract_Create, contractScript, manifest.ToString()); + script = sb.ToArray(); + } + UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); + Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - // byte[] script; - // using (ScriptBuilder sb = new ScriptBuilder()) - // { - // sb.EmitSysCall(ApplicationEngine.System_Contract_Create, contractScript, manifest.ToString()); - // script = sb.ToArray(); - // } - // UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); - // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + Transaction tx = await rpcClient + .MakeTransaction(script, signers) + .AddSignature(key) + .SignAsync().ConfigureAwait(false); - // Transaction tx = new TransactionManager(rpcClient) - // .MakeTransaction(script, signers) - // .AddSignature(key) - // .Sign() - // .Tx; - - // return tx; + return tx; } } } diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index bc77ae6bc..f9b4f4472 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -112,20 +112,17 @@ public async Task GetTokenInfo(UInt160 scriptHash) /// to account script hash /// transfer amount /// - public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount) + public async Task CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount) { - throw new NotImplementedException(); - // var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); - // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - - // byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - // Transaction tx = new TransactionManager(rpcClient) - // .MakeTransaction(script, signers) - // .AddSignature(fromKey) - // .Sign() - // .Tx; - - // return tx; + var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); + Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + + byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); + var tx = await rpcClient.MakeTransaction(script, signers) + .AddSignature(fromKey) + .SignAsync().ConfigureAwait(false); + + return tx; } /// @@ -138,29 +135,20 @@ public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 /// to account /// transfer amount /// - public Transaction CreateTransferTx(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount) + public async Task CreateTransferTx(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount) { - throw new NotImplementedException(); - - // if (m > fromKeys.Length) - // throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); - // var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash; - // Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - - // byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - // var tm = new TransactionManager(rpcClient); - // Transaction tx = new TransactionManager(rpcClient) - // .MakeTransaction(script, signers) - // .AddMultiSig(fromKeys, m, pubKeys) - // .Sign() - // .Tx; + if (m > fromKeys.Length) + throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); + var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash; + Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; + byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - // var tx = await rpcClient.MakeTransaction(script, signers) - // .AddMultiSig(fromKeys, m, pubKeys) - // .SignAsync(); + Transaction tx = await rpcClient.MakeTransaction(script, signers) + .AddMultiSig(fromKeys, m, pubKeys) + .SignAsync().ConfigureAwait(false); - // return tx; + return tx; } } } diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 4c302d5fb..b9af7a499 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -12,81 +12,131 @@ namespace Neo.Network.RPC { - /// - /// This class helps to create transaction with RPC API. - /// - public class TransactionManager + public class MakeTransactionContext { - private readonly RpcClient rpcClient; - private readonly PolicyAPI policyAPI; - private readonly Nep5API nep5API; - private class SignItem { public Contract Contract; public HashSet KeyPairs; } - /// - /// The Transaction context to manage the witnesses - /// - private ContractParametersContext context; - - /// - /// This container stores the keys for sign the transaction - /// - private List signStore; - - /// - /// The Transaction managed by this class - /// - public Transaction Tx { get; private set; } - - /// - /// TransactionManager Constructor - /// - /// the RPC client to call NEO RPC API - /// the account script hash of sender - public TransactionManager(RpcClient rpc) - { - rpcClient = rpc; - policyAPI = new PolicyAPI(rpc); - nep5API = new Nep5API(rpc); - } + private readonly RpcClient rpcClient; + private readonly Transaction transaction; + private readonly ContractParametersContext context; + private readonly List signStore = new List(); + private Task task = Task.FromResult(0); - /// - /// Create an unsigned Transaction object with given parameters. - /// - /// Transaction Script - /// Transaction Attributes - /// - public async Task MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + public MakeTransactionContext(RpcClient rpcClient, byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) { + this.rpcClient = rpcClient; + var random = new Random(); - uint height = await rpcClient.GetBlockCount() - 1; - Tx = new Transaction + transaction = new Transaction { Version = 0, Nonce = (uint)random.Next(), Script = script, - Signers = signers, - ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement, + Signers = signers ?? Array.Empty(), Attributes = attributes ?? Array.Empty(), }; - RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); - Tx.SystemFee = long.Parse(result.GasConsumed); - context = new ContractParametersContext(Tx); - signStore = new List(); + context = new ContractParametersContext(transaction); + + QueueWork(async t => + { + uint height = await rpcClient.GetBlockCount().ConfigureAwait(false) - 1; + transaction.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; + }); + + QueueWork(async t => + { + RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); + transaction.SystemFee = long.Parse(result.GasConsumed); + }); + } + + public MakeTransactionContext AddSignature(KeyPair key) + { + var contract = Contract.CreateSignatureContract(key.PublicKey); + QueueWork(() => { AddSignItem(contract, key); } ); + return this; + } + + public MakeTransactionContext AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) + { + Contract contract = Contract.CreateMultiSigContract(m, publicKeys); + QueueWork(() => { AddSignItem(contract, key); } ); + return this; + } + + public MakeTransactionContext AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) + { + Contract contract = Contract.CreateMultiSigContract(m, publicKeys); + for (int i = 0; i < keys.Length; i++) + { + KeyPair key = keys[i]; + QueueWork(() => { AddSignItem(contract, key); } ); + } + return this; + } + public MakeTransactionContext AddWitness(Contract contract, params object[] parameters) + { + QueueWork(() => { + if (!context.Add(contract, parameters)) + { + throw new Exception("AddWitness failed!"); + }; + }); return this; } - /// - /// Calculate NetworkFee - /// - /// + public MakeTransactionContext AddWitness(UInt160 scriptHash, params object[] parameters) + { + var contract = Contract.Create(scriptHash); + return AddWitness(contract, parameters); + } + + public async Task SignAsync() + { + // wait for all queued work to complete + await task; + + // Calculate NetworkFee + transaction.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); + var gasBalance = await new Nep5API(rpcClient).BalanceOf(NativeContract.GAS.Hash, transaction.Sender).ConfigureAwait(false); + if (gasBalance < transaction.SystemFee + transaction.NetworkFee) + throw new InvalidOperationException($"Insufficient GAS in address: {transaction.Sender.ToAddress()}"); + + // Sign with signStore + for (int i = 0; i < signStore.Count; i++) + { + SignItem item = signStore[i]; + foreach (var key in item.KeyPairs) + { + byte[] signature = transaction.Sign(key); + if (!context.AddSignature(item.Contract, key.PublicKey, signature)) + { + throw new Exception("AddSignature failed!"); + } + } + } + + // Verify witness count + if (!context.Completed) + { + throw new Exception($"Please add signature or witness first!"); + } + transaction.Witnesses = context.GetWitnesses(); + return transaction; + } + private async Task CalculateNetworkFee() { long networkFee = 0; - UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); - int size = Transaction.HeaderSize + Tx.Signers.GetVarSize() + Tx.Attributes.GetVarSize() + Tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); + UInt160[] hashes = transaction.GetScriptHashesForVerifying(null); + int size = Transaction.HeaderSize + + transaction.Signers.GetVarSize() + + transaction.Attributes.GetVarSize() + + transaction.Script.GetVarSize() + + IO.Helper.GetVarSize(hashes.Length); + foreach (UInt160 hash in hashes) { byte[] witness_script = null; @@ -106,53 +156,14 @@ private async Task CalculateNetworkFee() if (witness_script is null) continue; networkFee += Wallet.CalculateNetworkFee(witness_script, ref size); } - networkFee += size * (await policyAPI.GetFeePerByte().ConfigureAwait(false)); - return networkFee; - } - - /// - /// Add Signature - /// - /// The KeyPair to sign transction - /// - public TransactionManager AddSignature(KeyPair key) - { - var contract = Contract.CreateSignatureContract(key.PublicKey); - AddSignItem(contract, key); - return this; - } - - /// - /// Add Multi-Signature - /// - /// The KeyPair to sign transction - /// The least count of signatures needed for multiple signature contract - /// The Public Keys construct the multiple signature contract - public TransactionManager AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) - { - Contract contract = Contract.CreateMultiSigContract(m, publicKeys); - AddSignItem(contract, key); - return this; - } - /// - /// Add Multi-Signature - /// - /// The KeyPairs to sign transction - /// The least count of signatures needed for multiple signature contract - /// The Public Keys construct the multiple signature contract - public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) - { - foreach (var key in keys) - { - AddMultiSig(key, m, publicKeys); - } - return this; + networkFee += size * (await new PolicyAPI(rpcClient).GetFeePerByte().ConfigureAwait(false)); + return networkFee; } private void AddSignItem(Contract contract, KeyPair key) { - if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) + if (!transaction.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) { throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); } @@ -168,60 +179,230 @@ private void AddSignItem(Contract contract, KeyPair key) } } - /// - /// Add Witness with contract - /// - /// The witness verification contract - /// The witness invocation parameters - public TransactionManager AddWitness(Contract contract, params object[] parameters) + private void QueueWork(Func action) { - if (!context.Add(contract, parameters)) - { - throw new Exception("AddWitness failed!"); - }; - return this; + task = task.ContinueWith(action, TaskContinuationOptions.OnlyOnRanToCompletion); } - /// - /// Add Witness with scriptHash - /// - /// The witness verification contract hash - /// The witness invocation parameters - public TransactionManager AddWitness(UInt160 scriptHash, params object[] parameters) + private void QueueWork(Action action) { - var contract = Contract.Create(scriptHash); - return AddWitness(contract, parameters); + QueueWork(_ => { + action(); + return Task.FromResult(0); + }); } + } - /// - /// Verify Witness count and add witnesses - /// - public async Task Sign() - { - // Calculate NetworkFee - Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); - var gasBalance = await nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); - if (gasBalance < Tx.SystemFee + Tx.NetworkFee) - throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); + /// + /// This class helps to create transaction with RPC API. + /// + // public class TransactionManager + // { + // private readonly RpcClient rpcClient; + // private readonly PolicyAPI policyAPI; + // private readonly Nep5API nep5API; - // Sign with signStore - foreach (var item in signStore) - foreach (var key in item.KeyPairs) - { - byte[] signature = Tx.Sign(key); - if (!context.AddSignature(item.Contract, key.PublicKey, signature)) - { - throw new Exception("AddSignature failed!"); - } - } + // private class SignItem { public Contract Contract; public HashSet KeyPairs; } - // Verify witness count - if (!context.Completed) - { - throw new Exception($"Please add signature or witness first!"); - } - Tx.Witnesses = context.GetWitnesses(); - return this; - } - } + // /// + // /// The Transaction context to manage the witnesses + // /// + // private ContractParametersContext context; + + // /// + // /// This container stores the keys for sign the transaction + // /// + // private List signStore; + + // /// + // /// The Transaction managed by this class + // /// + // public Transaction Tx { get; private set; } + + // /// + // /// TransactionManager Constructor + // /// + // /// the RPC client to call NEO RPC API + // /// the account script hash of sender + // public TransactionManager(RpcClient rpc) + // { + // rpcClient = rpc; + // policyAPI = new PolicyAPI(rpc); + // nep5API = new Nep5API(rpc); + // } + + // /// + // /// Create an unsigned Transaction object with given parameters. + // /// + // /// Transaction Script + // /// Transaction Attributes + // /// + // public async Task MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + // { + // var random = new Random(); + // uint height = await rpcClient.GetBlockCount() - 1; + // Tx = new Transaction + // { + // Version = 0, + // Nonce = (uint)random.Next(), + // Script = script, + // Signers = signers, + // ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement, + // Attributes = attributes ?? Array.Empty(), + // }; + + // RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); + // Tx.SystemFee = long.Parse(result.GasConsumed); + // context = new ContractParametersContext(Tx); + // signStore = new List(); + + // return this; + // } + + // /// + // /// Calculate NetworkFee + // /// + // /// + // private async Task CalculateNetworkFee() + // { + // long networkFee = 0; + // UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); + // int size = Transaction.HeaderSize + Tx.Signers.GetVarSize() + Tx.Attributes.GetVarSize() + Tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); + // foreach (UInt160 hash in hashes) + // { + // byte[] witness_script = null; + + // // calculate NetworkFee + // witness_script = signStore.FirstOrDefault(p => p.Contract.ScriptHash == hash)?.Contract?.Script; + // if (witness_script is null || witness_script.Length == 0) + // { + // try + // { + // var contractState = await rpcClient.GetContractState(hash.ToString()).ConfigureAwait(false); + // witness_script = contractState?.Script; + // } + // catch { } + // } + + // if (witness_script is null) continue; + // networkFee += Wallet.CalculateNetworkFee(witness_script, ref size); + // } + // networkFee += size * (await policyAPI.GetFeePerByte().ConfigureAwait(false)); + // return networkFee; + // } + + // /// + // /// Add Signature + // /// + // /// The KeyPair to sign transction + // /// + // public TransactionManager AddSignature(KeyPair key) + // { + // var contract = Contract.CreateSignatureContract(key.PublicKey); + // AddSignItem(contract, key); + // return this; + // } + + // /// + // /// Add Multi-Signature + // /// + // /// The KeyPair to sign transction + // /// The least count of signatures needed for multiple signature contract + // /// The Public Keys construct the multiple signature contract + // public TransactionManager AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) + // { + // Contract contract = Contract.CreateMultiSigContract(m, publicKeys); + // AddSignItem(contract, key); + // return this; + // } + + // /// + // /// Add Multi-Signature + // /// + // /// The KeyPairs to sign transction + // /// The least count of signatures needed for multiple signature contract + // /// The Public Keys construct the multiple signature contract + // public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) + // { + // foreach (var key in keys) + // { + // AddMultiSig(key, m, publicKeys); + // } + // return this; + // } + + // private void AddSignItem(Contract contract, KeyPair key) + // { + // if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) + // { + // throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); + // } + + // SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); + // if (item is null) + // { + // signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); + // } + // else if (!item.KeyPairs.Contains(key)) + // { + // item.KeyPairs.Add(key); + // } + // } + + // /// + // /// Add Witness with contract + // /// + // /// The witness verification contract + // /// The witness invocation parameters + // public TransactionManager AddWitness(Contract contract, params object[] parameters) + // { + // if (!context.Add(contract, parameters)) + // { + // throw new Exception("AddWitness failed!"); + // }; + // return this; + // } + + // /// + // /// Add Witness with scriptHash + // /// + // /// The witness verification contract hash + // /// The witness invocation parameters + // public TransactionManager AddWitness(UInt160 scriptHash, params object[] parameters) + // { + // var contract = Contract.Create(scriptHash); + // return AddWitness(contract, parameters); + // } + + // /// + // /// Verify Witness count and add witnesses + // /// + // public async Task Sign() + // { + // // Calculate NetworkFee + // Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); + // var gasBalance = await nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); + // if (gasBalance < Tx.SystemFee + Tx.NetworkFee) + // throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); + + // // Sign with signStore + // foreach (var item in signStore) + // foreach (var key in item.KeyPairs) + // { + // byte[] signature = Tx.Sign(key); + // if (!context.AddSignature(item.Contract, key.PublicKey, signature)) + // { + // throw new Exception("AddSignature failed!"); + // } + // } + + // // Verify witness count + // if (!context.Completed) + // { + // throw new Exception($"Please add signature or witness first!"); + // } + // Tx.Witnesses = context.GetWitnesses(); + // return this; + // } + // } } diff --git a/src/RpcClient/Utility.cs b/src/RpcClient/Utility.cs index 6bca96b12..6f52434f5 100644 --- a/src/RpcClient/Utility.cs +++ b/src/RpcClient/Utility.cs @@ -16,6 +16,11 @@ namespace Neo.Network.RPC { public static class Utility { + public static MakeTransactionContext MakeTransaction(this RpcClient rpcClient, byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + { + return new MakeTransactionContext(rpcClient, script, signers, attributes); + } + private static (BigInteger numerator, BigInteger denominator) Fraction(decimal d) { int[] bits = decimal.GetBits(d); diff --git a/src/RpcClient/WalletAPI.cs b/src/RpcClient/WalletAPI.cs index 026bd881c..775494209 100644 --- a/src/RpcClient/WalletAPI.cs +++ b/src/RpcClient/WalletAPI.cs @@ -118,7 +118,7 @@ public async Task ClaimGas(KeyPair keyPair) { UInt160 toHash = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(); BigInteger balance = await nep5API.BalanceOf(NativeContract.NEO.Hash, toHash).ConfigureAwait(false); - Transaction transaction = nep5API.CreateTransferTx(NativeContract.NEO.Hash, keyPair, toHash, balance); + Transaction transaction = await nep5API.CreateTransferTx(NativeContract.NEO.Hash, keyPair, toHash, balance).ConfigureAwait(false); await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } @@ -153,7 +153,7 @@ public async Task Transfer(string tokenHash, string fromKey, string /// public async Task Transfer(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger) { - Transaction transaction = nep5API.CreateTransferTx(scriptHash, from, to, amountInteger); + Transaction transaction = await nep5API.CreateTransferTx(scriptHash, from, to, amountInteger).ConfigureAwait(false); await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } @@ -170,7 +170,7 @@ public async Task Transfer(UInt160 scriptHash, KeyPair from, UInt16 /// public async Task Transfer(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger) { - Transaction transaction = nep5API.CreateTransferTx(scriptHash, m, pubKeys, keys, to, amountInteger); + Transaction transaction = await nep5API.CreateTransferTx(scriptHash, m, pubKeys, keys, to, amountInteger).ConfigureAwait(false); await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); return transaction; } diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 803c37e7d..08f7cfb65 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -21,7 +21,7 @@ namespace Neo.Network.RPC.Tests [TestClass] public class UT_TransactionManager { - TransactionManager txManager; + // TransactionManager txManager; Mock rpcClientMock; Mock multiSigMock; KeyPair keyPair1; From 160a3682686b36525d30def452c3d34f548be953 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 16:58:14 -0700 Subject: [PATCH 04/21] mistake in GetBlock/GetBlockHeader --- src/RpcClient/RpcClient.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 894c7da81..2f13ecbd6 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -123,8 +123,8 @@ public async Task GetBlockHex(string hashOrIndex) public async Task GetBlock(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) - ? await RpcSendAsync("getblock", index).ConfigureAwait(false) - : await RpcSendAsync("getblock", hashOrIndex).ConfigureAwait(false); + ? await RpcSendAsync("getblock", index, true).ConfigureAwait(false) + : await RpcSendAsync("getblock", hashOrIndex, true).ConfigureAwait(false); return RpcBlock.FromJson(result); } @@ -164,8 +164,8 @@ public async Task GetBlockHeaderHex(string hashOrIndex) public async Task GetBlockHeader(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) - ? await RpcSendAsync("getblockheader", index).ConfigureAwait(false) - : await RpcSendAsync("getblockheader", hashOrIndex).ConfigureAwait(false); + ? await RpcSendAsync("getblockheader", index, true).ConfigureAwait(false) + : await RpcSendAsync("getblockheader", hashOrIndex, true).ConfigureAwait(false); return RpcBlockHeader.FromJson(result); } From 639e87e29e118c9ee835ec04eeeab92f6bd06ba9 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 17:29:49 -0700 Subject: [PATCH 05/21] rework TransactionManager to be closer to original --- src/RpcClient/ContractClient.cs | 2 +- src/RpcClient/Nep5API.cs | 6 +- src/RpcClient/RpcClient.cs | 2 +- src/RpcClient/TransactionManager.cs | 304 ++++++++-------------------- src/RpcClient/Utility.cs | 5 - 5 files changed, 86 insertions(+), 233 deletions(-) diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index 5964fad8c..e3d52be26 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -56,7 +56,7 @@ public async Task CreateDeployContractTx(byte[] contractScript, Con UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - Transaction tx = await rpcClient + Transaction tx = await new TransactionManager(rpcClient) .MakeTransaction(script, signers) .AddSignature(key) .SignAsync().ConfigureAwait(false); diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index f9b4f4472..a3b9285ba 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -118,7 +118,8 @@ public async Task CreateTransferTx(UInt160 scriptHash, KeyPair from Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - var tx = await rpcClient.MakeTransaction(script, signers) + var tx = await new TransactionManager(rpcClient) + .MakeTransaction(script, signers) .AddSignature(fromKey) .SignAsync().ConfigureAwait(false); @@ -144,7 +145,8 @@ public async Task CreateTransferTx(UInt160 scriptHash, int m, ECPoi byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - Transaction tx = await rpcClient.MakeTransaction(script, signers) + Transaction tx = await new TransactionManager(rpcClient) + .MakeTransaction(script, signers) .AddMultiSig(fromKeys, m, pubKeys) .SignAsync().ConfigureAwait(false); diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 2f13ecbd6..f7a4e30e2 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -67,7 +67,7 @@ public async Task SendAsync(RpcRequest request) if (disposedValue) throw new ObjectDisposedException(nameof(RpcClient)); var requestJson = request.ToJson().ToString(); - using var result = await httpClient.PostAsync(baseAddress, new StringContent(requestJson, Encoding.UTF8)).ConfigureAwait(false); + using var result = await httpClient.PostAsync(baseAddress, new StringContent(requestJson, Encoding.UTF8)).ConfigureAwait(false); var content = await result.Content.ReadAsStringAsync(); var response = RpcResponse.FromJson(JObject.Parse(content)); response.RawResponse = content; diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index b9af7a499..8b0235386 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -12,31 +12,64 @@ namespace Neo.Network.RPC { - public class MakeTransactionContext + /// + /// This class helps to create transaction with RPC API. + /// + public class TransactionManager { private class SignItem { public Contract Contract; public HashSet KeyPairs; } private readonly RpcClient rpcClient; private readonly Transaction transaction; + /// + /// The Transaction context to manage the witnesses + /// private readonly ContractParametersContext context; + /// + /// This container stores the keys for sign the transaction + /// private readonly List signStore = new List(); + + // task to manage fluent async operations private Task task = Task.FromResult(0); - public MakeTransactionContext(RpcClient rpcClient, byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + /// + /// The Transaction managed by this class + /// + public Transaction Tx => transaction; + + /// + /// TransactionManager Constructor + /// + /// the RPC client to call NEO RPC API + public TransactionManager(RpcClient rpcClient) { this.rpcClient = rpcClient; var random = new Random(); - transaction = new Transaction + this.transaction = new Transaction { Version = 0, Nonce = (uint)random.Next(), - Script = script, - Signers = signers ?? Array.Empty(), - Attributes = attributes ?? Array.Empty(), + Script = Array.Empty(), + Signers = Array.Empty(), + Attributes = Array.Empty(), }; context = new ContractParametersContext(transaction); + } + + /// + /// Create an unsigned Transaction object with given parameters. + /// + /// Transaction Script + /// Transaction Attributes + /// + public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + { + transaction.Script = script; + transaction.Signers = signers ?? Array.Empty(); + transaction.Attributes = attributes ?? Array.Empty(); QueueWork(async t => { @@ -49,23 +82,42 @@ public MakeTransactionContext(RpcClient rpcClient, byte[] script, Signer[] signe RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); transaction.SystemFee = long.Parse(result.GasConsumed); }); + + return this; } - public MakeTransactionContext AddSignature(KeyPair key) + /// + /// Add Signature + /// + /// The KeyPair to sign transction + /// + public TransactionManager AddSignature(KeyPair key) { var contract = Contract.CreateSignatureContract(key.PublicKey); QueueWork(() => { AddSignItem(contract, key); } ); return this; } - public MakeTransactionContext AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) + /// + /// Add Multi-Signature + /// + /// The KeyPair to sign transction + /// The least count of signatures needed for multiple signature contract + /// The Public Keys construct the multiple signature contract + public TransactionManager AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) { Contract contract = Contract.CreateMultiSigContract(m, publicKeys); QueueWork(() => { AddSignItem(contract, key); } ); return this; } - public MakeTransactionContext AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) + /// + /// Add Multi-Signature + /// + /// The KeyPairs to sign transction + /// The least count of signatures needed for multiple signature contract + /// The Public Keys construct the multiple signature contract + public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) { Contract contract = Contract.CreateMultiSigContract(m, publicKeys); for (int i = 0; i < keys.Length; i++) @@ -76,7 +128,12 @@ public MakeTransactionContext AddMultiSig(KeyPair[] keys, int m, params ECPoint[ return this; } - public MakeTransactionContext AddWitness(Contract contract, params object[] parameters) + /// + /// Add Witness with contract + /// + /// The witness verification contract + /// The witness invocation parameters + public TransactionManager AddWitness(Contract contract, params object[] parameters) { QueueWork(() => { if (!context.Add(contract, parameters)) @@ -87,12 +144,20 @@ public MakeTransactionContext AddWitness(Contract contract, params object[] para return this; } - public MakeTransactionContext AddWitness(UInt160 scriptHash, params object[] parameters) + /// + /// Add Witness with scriptHash + /// + /// The witness verification contract hash + /// The witness invocation parameters + public TransactionManager AddWitness(UInt160 scriptHash, params object[] parameters) { var contract = Contract.Create(scriptHash); return AddWitness(contract, parameters); } + /// + /// Verify Witness count and add witnesses + /// public async Task SignAsync() { // wait for all queued work to complete @@ -127,6 +192,10 @@ public async Task SignAsync() return transaction; } + /// + /// Calculate NetworkFee + /// + /// private async Task CalculateNetworkFee() { long networkFee = 0; @@ -192,217 +261,4 @@ private void QueueWork(Action action) }); } } - - /// - /// This class helps to create transaction with RPC API. - /// - // public class TransactionManager - // { - // private readonly RpcClient rpcClient; - // private readonly PolicyAPI policyAPI; - // private readonly Nep5API nep5API; - - // private class SignItem { public Contract Contract; public HashSet KeyPairs; } - - // /// - // /// The Transaction context to manage the witnesses - // /// - // private ContractParametersContext context; - - // /// - // /// This container stores the keys for sign the transaction - // /// - // private List signStore; - - // /// - // /// The Transaction managed by this class - // /// - // public Transaction Tx { get; private set; } - - // /// - // /// TransactionManager Constructor - // /// - // /// the RPC client to call NEO RPC API - // /// the account script hash of sender - // public TransactionManager(RpcClient rpc) - // { - // rpcClient = rpc; - // policyAPI = new PolicyAPI(rpc); - // nep5API = new Nep5API(rpc); - // } - - // /// - // /// Create an unsigned Transaction object with given parameters. - // /// - // /// Transaction Script - // /// Transaction Attributes - // /// - // public async Task MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) - // { - // var random = new Random(); - // uint height = await rpcClient.GetBlockCount() - 1; - // Tx = new Transaction - // { - // Version = 0, - // Nonce = (uint)random.Next(), - // Script = script, - // Signers = signers, - // ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement, - // Attributes = attributes ?? Array.Empty(), - // }; - - // RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); - // Tx.SystemFee = long.Parse(result.GasConsumed); - // context = new ContractParametersContext(Tx); - // signStore = new List(); - - // return this; - // } - - // /// - // /// Calculate NetworkFee - // /// - // /// - // private async Task CalculateNetworkFee() - // { - // long networkFee = 0; - // UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); - // int size = Transaction.HeaderSize + Tx.Signers.GetVarSize() + Tx.Attributes.GetVarSize() + Tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); - // foreach (UInt160 hash in hashes) - // { - // byte[] witness_script = null; - - // // calculate NetworkFee - // witness_script = signStore.FirstOrDefault(p => p.Contract.ScriptHash == hash)?.Contract?.Script; - // if (witness_script is null || witness_script.Length == 0) - // { - // try - // { - // var contractState = await rpcClient.GetContractState(hash.ToString()).ConfigureAwait(false); - // witness_script = contractState?.Script; - // } - // catch { } - // } - - // if (witness_script is null) continue; - // networkFee += Wallet.CalculateNetworkFee(witness_script, ref size); - // } - // networkFee += size * (await policyAPI.GetFeePerByte().ConfigureAwait(false)); - // return networkFee; - // } - - // /// - // /// Add Signature - // /// - // /// The KeyPair to sign transction - // /// - // public TransactionManager AddSignature(KeyPair key) - // { - // var contract = Contract.CreateSignatureContract(key.PublicKey); - // AddSignItem(contract, key); - // return this; - // } - - // /// - // /// Add Multi-Signature - // /// - // /// The KeyPair to sign transction - // /// The least count of signatures needed for multiple signature contract - // /// The Public Keys construct the multiple signature contract - // public TransactionManager AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) - // { - // Contract contract = Contract.CreateMultiSigContract(m, publicKeys); - // AddSignItem(contract, key); - // return this; - // } - - // /// - // /// Add Multi-Signature - // /// - // /// The KeyPairs to sign transction - // /// The least count of signatures needed for multiple signature contract - // /// The Public Keys construct the multiple signature contract - // public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] publicKeys) - // { - // foreach (var key in keys) - // { - // AddMultiSig(key, m, publicKeys); - // } - // return this; - // } - - // private void AddSignItem(Contract contract, KeyPair key) - // { - // if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) - // { - // throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); - // } - - // SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); - // if (item is null) - // { - // signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); - // } - // else if (!item.KeyPairs.Contains(key)) - // { - // item.KeyPairs.Add(key); - // } - // } - - // /// - // /// Add Witness with contract - // /// - // /// The witness verification contract - // /// The witness invocation parameters - // public TransactionManager AddWitness(Contract contract, params object[] parameters) - // { - // if (!context.Add(contract, parameters)) - // { - // throw new Exception("AddWitness failed!"); - // }; - // return this; - // } - - // /// - // /// Add Witness with scriptHash - // /// - // /// The witness verification contract hash - // /// The witness invocation parameters - // public TransactionManager AddWitness(UInt160 scriptHash, params object[] parameters) - // { - // var contract = Contract.Create(scriptHash); - // return AddWitness(contract, parameters); - // } - - // /// - // /// Verify Witness count and add witnesses - // /// - // public async Task Sign() - // { - // // Calculate NetworkFee - // Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); - // var gasBalance = await nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); - // if (gasBalance < Tx.SystemFee + Tx.NetworkFee) - // throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); - - // // Sign with signStore - // foreach (var item in signStore) - // foreach (var key in item.KeyPairs) - // { - // byte[] signature = Tx.Sign(key); - // if (!context.AddSignature(item.Contract, key.PublicKey, signature)) - // { - // throw new Exception("AddSignature failed!"); - // } - // } - - // // Verify witness count - // if (!context.Completed) - // { - // throw new Exception($"Please add signature or witness first!"); - // } - // Tx.Witnesses = context.GetWitnesses(); - // return this; - // } - // } } diff --git a/src/RpcClient/Utility.cs b/src/RpcClient/Utility.cs index 6f52434f5..6bca96b12 100644 --- a/src/RpcClient/Utility.cs +++ b/src/RpcClient/Utility.cs @@ -16,11 +16,6 @@ namespace Neo.Network.RPC { public static class Utility { - public static MakeTransactionContext MakeTransaction(this RpcClient rpcClient, byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) - { - return new MakeTransactionContext(rpcClient, script, signers, attributes); - } - private static (BigInteger numerator, BigInteger denominator) Fraction(decimal d) { int[] bits = decimal.GetBits(d); From 73c4465e23c2e0a19aaa653c295aa4c3eb6dd919 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 17:46:13 -0700 Subject: [PATCH 06/21] more unit tests (2 still failing) --- tests/Neo.Network.RPC.Tests/AssertEx.cs | 36 +++ .../UT_ContractClient.cs | 4 +- tests/Neo.Network.RPC.Tests/UT_Nep5API.cs | 4 +- .../UT_TransactionManager.cs | 224 +++++++++--------- 4 files changed, 152 insertions(+), 116 deletions(-) create mode 100644 tests/Neo.Network.RPC.Tests/AssertEx.cs diff --git a/tests/Neo.Network.RPC.Tests/AssertEx.cs b/tests/Neo.Network.RPC.Tests/AssertEx.cs new file mode 100644 index 000000000..4693ee82a --- /dev/null +++ b/tests/Neo.Network.RPC.Tests/AssertEx.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading.Tasks; + +namespace Neo.Network.RPC.Tests +{ + public static class AssertEx + { + public static async Task ThrowsAsync(Func action, bool allowDerivedTypes = true) + where TException : Exception + { + try + { + await action(); + } + catch (Exception ex) + { + if (allowDerivedTypes && !(ex is TException)) + throw new Exception("Delegate threw exception of type " + + ex.GetType().Name + ", but " + typeof(TException).Name + + " or a derived type was expected.", ex); + if (!allowDerivedTypes && ex.GetType() != typeof(TException)) + throw new Exception("Delegate threw exception of type " + + ex.GetType().Name + ", but " + typeof(TException).Name + + " was expected.", ex); + return (TException)ex; + } + throw new Exception("Delegate did not throw expected exception " + + typeof(TException).Name + "."); + } + + public static Task ThrowsAsync(Func action) + { + return ThrowsAsync(action, true); + } + } +} diff --git a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs index 0208e5cdc..2c588761d 100644 --- a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs @@ -37,7 +37,7 @@ public async Task TestInvoke() } [TestMethod] - public void TestDeployContract() + public async Task TestDeployContract() { byte[] script; var manifest = new ContractManifest() @@ -65,7 +65,7 @@ public void TestDeployContract() UT_TransactionManager.MockInvokeScript(rpcClientMock, script, new ContractParameter()); ContractClient contractClient = new ContractClient(rpcClientMock.Object); - var result = contractClient.CreateDeployContractTx(new byte[1], manifest, keyPair1); + var result = await contractClient.CreateDeployContractTx(new byte[1], manifest, keyPair1); Assert.IsNotNull(result); } diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs index ba0a5972e..546729c1b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs @@ -100,12 +100,12 @@ public async Task TestGetTokenInfo() } [TestMethod] - public void TestTransfer() + public async Task TestTransfer() { byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000)); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter()); - var result = nep5API.CreateTransferTx(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000)); + var result = await nep5API.CreateTransferTx(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000)); Assert.IsNotNull(result); } } diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 08f7cfb65..37c71bda1 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -21,7 +21,7 @@ namespace Neo.Network.RPC.Tests [TestClass] public class UT_TransactionManager { - // TransactionManager txManager; + TransactionManager txManager; Mock rpcClientMock; Mock multiSigMock; KeyPair keyPair1; @@ -107,116 +107,116 @@ public static void MockInvokeScript(Mock mockClient, byte[] script, p .Verifiable(); } - // [TestMethod] - // public void TestMakeTransaction() - // { - // txManager = new TransactionManager(rpcClientMock.Object); - - // Signer[] signers = new Signer[1] - // { - // new Signer - // { - // Account = sender, - // Scopes= WitnessScope.Global - // } - // }; - - // byte[] script = new byte[1]; - // txManager.MakeTransaction(script, signers); - - // var tx = txManager.Tx; - // Assert.AreEqual(WitnessScope.Global, tx.Signers[0].Scopes); - // } - - // [TestMethod] - // public void TestSign() - // { - // txManager = new TransactionManager(rpcClientMock.Object); - - // Signer[] signers = new Signer[1] - // { - // new Signer - // { - // Account = sender, - // Scopes = WitnessScope.Global - // } - // }; - - // byte[] script = new byte[1]; - // txManager.MakeTransaction(script, signers) - // .AddSignature(keyPair1) - // .Sign(); - - // // get signature from Witnesses - // var tx = txManager.Tx; - // byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray(); - - // Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey)); - // // verify network fee and system fee - // long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1; - // Assert.AreEqual(networkFee, tx.NetworkFee); - // Assert.AreEqual(100, tx.SystemFee); - - // // duplicate sign should not add new witness - // txManager.AddSignature(keyPair1).Sign(); - // Assert.AreEqual(1, txManager.Tx.Witnesses.Length); - - // // throw exception when the KeyPair is wrong - // Assert.ThrowsException(() => txManager.AddSignature(keyPair2).Sign()); - // } - - // [TestMethod] - // public void TestSignMulti() - // { - // txManager = new TransactionManager(multiSigMock.Object); - - // // Cosigner needs multi signature - // Signer[] signers = new Signer[1] - // { - // new Signer - // { - // Account = multiHash, - // Scopes = WitnessScope.Global - // } - // }; - - // byte[] script = new byte[1]; - // txManager.MakeTransaction(script, signers) - // .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey) - // .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey) - // .Sign(); - // } - - // [TestMethod] - // public void TestAddWitness() - // { - // txManager = new TransactionManager(rpcClientMock.Object); - - // // Cosigner as contract scripthash - // Signer[] signers = new Signer[2] - // { - // new Signer - // { - // Account = sender, - // Scopes = WitnessScope.Global - // }, - // new Signer - // { - // Account = UInt160.Zero, - // Scopes = WitnessScope.Global - // } - // }; - - // byte[] script = new byte[1]; - // txManager.MakeTransaction(script, signers); - // txManager.AddWitness(UInt160.Zero); - // txManager.AddSignature(keyPair1); - // txManager.Sign(); - - // var tx = txManager.Tx; - // Assert.AreEqual(2, tx.Witnesses.Length); - // Assert.AreEqual(41, tx.Witnesses[0].VerificationScript.Length); - // Assert.AreEqual(66, tx.Witnesses[0].InvocationScript.Length); - // } + [TestMethod] + public void TestMakeTransaction() + { + txManager = new TransactionManager(rpcClientMock.Object); + + Signer[] signers = new Signer[1] + { + new Signer + { + Account = sender, + Scopes= WitnessScope.Global + } + }; + + byte[] script = new byte[1]; + txManager.MakeTransaction(script, signers); + + var tx = txManager.Tx; + Assert.AreEqual(WitnessScope.Global, tx.Signers[0].Scopes); + } + + [TestMethod] + public async Task TestSign() + { + txManager = new TransactionManager(rpcClientMock.Object); + + Signer[] signers = new Signer[1] + { + new Signer + { + Account = sender, + Scopes = WitnessScope.Global + } + }; + + byte[] script = new byte[1]; + await txManager.MakeTransaction(script, signers) + .AddSignature(keyPair1) + .SignAsync(); + + // get signature from Witnesses + var tx = txManager.Tx; + byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray(); + + Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey)); + // verify network fee and system fee + long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1; + Assert.AreEqual(networkFee, tx.NetworkFee); + Assert.AreEqual(100, tx.SystemFee); + + // duplicate sign should not add new witness + await txManager.AddSignature(keyPair1).SignAsync(); + Assert.AreEqual(1, txManager.Tx.Witnesses.Length); + + // throw exception when the KeyPair is wrong + await AssertEx.ThrowsAsync(async () => await txManager.AddSignature(keyPair2).SignAsync()); + } + + [TestMethod] + public async Task TestSignMulti() + { + txManager = new TransactionManager(multiSigMock.Object); + + // Cosigner needs multi signature + Signer[] signers = new Signer[1] + { + new Signer + { + Account = multiHash, + Scopes = WitnessScope.Global + } + }; + + byte[] script = new byte[1]; + await txManager.MakeTransaction(script, signers) + .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey) + .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey) + .SignAsync(); + } + + [TestMethod] + public async Task TestAddWitness() + { + txManager = new TransactionManager(rpcClientMock.Object); + + // Cosigner as contract scripthash + Signer[] signers = new Signer[2] + { + new Signer + { + Account = sender, + Scopes = WitnessScope.Global + }, + new Signer + { + Account = UInt160.Zero, + Scopes = WitnessScope.Global + } + }; + + byte[] script = new byte[1]; + txManager.MakeTransaction(script, signers); + txManager.AddWitness(UInt160.Zero); + txManager.AddSignature(keyPair1); + await txManager.SignAsync(); + + var tx = txManager.Tx; + Assert.AreEqual(2, tx.Witnesses.Length); + Assert.AreEqual(41, tx.Witnesses[0].VerificationScript.Length); + Assert.AreEqual(66, tx.Witnesses[0].InvocationScript.Length); + } } } From 05b3f94d82958f0c2e619e88be7e21c7b1ced279 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 18:23:37 -0700 Subject: [PATCH 07/21] remove assertEx --- tests/Neo.Network.RPC.Tests/AssertEx.cs | 36 ------------------- .../UT_TransactionManager.cs | 25 ++++++++++++- 2 files changed, 24 insertions(+), 37 deletions(-) delete mode 100644 tests/Neo.Network.RPC.Tests/AssertEx.cs diff --git a/tests/Neo.Network.RPC.Tests/AssertEx.cs b/tests/Neo.Network.RPC.Tests/AssertEx.cs deleted file mode 100644 index 4693ee82a..000000000 --- a/tests/Neo.Network.RPC.Tests/AssertEx.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Neo.Network.RPC.Tests -{ - public static class AssertEx - { - public static async Task ThrowsAsync(Func action, bool allowDerivedTypes = true) - where TException : Exception - { - try - { - await action(); - } - catch (Exception ex) - { - if (allowDerivedTypes && !(ex is TException)) - throw new Exception("Delegate threw exception of type " + - ex.GetType().Name + ", but " + typeof(TException).Name + - " or a derived type was expected.", ex); - if (!allowDerivedTypes && ex.GetType() != typeof(TException)) - throw new Exception("Delegate threw exception of type " + - ex.GetType().Name + ", but " + typeof(TException).Name + - " was expected.", ex); - return (TException)ex; - } - throw new Exception("Delegate did not throw expected exception " + - typeof(TException).Name + "."); - } - - public static Task ThrowsAsync(Func action) - { - return ThrowsAsync(action, true); - } - } -} diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 37c71bda1..7ac7d6836 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -162,7 +162,30 @@ await txManager.MakeTransaction(script, signers) Assert.AreEqual(1, txManager.Tx.Witnesses.Length); // throw exception when the KeyPair is wrong - await AssertEx.ThrowsAsync(async () => await txManager.AddSignature(keyPair2).SignAsync()); + await ThrowsAsync(async () => await txManager.AddSignature(keyPair2).SignAsync()); + } + + static async Task ThrowsAsync(Func action, bool allowDerivedTypes = true) + where TException : Exception + { + try + { + await action(); + } + catch (Exception ex) + { + if (allowDerivedTypes && !(ex is TException)) + throw new Exception("Delegate threw exception of type " + + ex.GetType().Name + ", but " + typeof(TException).Name + + " or a derived type was expected.", ex); + if (!allowDerivedTypes && ex.GetType() != typeof(TException)) + throw new Exception("Delegate threw exception of type " + + ex.GetType().Name + ", but " + typeof(TException).Name + + " was expected.", ex); + return (TException)ex; + } + throw new Exception("Delegate did not throw expected exception " + + typeof(TException).Name + "."); } [TestMethod] From 4880d7405e44add911c777709009c96f8434d36d Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 18:24:04 -0700 Subject: [PATCH 08/21] Add ThrowsAsync comment --- tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 7ac7d6836..57777962b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -165,6 +165,7 @@ await txManager.MakeTransaction(script, signers) await ThrowsAsync(async () => await txManager.AddSignature(keyPair2).SignAsync()); } + // https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/november/async-programming-unit-testing-asynchronous-code#testing-exceptions static async Task ThrowsAsync(Func action, bool allowDerivedTypes = true) where TException : Exception { From abae491587af2bac3c77bede7661cb394e32b156 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 18:43:15 -0700 Subject: [PATCH 09/21] ReturnsAsync --- src/RpcClient/RpcClient.cs | 2 +- tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs | 6 +++--- tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index f7a4e30e2..2f13ecbd6 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -67,7 +67,7 @@ public async Task SendAsync(RpcRequest request) if (disposedValue) throw new ObjectDisposedException(nameof(RpcClient)); var requestJson = request.ToJson().ToString(); - using var result = await httpClient.PostAsync(baseAddress, new StringContent(requestJson, Encoding.UTF8)).ConfigureAwait(false); + using var result = await httpClient.PostAsync(baseAddress, new StringContent(requestJson, Encoding.UTF8)).ConfigureAwait(false); var content = await result.Content.ReadAsStringAsync(); var response = RpcResponse.FromJson(JObject.Parse(content)); response.RawResponse = content; diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 57777962b..af44353d4 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -45,7 +45,7 @@ public static Mock MockRpcClient(UInt160 sender, byte[] script) var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); // MockHeight - mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).Returns(Task.FromResult((JObject)100)).Verifiable(); + mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).ReturnsAsync(100).Verifiable(); // MockGasBalance byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); @@ -71,7 +71,7 @@ public static Mock MockMultiSig(UInt160 multiHash, byte[] script) var mockRpc = new Mock(MockBehavior.Strict, "http://seed1.neo.org:10331", null, null); // MockHeight - mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).Returns(Task.FromResult((JObject)100)).Verifiable(); + mockRpc.Setup(p => p.RpcSendAsync("getblockcount")).ReturnsAsync(100).Verifiable(); // MockGasBalance byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash); @@ -103,7 +103,7 @@ public static void MockInvokeScript(Mock mockClient, byte[] script, p }; mockClient.Setup(p => p.RpcSendAsync("invokescript", It.Is(j => j[0].AsString() == script.ToHexString()))) - .Returns(Task.FromResult(result.ToJson())) + .ReturnsAsync(result.ToJson()) .Verifiable(); } diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 5ecead29b..984f737c2 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -84,7 +84,7 @@ public async Task TestClaimGas() var json = new JObject(); json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); var tranaction = await walletAPI.ClaimGas(keyPair1.Export()); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); @@ -101,7 +101,7 @@ public async Task TestTransfer() var json = new JObject(); json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); @@ -123,7 +123,7 @@ public async Task TestTransferfromMultiSigAccount() var json = new JObject(); json["hash"] = UInt256.Zero.ToString(); - rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).Returns(Task.FromResult(json)); + rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); @@ -134,7 +134,7 @@ public async Task TestWaitTransaction() { Transaction transaction = TestUtils.GetTransaction(); rpcClientMock.Setup(p => p.RpcSendAsync("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) - .Returns(Task.FromResult(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson())); + .ReturnsAsync(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson()); var tx = await walletAPI.WaitTransaction(transaction); Assert.AreEqual(VMState.HALT, tx.VMState); From 3cd5a847f89977f6a6d8f4eed69d8f1bbe1601a7 Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 22:40:53 -0700 Subject: [PATCH 10/21] fixed last remaining test issues --- src/RpcClient/Nep5API.cs | 5 +++-- src/RpcClient/RpcClient.cs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index a3b9285ba..161b1ca0b 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -87,12 +87,13 @@ public async Task TotalSupply(UInt160 scriptHash) /// public async Task GetTokenInfo(UInt160 scriptHash) { - byte[] script = Concat(scriptHash.MakeScript("name"), + byte[] script = Concat( + scriptHash.MakeScript("name"), scriptHash.MakeScript("symbol"), scriptHash.MakeScript("decimals"), scriptHash.MakeScript("totalSupply")); - var result = await TestInvoke(scriptHash, "totalSupply").ConfigureAwait(false); + var result = await rpcClient.InvokeScript(script).ConfigureAwait(false); var stack = result.Stack; return new RpcNep5TokenInfo diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 2f13ecbd6..cba8ea1c3 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -143,7 +143,7 @@ public async Task GetBlockCount() /// public async Task GetBlockHash(int index) { - var result = await RpcSendAsync("getblockhash").ConfigureAwait(false); + var result = await RpcSendAsync("getblockhash", index).ConfigureAwait(false); return result.AsString(); } From b30fad7ec1a57ee7156502964bdb39c2a1b2d02c Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 22:47:53 -0700 Subject: [PATCH 11/21] minor TXManager cleanup --- src/RpcClient/TransactionManager.cs | 41 +++++++++++++++-------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 8b0235386..1886bc9bd 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -31,7 +31,7 @@ private class SignItem { public Contract Contract; public HashSet KeyPa private readonly List signStore = new List(); // task to manage fluent async operations - private Task task = Task.FromResult(0); + private Task fluentOperationsTask = Task.FromResult(0); /// /// The Transaction managed by this class @@ -94,7 +94,7 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null public TransactionManager AddSignature(KeyPair key) { var contract = Contract.CreateSignatureContract(key.PublicKey); - QueueWork(() => { AddSignItem(contract, key); } ); + AddSignItem(contract, key); return this; } @@ -107,7 +107,7 @@ public TransactionManager AddSignature(KeyPair key) public TransactionManager AddMultiSig(KeyPair key, int m, params ECPoint[] publicKeys) { Contract contract = Contract.CreateMultiSigContract(m, publicKeys); - QueueWork(() => { AddSignItem(contract, key); } ); + AddSignItem(contract, key); return this; } @@ -122,8 +122,7 @@ public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] pu Contract contract = Contract.CreateMultiSigContract(m, publicKeys); for (int i = 0; i < keys.Length; i++) { - KeyPair key = keys[i]; - QueueWork(() => { AddSignItem(contract, key); } ); + AddSignItem(contract, keys[i]); } return this; } @@ -161,7 +160,7 @@ public TransactionManager AddWitness(UInt160 scriptHash, params object[] paramet public async Task SignAsync() { // wait for all queued work to complete - await task; + await fluentOperationsTask; // Calculate NetworkFee transaction.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); @@ -232,25 +231,27 @@ private async Task CalculateNetworkFee() private void AddSignItem(Contract contract, KeyPair key) { - if (!transaction.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) - { - throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); - } + QueueWork(() => { + if (!transaction.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) + { + throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); + } - SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); - if (item is null) - { - signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); - } - else if (!item.KeyPairs.Contains(key)) - { - item.KeyPairs.Add(key); - } + SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); + if (item is null) + { + signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); + } + else if (!item.KeyPairs.Contains(key)) + { + item.KeyPairs.Add(key); + } + }); } private void QueueWork(Func action) { - task = task.ContinueWith(action, TaskContinuationOptions.OnlyOnRanToCompletion); + fluentOperationsTask = fluentOperationsTask.ContinueWith(action, TaskContinuationOptions.OnlyOnRanToCompletion); } private void QueueWork(Action action) From 55de42778045f2fb9f4fc4c8e2d11d1a9826924d Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 28 Aug 2020 22:51:52 -0700 Subject: [PATCH 12/21] formatting --- src/RpcClient/TransactionManager.cs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 1886bc9bd..5f975526d 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -29,7 +29,7 @@ private class SignItem { public Contract Contract; public HashSet KeyPa /// This container stores the keys for sign the transaction /// private readonly List signStore = new List(); - + // task to manage fluent async operations private Task fluentOperationsTask = Task.FromResult(0); @@ -71,19 +71,19 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null transaction.Signers = signers ?? Array.Empty(); transaction.Attributes = attributes ?? Array.Empty(); - QueueWork(async t => + QueueWork(async t => { uint height = await rpcClient.GetBlockCount().ConfigureAwait(false) - 1; transaction.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; }); - QueueWork(async t => + QueueWork(async t => { RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); transaction.SystemFee = long.Parse(result.GasConsumed); }); - - return this; + + return this; } /// @@ -134,7 +134,8 @@ public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] pu /// The witness invocation parameters public TransactionManager AddWitness(Contract contract, params object[] parameters) { - QueueWork(() => { + QueueWork(() => + { if (!context.Add(contract, parameters)) { throw new Exception("AddWitness failed!"); @@ -199,7 +200,7 @@ private async Task CalculateNetworkFee() { long networkFee = 0; UInt160[] hashes = transaction.GetScriptHashesForVerifying(null); - int size = Transaction.HeaderSize + int size = Transaction.HeaderSize + transaction.Signers.GetVarSize() + transaction.Attributes.GetVarSize() + transaction.Script.GetVarSize() @@ -231,7 +232,8 @@ private async Task CalculateNetworkFee() private void AddSignItem(Contract contract, KeyPair key) { - QueueWork(() => { + QueueWork(() => + { if (!transaction.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) { throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); @@ -246,7 +248,7 @@ private void AddSignItem(Contract contract, KeyPair key) { item.KeyPairs.Add(key); } - }); + }); } private void QueueWork(Func action) @@ -256,7 +258,8 @@ private void QueueWork(Func action) private void QueueWork(Action action) { - QueueWork(_ => { + QueueWork(_ => + { action(); return Task.FromResult(0); }); From 7119bdc43a81db58fd195e494772f6b8657b5e49 Mon Sep 17 00:00:00 2001 From: Harry Pierson Date: Sun, 30 Aug 2020 10:15:27 -0700 Subject: [PATCH 13/21] move tx contruction to MakeTransaction --- src/RpcClient/TransactionManager.cs | 60 ++++++++++++++--------------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 5f975526d..ff3c4fbc2 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -20,11 +20,12 @@ public class TransactionManager private class SignItem { public Contract Contract; public HashSet KeyPairs; } private readonly RpcClient rpcClient; - private readonly Transaction transaction; + /// /// The Transaction context to manage the witnesses /// - private readonly ContractParametersContext context; + private ContractParametersContext context; + /// /// This container stores the keys for sign the transaction /// @@ -36,7 +37,7 @@ private class SignItem { public Contract Contract; public HashSet KeyPa /// /// The Transaction managed by this class /// - public Transaction Tx => transaction; + public Transaction Tx { get; private set; } /// /// TransactionManager Constructor @@ -45,18 +46,6 @@ private class SignItem { public Contract Contract; public HashSet KeyPa public TransactionManager(RpcClient rpcClient) { this.rpcClient = rpcClient; - - var random = new Random(); - this.transaction = new Transaction - { - Version = 0, - Nonce = (uint)random.Next(), - Script = Array.Empty(), - Signers = Array.Empty(), - Attributes = Array.Empty(), - }; - - context = new ContractParametersContext(transaction); } /// @@ -67,20 +56,27 @@ public TransactionManager(RpcClient rpcClient) /// public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) { - transaction.Script = script; - transaction.Signers = signers ?? Array.Empty(); - transaction.Attributes = attributes ?? Array.Empty(); + Tx = new Transaction + { + Version = 0, + Nonce = (uint)new Random().Next(), + Script = script, + Signers = signers ?? Array.Empty(), + Attributes = attributes ?? Array.Empty(), + }; + + context = new ContractParametersContext(Tx); QueueWork(async t => { uint height = await rpcClient.GetBlockCount().ConfigureAwait(false) - 1; - transaction.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; + Tx.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; }); QueueWork(async t => { RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); - transaction.SystemFee = long.Parse(result.GasConsumed); + Tx.SystemFee = long.Parse(result.GasConsumed); }); return this; @@ -164,10 +160,10 @@ public async Task SignAsync() await fluentOperationsTask; // Calculate NetworkFee - transaction.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); - var gasBalance = await new Nep5API(rpcClient).BalanceOf(NativeContract.GAS.Hash, transaction.Sender).ConfigureAwait(false); - if (gasBalance < transaction.SystemFee + transaction.NetworkFee) - throw new InvalidOperationException($"Insufficient GAS in address: {transaction.Sender.ToAddress()}"); + Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); + var gasBalance = await new Nep5API(rpcClient).BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); + if (gasBalance < Tx.SystemFee + Tx.NetworkFee) + throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); // Sign with signStore for (int i = 0; i < signStore.Count; i++) @@ -175,7 +171,7 @@ public async Task SignAsync() SignItem item = signStore[i]; foreach (var key in item.KeyPairs) { - byte[] signature = transaction.Sign(key); + byte[] signature = Tx.Sign(key); if (!context.AddSignature(item.Contract, key.PublicKey, signature)) { throw new Exception("AddSignature failed!"); @@ -188,8 +184,8 @@ public async Task SignAsync() { throw new Exception($"Please add signature or witness first!"); } - transaction.Witnesses = context.GetWitnesses(); - return transaction; + Tx.Witnesses = context.GetWitnesses(); + return Tx; } /// @@ -199,11 +195,11 @@ public async Task SignAsync() private async Task CalculateNetworkFee() { long networkFee = 0; - UInt160[] hashes = transaction.GetScriptHashesForVerifying(null); + UInt160[] hashes = Tx.GetScriptHashesForVerifying(null); int size = Transaction.HeaderSize - + transaction.Signers.GetVarSize() - + transaction.Attributes.GetVarSize() - + transaction.Script.GetVarSize() + + Tx.Signers.GetVarSize() + + Tx.Attributes.GetVarSize() + + Tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); foreach (UInt160 hash in hashes) @@ -234,7 +230,7 @@ private void AddSignItem(Contract contract, KeyPair key) { QueueWork(() => { - if (!transaction.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) + if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) { throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); } From 202fdd0c6105e002d5d2a986aa1cdaec3117f5dd Mon Sep 17 00:00:00 2001 From: Harry Pierson Date: Sun, 30 Aug 2020 10:16:59 -0700 Subject: [PATCH 14/21] discards --- src/RpcClient/TransactionManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index ff3c4fbc2..18fe06927 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -67,13 +67,13 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null context = new ContractParametersContext(Tx); - QueueWork(async t => + QueueWork(async _ => { uint height = await rpcClient.GetBlockCount().ConfigureAwait(false) - 1; Tx.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; }); - QueueWork(async t => + QueueWork(async _ => { RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); Tx.SystemFee = long.Parse(result.GasConsumed); From aa451c813018eb964f9f8602ee7ee42aee2bc737 Mon Sep 17 00:00:00 2001 From: Harry Date: Tue, 8 Sep 2020 16:20:30 -0700 Subject: [PATCH 15/21] Async Suffixes (PR feedback) --- src/RpcClient/ContractClient.cs | 6 +- src/RpcClient/Nep5API.cs | 28 +-- src/RpcClient/PolicyAPI.cs | 16 +- src/RpcClient/RpcClient.cs | 84 ++++----- src/RpcClient/TransactionManager.cs | 10 +- src/RpcClient/WalletAPI.cs | 56 +++--- tests/Neo.Network.RPC.Tests/RpcTestCases.json | 94 +++++----- .../UT_ContractClient.cs | 4 +- tests/Neo.Network.RPC.Tests/UT_Nep5API.cs | 14 +- tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs | 8 +- tests/Neo.Network.RPC.Tests/UT_RpcClient.cs | 160 +++++++++--------- tests/Neo.Network.RPC.Tests/UT_RpcModels.cs | 32 ++-- tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 16 +- 13 files changed, 264 insertions(+), 264 deletions(-) diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index e3d52be26..ef7589fd5 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -32,10 +32,10 @@ public ContractClient(RpcClient rpc) /// contract operation /// operation arguments /// - public Task TestInvoke(UInt160 scriptHash, string operation, params object[] args) + public Task TestInvokeAsync(UInt160 scriptHash, string operation, params object[] args) { byte[] script = scriptHash.MakeScript(operation, args); - return rpcClient.InvokeScript(script); + return rpcClient.InvokeScriptAsync(script); } /// @@ -45,7 +45,7 @@ public Task TestInvoke(UInt160 scriptHash, string operation, pa /// contract manifest /// sender KeyPair /// - public async Task CreateDeployContractTx(byte[] contractScript, ContractManifest manifest, KeyPair key) + public async Task CreateDeployContractTxAsync(byte[] contractScript, ContractManifest manifest, KeyPair key) { byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index 161b1ca0b..b0f510c2e 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -29,9 +29,9 @@ public Nep5API(RpcClient rpcClient) : base(rpcClient) { } /// contract script hash /// account script hash /// - public async Task BalanceOf(UInt160 scriptHash, UInt160 account) + public async Task BalanceOfAsync(UInt160 scriptHash, UInt160 account) { - var result = await TestInvoke(scriptHash, "balanceOf", account).ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "balanceOf", account).ConfigureAwait(false); BigInteger balance = result.Stack.Single().GetInteger(); return balance; } @@ -41,9 +41,9 @@ public async Task BalanceOf(UInt160 scriptHash, UInt160 account) /// /// contract script hash /// - public async Task Name(UInt160 scriptHash) + public async Task NameAsync(UInt160 scriptHash) { - var result = await TestInvoke(scriptHash, "name").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "name").ConfigureAwait(false); return result.Stack.Single().GetString(); } @@ -52,9 +52,9 @@ public async Task Name(UInt160 scriptHash) /// /// contract script hash /// - public async Task Symbol(UInt160 scriptHash) + public async Task SymbolAsync(UInt160 scriptHash) { - var result = await TestInvoke(scriptHash, "symbol").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "symbol").ConfigureAwait(false); return result.Stack.Single().GetString(); } @@ -63,9 +63,9 @@ public async Task Symbol(UInt160 scriptHash) /// /// contract script hash /// - public async Task Decimals(UInt160 scriptHash) + public async Task DecimalsAsync(UInt160 scriptHash) { - var result = await TestInvoke(scriptHash, "decimals").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "decimals").ConfigureAwait(false); return (byte)result.Stack.Single().GetInteger(); } @@ -74,9 +74,9 @@ public async Task Decimals(UInt160 scriptHash) /// /// contract script hash /// - public async Task TotalSupply(UInt160 scriptHash) + public async Task TotalSupplyAsync(UInt160 scriptHash) { - var result = await TestInvoke(scriptHash, "totalSupply").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "totalSupply").ConfigureAwait(false); return result.Stack.Single().GetInteger(); } @@ -85,7 +85,7 @@ public async Task TotalSupply(UInt160 scriptHash) /// /// contract script hash /// - public async Task GetTokenInfo(UInt160 scriptHash) + public async Task GetTokenInfoAsync(UInt160 scriptHash) { byte[] script = Concat( scriptHash.MakeScript("name"), @@ -93,7 +93,7 @@ public async Task GetTokenInfo(UInt160 scriptHash) scriptHash.MakeScript("decimals"), scriptHash.MakeScript("totalSupply")); - var result = await rpcClient.InvokeScript(script).ConfigureAwait(false); + var result = await rpcClient.InvokeScriptAsync(script).ConfigureAwait(false); var stack = result.Stack; return new RpcNep5TokenInfo @@ -113,7 +113,7 @@ public async Task GetTokenInfo(UInt160 scriptHash) /// to account script hash /// transfer amount /// - public async Task CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount) + public async Task CreateTransferTxAsync(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount) { var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; @@ -137,7 +137,7 @@ public async Task CreateTransferTx(UInt160 scriptHash, KeyPair from /// to account /// transfer amount /// - public async Task CreateTransferTx(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount) + public async Task CreateTransferTxAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount) { if (m > fromKeys.Length) throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); diff --git a/src/RpcClient/PolicyAPI.cs b/src/RpcClient/PolicyAPI.cs index 8eb004bc0..540f945da 100644 --- a/src/RpcClient/PolicyAPI.cs +++ b/src/RpcClient/PolicyAPI.cs @@ -22,9 +22,9 @@ public PolicyAPI(RpcClient rpcClient) : base(rpcClient) { } /// Get Max Transactions Count Per Block /// /// - public async Task GetMaxTransactionsPerBlock() + public async Task GetMaxTransactionsPerBlockAsync() { - var result = await TestInvoke(scriptHash, "getMaxTransactionsPerBlock").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "getMaxTransactionsPerBlock").ConfigureAwait(false); return (uint)result.Stack.Single().GetInteger(); } @@ -32,9 +32,9 @@ public async Task GetMaxTransactionsPerBlock() /// Get Max Block Size /// /// - public async Task GetMaxBlockSize() + public async Task GetMaxBlockSizeAsync() { - var result = await TestInvoke(scriptHash, "getMaxBlockSize").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "getMaxBlockSize").ConfigureAwait(false); return (uint)result.Stack.Single().GetInteger(); } @@ -42,9 +42,9 @@ public async Task GetMaxBlockSize() /// Get Network Fee Per Byte /// /// - public async Task GetFeePerByte() + public async Task GetFeePerByteAsync() { - var result = await TestInvoke(scriptHash, "getFeePerByte").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "getFeePerByte").ConfigureAwait(false); return (long)result.Stack.Single().GetInteger(); } @@ -52,9 +52,9 @@ public async Task GetFeePerByte() /// Get Ploicy Blocked Accounts /// /// - public async Task GetBlockedAccounts() + public async Task GetBlockedAccountsAsync() { - var result = await TestInvoke(scriptHash, "getBlockedAccounts").ConfigureAwait(false); + var result = await TestInvokeAsync(scriptHash, "getBlockedAccounts").ConfigureAwait(false); var array = (VM.Types.Array)result.Stack.Single(); return array.Select(p => new UInt160(p.GetSpan().ToArray())).ToArray(); } diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index cba8ea1c3..d276db560 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -99,7 +99,7 @@ public virtual async Task RpcSendAsync(string method, params JObject[] /// /// Returns the hash of the tallest block in the main chain. /// - public async Task GetBestBlockHash() + public async Task GetBestBlockHashAsync() { var result = await RpcSendAsync("getbestblockhash").ConfigureAwait(false); return result.AsString(); @@ -109,7 +109,7 @@ public async Task GetBestBlockHash() /// Returns the hash of the tallest block in the main chain. /// The serialized information of the block is returned, represented by a hexadecimal string. /// - public async Task GetBlockHex(string hashOrIndex) + public async Task GetBlockHexAsync(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) ? await RpcSendAsync("getblock", index).ConfigureAwait(false) @@ -120,7 +120,7 @@ public async Task GetBlockHex(string hashOrIndex) /// /// Returns the hash of the tallest block in the main chain. /// - public async Task GetBlock(string hashOrIndex) + public async Task GetBlockAsync(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) ? await RpcSendAsync("getblock", index, true).ConfigureAwait(false) @@ -132,7 +132,7 @@ public async Task GetBlock(string hashOrIndex) /// /// Gets the number of blocks in the main chain. /// - public async Task GetBlockCount() + public async Task GetBlockCountAsync() { var result = await RpcSendAsync("getblockcount").ConfigureAwait(false); return (uint)result.AsNumber(); @@ -141,7 +141,7 @@ public async Task GetBlockCount() /// /// Returns the hash value of the corresponding block, based on the specified index. /// - public async Task GetBlockHash(int index) + public async Task GetBlockHashAsync(int index) { var result = await RpcSendAsync("getblockhash", index).ConfigureAwait(false); return result.AsString(); @@ -150,7 +150,7 @@ public async Task GetBlockHash(int index) /// /// Returns the corresponding block header information according to the specified script hash. /// - public async Task GetBlockHeaderHex(string hashOrIndex) + public async Task GetBlockHeaderHexAsync(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) ? await RpcSendAsync("getblockheader", index).ConfigureAwait(false) @@ -161,7 +161,7 @@ public async Task GetBlockHeaderHex(string hashOrIndex) /// /// Returns the corresponding block header information according to the specified script hash. /// - public async Task GetBlockHeader(string hashOrIndex) + public async Task GetBlockHeaderAsync(string hashOrIndex) { var result = int.TryParse(hashOrIndex, out int index) ? await RpcSendAsync("getblockheader", index, true).ConfigureAwait(false) @@ -173,7 +173,7 @@ public async Task GetBlockHeader(string hashOrIndex) /// /// Queries contract information, according to the contract script hash. /// - public async Task GetContractState(string hash) + public async Task GetContractStateAsync(string hash) { var result = await RpcSendAsync("getcontractstate", hash).ConfigureAwait(false); return ContractStateFromJson(result); @@ -192,7 +192,7 @@ public static ContractState ContractStateFromJson(JObject json) /// /// Obtains the list of unconfirmed transactions in memory. /// - public async Task GetRawMempool() + public async Task GetRawMempoolAsync() { var result = await RpcSendAsync("getrawmempool").ConfigureAwait(false); return ((JArray)result).Select(p => p.AsString()).ToArray(); @@ -202,7 +202,7 @@ public async Task GetRawMempool() /// Obtains the list of unconfirmed transactions in memory. /// shouldGetUnverified = true /// - public async Task GetRawMempoolBoth() + public async Task GetRawMempoolBothAsync() { var result = await RpcSendAsync("getrawmempool", true).ConfigureAwait(false); return RpcRawMemPool.FromJson(result); @@ -211,7 +211,7 @@ public async Task GetRawMempoolBoth() /// /// Returns the corresponding transaction information, based on the specified hash value. /// - public async Task GetRawTransactionHex(string txHash) + public async Task GetRawTransactionHexAsync(string txHash) { var result = await RpcSendAsync("getrawtransaction", txHash).ConfigureAwait(false); return result.AsString(); @@ -221,7 +221,7 @@ public async Task GetRawTransactionHex(string txHash) /// Returns the corresponding transaction information, based on the specified hash value. /// verbose = true /// - public async Task GetRawTransaction(string txHash) + public async Task GetRawTransactionAsync(string txHash) { var result = await RpcSendAsync("getrawtransaction", txHash, true).ConfigureAwait(false); return RpcTransaction.FromJson(result); @@ -230,7 +230,7 @@ public async Task GetRawTransaction(string txHash) /// /// Returns the stored value, according to the contract script hash (or Id) and the stored key. /// - public async Task GetStorage(string scriptHashOrId, string key) + public async Task GetStorageAsync(string scriptHashOrId, string key) { var result = int.TryParse(scriptHashOrId, out int id) ? await RpcSendAsync("getstorage", id, key).ConfigureAwait(false) @@ -241,7 +241,7 @@ public async Task GetStorage(string scriptHashOrId, string key) /// /// Returns the block index in which the transaction is found. /// - public async Task GetTransactionHeight(string txHash) + public async Task GetTransactionHeightAsync(string txHash) { var result = await RpcSendAsync("gettransactionheight", txHash).ConfigureAwait(false); return uint.Parse(result.AsString()); @@ -250,7 +250,7 @@ public async Task GetTransactionHeight(string txHash) /// /// Returns the current NEO consensus nodes information and voting status. /// - public async Task GetValidators() + public async Task GetValidatorsAsync() { var result = await RpcSendAsync("getvalidators").ConfigureAwait(false); return ((JArray)result).Select(p => RpcValidator.FromJson(p)).ToArray(); @@ -263,7 +263,7 @@ public async Task GetValidators() /// /// Gets the current number of connections for the node. /// - public async Task GetConnectionCount() + public async Task GetConnectionCountAsync() { var result = await RpcSendAsync("getconnectioncount").ConfigureAwait(false); return (int)result.AsNumber(); @@ -272,7 +272,7 @@ public async Task GetConnectionCount() /// /// Gets the list of nodes that the node is currently connected/disconnected from. /// - public async Task GetPeers() + public async Task GetPeersAsync() { var result = await RpcSendAsync("getpeers").ConfigureAwait(false); return RpcPeers.FromJson(result); @@ -281,7 +281,7 @@ public async Task GetPeers() /// /// Returns the version information about the queried node. /// - public async Task GetVersion() + public async Task GetVersionAsync() { var result = await RpcSendAsync("getversion").ConfigureAwait(false); return RpcVersion.FromJson(result); @@ -290,7 +290,7 @@ public async Task GetVersion() /// /// Broadcasts a serialized transaction over the NEO network. /// - public async Task SendRawTransaction(byte[] rawTransaction) + public async Task SendRawTransactionAsync(byte[] rawTransaction) { var result = await RpcSendAsync("sendrawtransaction", rawTransaction.ToHexString()).ConfigureAwait(false); return UInt256.Parse(result["hash"].AsString()); @@ -299,15 +299,15 @@ public async Task SendRawTransaction(byte[] rawTransaction) /// /// Broadcasts a transaction over the NEO network. /// - public Task SendRawTransaction(Transaction transaction) + public Task SendRawTransactionAsync(Transaction transaction) { - return SendRawTransaction(transaction.ToArray()); + return SendRawTransactionAsync(transaction.ToArray()); } /// /// Broadcasts a serialized block over the NEO network. /// - public async Task SubmitBlock(byte[] block) + public async Task SubmitBlockAsync(byte[] block) { var result = await RpcSendAsync("submitblock", block.ToHexString()).ConfigureAwait(false); return UInt256.Parse(result["hash"].AsString()); @@ -321,7 +321,7 @@ public async Task SubmitBlock(byte[] block) /// Returns the result after calling a smart contract at scripthash with the given operation and parameters. /// This RPC call does not affect the blockchain in any way. /// - public async Task InvokeFunction(string scriptHash, string operation, RpcStack[] stacks, params Signer[] signer) + public async Task InvokeFunctionAsync(string scriptHash, string operation, RpcStack[] stacks, params Signer[] signer) { List parameters = new List { scriptHash, operation, stacks.Select(p => p.ToJson()).ToArray() }; if (signer.Length > 0) @@ -336,7 +336,7 @@ public async Task InvokeFunction(string scriptHash, string oper /// Returns the result after passing a script through the VM. /// This RPC call does not affect the blockchain in any way. /// - public async Task InvokeScript(byte[] script, params Signer[] signers) + public async Task InvokeScriptAsync(byte[] script, params Signer[] signers) { List parameters = new List { script.ToHexString() }; if (signers.Length > 0) @@ -347,7 +347,7 @@ public async Task InvokeScript(byte[] script, params Signer[] s return RpcInvokeResult.FromJson(result); } - public async Task GetUnclaimedGas(string address) + public async Task GetUnclaimedGasAsync(string address) { var result = await RpcSendAsync("getunclaimedgas", address).ConfigureAwait(false); return RpcUnclaimedGas.FromJson(result); @@ -360,7 +360,7 @@ public async Task GetUnclaimedGas(string address) /// /// Returns a list of plugins loaded by the node. /// - public async Task ListPlugins() + public async Task ListPluginsAsync() { var result = await RpcSendAsync("listplugins").ConfigureAwait(false); return ((JArray)result).Select(p => RpcPlugin.FromJson(p)).ToArray(); @@ -369,7 +369,7 @@ public async Task ListPlugins() /// /// Verifies that the address is a correct NEO address. /// - public async Task ValidateAddress(string address) + public async Task ValidateAddressAsync(string address) { var result = await RpcSendAsync("validateaddress", address).ConfigureAwait(false); return RpcValidateAddressResult.FromJson(result); @@ -382,7 +382,7 @@ public async Task ValidateAddress(string address) /// /// Close the wallet opened by RPC. /// - public async Task CloseWallet() + public async Task CloseWalletAsync() { var result = await RpcSendAsync("closewallet").ConfigureAwait(false); return result.AsBoolean(); @@ -391,7 +391,7 @@ public async Task CloseWallet() /// /// Exports the private key of the specified address. /// - public async Task DumpPrivKey(string address) + public async Task DumpPrivKeyAsync(string address) { var result = await RpcSendAsync("dumpprivkey", address).ConfigureAwait(false); return result.AsString(); @@ -400,7 +400,7 @@ public async Task DumpPrivKey(string address) /// /// Creates a new account in the wallet opened by RPC. /// - public async Task GetNewAddress() + public async Task GetNewAddressAsync() { var result = await RpcSendAsync("getnewaddress").ConfigureAwait(false); return result.AsString(); @@ -411,9 +411,9 @@ public async Task GetNewAddress() /// This method applies to assets that conform to NEP-5 standards. /// /// new address as string - public async Task GetWalletBalance(string assetId) + public async Task GetWalletBalanceAsync(string assetId) { - byte decimals = await (new Nep5API(this).Decimals(UInt160.Parse(assetId))); + byte decimals = await (new Nep5API(this).DecimalsAsync(UInt160.Parse(assetId))); var result = await RpcSendAsync("getwalletbalance", assetId).ConfigureAwait(false); BigInteger balance = BigInteger.Parse(result["balance"].AsString()); return new BigDecimal(balance, decimals); @@ -422,7 +422,7 @@ public async Task GetWalletBalance(string assetId) /// /// Gets the amount of unclaimed GAS in the wallet. /// - public async Task GetWalletUnclaimedGas() + public async Task GetWalletUnclaimedGasAsync() { var result = await RpcSendAsync("getwalletunclaimedgas").ConfigureAwait(false); return BigInteger.Parse(result.AsString()); @@ -431,7 +431,7 @@ public async Task GetWalletUnclaimedGas() /// /// Imports the private key to the wallet. /// - public async Task ImportPrivKey(string wif) + public async Task ImportPrivKeyAsync(string wif) { var result = await RpcSendAsync("importprivkey", wif).ConfigureAwait(false); return RpcAccount.FromJson(result); @@ -440,7 +440,7 @@ public async Task ImportPrivKey(string wif) /// /// Lists all the accounts in the current wallet. /// - public async Task> ListAddress() + public async Task> ListAddressAsync() { var result = await RpcSendAsync("listaddress").ConfigureAwait(false); return ((JArray)result).Select(p => RpcAccount.FromJson(p)).ToList(); @@ -450,7 +450,7 @@ public async Task> ListAddress() /// Open wallet file in the provider's machine. /// By default, this method is disabled by RpcServer config.json. /// - public async Task OpenWallet(string path, string password) + public async Task OpenWalletAsync(string path, string password) { var result = await RpcSendAsync("openwallet", path, password).ConfigureAwait(false); return result.AsBoolean(); @@ -460,7 +460,7 @@ public async Task OpenWallet(string path, string password) /// Transfer from the specified address to the destination address. /// /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public async Task SendFrom(string assetId, string fromAddress, string toAddress, string amount) + public async Task SendFromAsync(string assetId, string fromAddress, string toAddress, string amount) { return await RpcSendAsync("sendfrom", assetId, fromAddress, toAddress, amount).ConfigureAwait(false); } @@ -469,7 +469,7 @@ public async Task SendFrom(string assetId, string fromAddress, string t /// Bulk transfer order, and you can specify a sender address. /// /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public async Task SendMany(string fromAddress, IEnumerable outputs) + public async Task SendManyAsync(string fromAddress, IEnumerable outputs) { var parameters = new List(); if (!string.IsNullOrEmpty(fromAddress)) @@ -485,7 +485,7 @@ public async Task SendMany(string fromAddress, IEnumerable /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. - public async Task SendToAddress(string assetId, string address, string amount) + public async Task SendToAddressAsync(string assetId, string address, string amount) { return await RpcSendAsync("sendtoaddress", assetId, address, amount).ConfigureAwait(false); } @@ -498,7 +498,7 @@ public async Task SendToAddress(string assetId, string address, string /// Returns the contract log based on the specified txHash. The complete contract logs are stored under the ApplicationLogs directory. /// This method is provided by the plugin ApplicationLogs. /// - public async Task GetApplicationLog(string txHash) + public async Task GetApplicationLogAsync(string txHash) { var result = await RpcSendAsync("getapplicationlog", txHash).ConfigureAwait(false); return RpcApplicationLog.FromJson(result); @@ -511,7 +511,7 @@ public async Task GetApplicationLog(string txHash) /// The address to query the transaction information. /// The start block Timestamp, default to seven days before UtcNow /// The end block Timestamp, default to UtcNow - public async Task GetNep5Transfers(string address, ulong? startTimestamp = default, ulong? endTimestamp = default) + public async Task GetNep5TransfersAsync(string address, ulong? startTimestamp = default, ulong? endTimestamp = default) { startTimestamp ??= 0; endTimestamp ??= DateTime.UtcNow.ToTimestampMS(); @@ -523,7 +523,7 @@ public async Task GetNep5Transfers(string address, ulong? star /// Returns the balance of all NEP-5 assets in the specified address. /// This method is provided by the plugin RpcNep5Tracker. /// - public async Task GetNep5Balances(string address) + public async Task GetNep5BalancesAsync(string address) { var result = await RpcSendAsync("getnep5balances", address).ConfigureAwait(false); return RpcNep5Balances.FromJson(result); diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 18fe06927..cd149903b 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -69,13 +69,13 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null QueueWork(async _ => { - uint height = await rpcClient.GetBlockCount().ConfigureAwait(false) - 1; + uint height = await rpcClient.GetBlockCountAsync().ConfigureAwait(false) - 1; Tx.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; }); QueueWork(async _ => { - RpcInvokeResult result = await rpcClient.InvokeScript(script, signers).ConfigureAwait(false); + RpcInvokeResult result = await rpcClient.InvokeScriptAsync(script, signers).ConfigureAwait(false); Tx.SystemFee = long.Parse(result.GasConsumed); }); @@ -161,7 +161,7 @@ public async Task SignAsync() // Calculate NetworkFee Tx.NetworkFee = await CalculateNetworkFee().ConfigureAwait(false); - var gasBalance = await new Nep5API(rpcClient).BalanceOf(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); + var gasBalance = await new Nep5API(rpcClient).BalanceOfAsync(NativeContract.GAS.Hash, Tx.Sender).ConfigureAwait(false); if (gasBalance < Tx.SystemFee + Tx.NetworkFee) throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}"); @@ -212,7 +212,7 @@ private async Task CalculateNetworkFee() { try { - var contractState = await rpcClient.GetContractState(hash.ToString()).ConfigureAwait(false); + var contractState = await rpcClient.GetContractStateAsync(hash.ToString()).ConfigureAwait(false); witness_script = contractState?.Script; } catch { } @@ -222,7 +222,7 @@ private async Task CalculateNetworkFee() networkFee += Wallet.CalculateNetworkFee(witness_script, ref size); } - networkFee += size * (await new PolicyAPI(rpcClient).GetFeePerByte().ConfigureAwait(false)); + networkFee += size * (await new PolicyAPI(rpcClient).GetFeePerByteAsync().ConfigureAwait(false)); return networkFee; } diff --git a/src/RpcClient/WalletAPI.cs b/src/RpcClient/WalletAPI.cs index 775494209..b4cef3c55 100644 --- a/src/RpcClient/WalletAPI.cs +++ b/src/RpcClient/WalletAPI.cs @@ -37,10 +37,10 @@ public WalletAPI(RpcClient rpc) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public Task GetUnclaimedGas(string account) + public Task GetUnclaimedGasAsync(string account) { UInt160 accountHash = Utility.GetScriptHash(account); - return GetUnclaimedGas(accountHash); + return GetUnclaimedGasAsync(accountHash); } /// @@ -48,11 +48,11 @@ public Task GetUnclaimedGas(string account) /// /// account scripthash /// - public async Task GetUnclaimedGas(UInt160 account) + public async Task GetUnclaimedGasAsync(UInt160 account) { UInt160 scriptHash = NativeContract.NEO.Hash; - var blockCount = await rpcClient.GetBlockCount().ConfigureAwait(false); - var result = await nep5API.TestInvoke(scriptHash, "unclaimedGas", account, blockCount - 1).ConfigureAwait(false); + var blockCount = await rpcClient.GetBlockCountAsync().ConfigureAwait(false); + var result = await nep5API.TestInvokeAsync(scriptHash, "unclaimedGas", account, blockCount - 1).ConfigureAwait(false); BigInteger balance = result.Stack.Single().GetInteger(); return ((decimal)balance) / (long)NativeContract.GAS.Factor; } @@ -63,9 +63,9 @@ public async Task GetUnclaimedGas(UInt160 account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public async Task GetNeoBalance(string account) + public async Task GetNeoBalanceAsync(string account) { - BigInteger balance = await GetTokenBalance(NativeContract.NEO.Hash.ToString(), account).ConfigureAwait(false); + BigInteger balance = await GetTokenBalanceAsync(NativeContract.NEO.Hash.ToString(), account).ConfigureAwait(false); return (uint)balance; } @@ -75,9 +75,9 @@ public async Task GetNeoBalance(string account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public async Task GetGasBalance(string account) + public async Task GetGasBalanceAsync(string account) { - BigInteger balance = await GetTokenBalance(NativeContract.GAS.Hash.ToString(), account).ConfigureAwait(false); + BigInteger balance = await GetTokenBalanceAsync(NativeContract.GAS.Hash.ToString(), account).ConfigureAwait(false); return ((decimal)balance) / (long)NativeContract.GAS.Factor; } @@ -88,11 +88,11 @@ public async Task GetGasBalance(string account) /// address, scripthash or public key string /// Example: address ("Ncm9TEzrp8SSer6Wa3UCSLTRnqzwVhCfuE"), scripthash ("0xb0a31817c80ad5f87b6ed390ecb3f9d312f7ceb8"), public key ("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575") /// - public Task GetTokenBalance(string tokenHash, string account) + public Task GetTokenBalanceAsync(string tokenHash, string account) { UInt160 scriptHash = Utility.GetScriptHash(tokenHash); UInt160 accountHash = Utility.GetScriptHash(account); - return nep5API.BalanceOf(scriptHash, accountHash); + return nep5API.BalanceOfAsync(scriptHash, accountHash); } /// @@ -102,10 +102,10 @@ public Task GetTokenBalance(string tokenHash, string account) /// wif or private key /// Example: WIF ("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"), PrivateKey ("450d6c2a04b5b470339a745427bae6828400cf048400837d73c415063835e005") /// The transaction sended - public Task ClaimGas(string key) + public Task ClaimGasAsync(string key) { KeyPair keyPair = Utility.GetKeyPair(key); - return ClaimGas(keyPair); + return ClaimGasAsync(keyPair); } /// @@ -114,12 +114,12 @@ public Task ClaimGas(string key) /// /// keyPair /// The transaction sended - public async Task ClaimGas(KeyPair keyPair) + public async Task ClaimGasAsync(KeyPair keyPair) { UInt160 toHash = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(); - BigInteger balance = await nep5API.BalanceOf(NativeContract.NEO.Hash, toHash).ConfigureAwait(false); - Transaction transaction = await nep5API.CreateTransferTx(NativeContract.NEO.Hash, keyPair, toHash, balance).ConfigureAwait(false); - await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); + BigInteger balance = await nep5API.BalanceOfAsync(NativeContract.NEO.Hash, toHash).ConfigureAwait(false); + Transaction transaction = await nep5API.CreateTransferTxAsync(NativeContract.NEO.Hash, keyPair, toHash, balance).ConfigureAwait(false); + await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } @@ -132,15 +132,15 @@ public async Task ClaimGas(KeyPair keyPair) /// address or account script hash /// token amount /// - public async Task Transfer(string tokenHash, string fromKey, string toAddress, decimal amount) + public async Task TransferAsync(string tokenHash, string fromKey, string toAddress, decimal amount) { UInt160 scriptHash = Utility.GetScriptHash(tokenHash); - var decimals = await nep5API.Decimals(scriptHash).ConfigureAwait(false); + var decimals = await nep5API.DecimalsAsync(scriptHash).ConfigureAwait(false); KeyPair from = Utility.GetKeyPair(fromKey); UInt160 to = Utility.GetScriptHash(toAddress); BigInteger amountInteger = amount.ToBigInteger(decimals); - return await Transfer(scriptHash, from, to, amountInteger).ConfigureAwait(false); + return await TransferAsync(scriptHash, from, to, amountInteger).ConfigureAwait(false); } /// @@ -151,10 +151,10 @@ public async Task Transfer(string tokenHash, string fromKey, string /// to account script hash /// transfer amount /// - public async Task Transfer(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger) + public async Task TransferAsync(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger) { - Transaction transaction = await nep5API.CreateTransferTx(scriptHash, from, to, amountInteger).ConfigureAwait(false); - await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); + Transaction transaction = await nep5API.CreateTransferTxAsync(scriptHash, from, to, amountInteger).ConfigureAwait(false); + await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } @@ -168,10 +168,10 @@ public async Task Transfer(UInt160 scriptHash, KeyPair from, UInt16 /// to account /// transfer amount /// - public async Task Transfer(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger) + public async Task TransferAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger) { - Transaction transaction = await nep5API.CreateTransferTx(scriptHash, m, pubKeys, keys, to, amountInteger).ConfigureAwait(false); - await rpcClient.SendRawTransaction(transaction).ConfigureAwait(false); + Transaction transaction = await nep5API.CreateTransferTxAsync(scriptHash, m, pubKeys, keys, to, amountInteger).ConfigureAwait(false); + await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } @@ -181,7 +181,7 @@ public async Task Transfer(UInt160 scriptHash, int m, ECPoint[] pub /// the transaction to observe /// TimeoutException throws after "timeout" seconds /// the Transaction state, including vmState and blockhash - public async Task WaitTransaction(Transaction transaction, int timeout = 60) + public async Task WaitTransactionAsync(Transaction transaction, int timeout = 60) { DateTime deadline = DateTime.UtcNow.AddSeconds(timeout); RpcTransaction rpcTx = null; @@ -194,7 +194,7 @@ public async Task WaitTransaction(Transaction transaction, int t try { - rpcTx = await rpcClient.GetRawTransaction(transaction.Hash.ToString()).ConfigureAwait(false); + rpcTx = await rpcClient.GetRawTransactionAsync(transaction.Hash.ToString()).ConfigureAwait(false); if (rpcTx == null || rpcTx.Confirmations == null) { await Task.Delay((int)Blockchain.MillisecondsPerBlock / 2); diff --git a/tests/Neo.Network.RPC.Tests/RpcTestCases.json b/tests/Neo.Network.RPC.Tests/RpcTestCases.json index 5dccd0d73..684767260 100644 --- a/tests/Neo.Network.RPC.Tests/RpcTestCases.json +++ b/tests/Neo.Network.RPC.Tests/RpcTestCases.json @@ -1,6 +1,6 @@ [ { - "Name": "sendrawtransactionerror", + "Name": "sendrawtransactionasyncerror", "Request": { "jsonrpc": "2.0", "method": "sendrawtransaction", @@ -18,7 +18,7 @@ } }, { - "Name": "getbestblockhash", + "Name": "getbestblockhashasync", "Request": { "jsonrpc": "2.0", "method": "getbestblockhash", @@ -32,7 +32,7 @@ } }, { - "Name": "getblockhex", + "Name": "getblockhexasync", "Request": { "jsonrpc": "2.0", "method": "getblock", @@ -46,7 +46,7 @@ } }, { - "Name": "getblockhex", + "Name": "getblockhexasync", "Request": { "jsonrpc": "2.0", "method": "getblock", @@ -60,7 +60,7 @@ } }, { - "Name": "getblock", + "Name": "getblockasync", "Request": { "jsonrpc": "2.0", "method": "getblock", @@ -121,7 +121,7 @@ } }, { - "Name": "getblock", + "Name": "getblockasync", "Request": { "jsonrpc": "2.0", "method": "getblock", @@ -182,7 +182,7 @@ } }, { - "Name": "getblockcount", + "Name": "getblockcountasync", "Request": { "jsonrpc": "2.0", "method": "getblockcount", @@ -196,7 +196,7 @@ } }, { - "Name": "getblockhash", + "Name": "getblockhashasync", "Request": { "jsonrpc": "2.0", "method": "getblockhash", @@ -210,7 +210,7 @@ } }, { - "Name": "getblockheaderhex", + "Name": "getblockheaderhexasync", "Request": { "jsonrpc": "2.0", "method": "getblockheader", @@ -224,7 +224,7 @@ } }, { - "Name": "getblockheaderhex", + "Name": "getblockheaderhexasync", "Request": { "jsonrpc": "2.0", "method": "getblockheader", @@ -238,7 +238,7 @@ } }, { - "Name": "getblockheader", + "Name": "getblockheaderasync", "Request": { "jsonrpc": "2.0", "method": "getblockheader", @@ -269,7 +269,7 @@ } }, { - "Name": "getblockheader", + "Name": "getblockheaderasync", "Request": { "jsonrpc": "2.0", "method": "getblockheader", @@ -300,7 +300,7 @@ } }, { - "Name": "getblocksysfee", + "Name": "getblocksysfeeasync", "Request": { "jsonrpc": "2.0", "method": "getblocksysfee", @@ -314,7 +314,7 @@ } }, { - "Name": "getcontractstate", + "Name": "getcontractstateasync", "Request": { "jsonrpc": "2.0", "method": "getcontractstate", @@ -458,7 +458,7 @@ } }, { - "Name": "getrawmempool", + "Name": "getrawmempoolasync", "Request": { "jsonrpc": "2.0", "method": "getrawmempool", @@ -472,7 +472,7 @@ } }, { - "Name": "getrawmempoolboth", + "Name": "getrawmempoolbothasync", "Request": { "jsonrpc": "2.0", "method": "getrawmempool", @@ -490,7 +490,7 @@ } }, { - "Name": "getrawtransactionhex", + "Name": "getrawtransactionhexasync", "Request": { "jsonrpc": "2.0", "method": "getrawtransaction", @@ -504,7 +504,7 @@ } }, { - "Name": "getrawtransaction", + "Name": "getrawtransactionasync", "Request": { "jsonrpc": "2.0", "method": "getrawtransaction", @@ -545,7 +545,7 @@ } }, { - "Name": "getstorage", + "Name": "getstorageasync", "Request": { "jsonrpc": "2.0", "method": "getstorage", @@ -559,7 +559,7 @@ } }, { - "Name": "getstorage", + "Name": "getstorageasync", "Request": { "jsonrpc": "2.0", "method": "getstorage", @@ -573,7 +573,7 @@ } }, { - "Name": "gettransactionheight", + "Name": "gettransactionheightasync", "Request": { "jsonrpc": "2.0", "method": "gettransactionheight", @@ -587,7 +587,7 @@ } }, { - "Name": "getvalidators", + "Name": "getvalidatorsasync", "Request": { "jsonrpc": "2.0", "method": "getvalidators", @@ -609,7 +609,7 @@ { - "Name": "getconnectioncount", + "Name": "getconnectioncountasync", "Request": { "jsonrpc": "2.0", "method": "getconnectioncount", @@ -623,7 +623,7 @@ } }, { - "Name": "getpeers", + "Name": "getpeersasync", "Request": { "jsonrpc": "2.0", "method": "getpeers", @@ -655,7 +655,7 @@ } }, { - "Name": "getversion", + "Name": "getversionasync", "Request": { "jsonrpc": "2.0", "method": "getversion", @@ -674,7 +674,7 @@ } }, { - "Name": "sendrawtransaction", + "Name": "sendrawtransactionasync", "Request": { "jsonrpc": "2.0", "method": "sendrawtransaction", @@ -690,7 +690,7 @@ } }, { - "Name": "submitblock", + "Name": "submitblockasync", "Request": { "jsonrpc": "2.0", "method": "submitblock", @@ -708,7 +708,7 @@ { - "Name": "invokefunction", + "Name": "invokefunctionasync", "Request": { "jsonrpc": "2.0", "method": "invokefunction", @@ -742,7 +742,7 @@ } }, { - "Name": "invokescript", + "Name": "invokescriptasync", "Request": { "jsonrpc": "2.0", "method": "invokescript", @@ -822,7 +822,7 @@ }, { - "Name": "getunclaimedgas", + "Name": "getunclaimedgasasync", "Request": { "jsonrpc": "2.0", "method": "getunclaimedgas", @@ -840,7 +840,7 @@ }, { - "Name": "listplugins", + "Name": "listpluginsasync", "Request": { "jsonrpc": "2.0", "method": "listplugins", @@ -881,7 +881,7 @@ } }, { - "Name": "validateaddress", + "Name": "validateaddressasync", "Request": { "jsonrpc": "2.0", "method": "validateaddress", @@ -900,7 +900,7 @@ { - "Name": "closewallet", + "Name": "closewalletasync", "Request": { "jsonrpc": "2.0", "method": "closewallet", @@ -914,7 +914,7 @@ } }, { - "Name": "dumpprivkey", + "Name": "dumpprivkeyasync", "Request": { "jsonrpc": "2.0", "method": "dumpprivkey", @@ -928,7 +928,7 @@ } }, { - "Name": "invokescript", + "Name": "invokescriptasync", "Request": { "jsonrpc": "2.0", "method": "invokescript", @@ -953,7 +953,7 @@ } }, { - "Name": "getnewaddress", + "Name": "getnewaddressasync", "Request": { "jsonrpc": "2.0", "method": "getnewaddress", @@ -967,7 +967,7 @@ } }, { - "Name": "getwalletbalance", + "Name": "getwalletbalanceasync", "Request": { "jsonrpc": "2.0", "method": "getwalletbalance", @@ -983,7 +983,7 @@ } }, { - "Name": "getwalletunclaimedgas", + "Name": "getwalletunclaimedgasasync", "Request": { "jsonrpc": "2.0", "method": "getwalletunclaimedgas", @@ -997,7 +997,7 @@ } }, { - "Name": "importprivkey", + "Name": "importprivkeyasync", "Request": { "jsonrpc": "2.0", "method": "importprivkey", @@ -1016,7 +1016,7 @@ } }, { - "Name": "listaddress", + "Name": "listaddressasync", "Request": { "jsonrpc": "2.0", "method": "listaddress", @@ -1043,7 +1043,7 @@ } }, { - "Name": "openwallet", + "Name": "openwalletasync", "Request": { "jsonrpc": "2.0", "method": "openwallet", @@ -1057,7 +1057,7 @@ } }, { - "Name": "sendfrom", + "Name": "sendfromasync", "Request": { "jsonrpc": "2.0", "method": "sendfrom", @@ -1094,7 +1094,7 @@ } }, { - "Name": "sendmany", + "Name": "sendmanyasync", "Request": { "jsonrpc": "2.0", "method": "sendmany", @@ -1153,7 +1153,7 @@ } }, { - "Name": "sendtoaddress", + "Name": "sendtoaddressasync", "Request": { "jsonrpc": "2.0", "method": "sendtoaddress", @@ -1196,7 +1196,7 @@ { - "Name": "getapplicationlog", + "Name": "getapplicationlogasync", "Request": { "jsonrpc": "2.0", "method": "getapplicationlog", @@ -1359,7 +1359,7 @@ } }, { - "Name": "getnep5transfers", + "Name": "getnep5transfersasync", "Request": { "jsonrpc": "2.0", "method": "getnep5transfers", @@ -1406,7 +1406,7 @@ } }, { - "Name": "getnep5balances", + "Name": "getnep5balancesasync", "Request": { "jsonrpc": "2.0", "method": "getnep5balances", diff --git a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs index 2c588761d..2a120fad4 100644 --- a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs @@ -31,7 +31,7 @@ public async Task TestInvoke() UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.ByteArray, Value = "00e057eb481b".HexToBytes() }); ContractClient contractClient = new ContractClient(rpcClientMock.Object); - var result = await contractClient.TestInvoke(NativeContract.GAS.Hash, "balanceOf", UInt160.Zero); + var result = await contractClient.TestInvokeAsync(NativeContract.GAS.Hash, "balanceOf", UInt160.Zero); Assert.AreEqual(30000000000000L, (long)result.Stack[0].GetInteger()); } @@ -65,7 +65,7 @@ public async Task TestDeployContract() UT_TransactionManager.MockInvokeScript(rpcClientMock, script, new ContractParameter()); ContractClient contractClient = new ContractClient(rpcClientMock.Object); - var result = await contractClient.CreateDeployContractTx(new byte[1], manifest, keyPair1); + var result = await contractClient.CreateDeployContractTxAsync(new byte[1], manifest, keyPair1); Assert.IsNotNull(result); } diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs index 546729c1b..12f0142c9 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep5API.cs @@ -33,7 +33,7 @@ public async Task TestBalanceOf() byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", UInt160.Zero); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(10000) }); - var balance = await nep5API.BalanceOf(NativeContract.GAS.Hash, UInt160.Zero); + var balance = await nep5API.BalanceOfAsync(NativeContract.GAS.Hash, UInt160.Zero); Assert.AreEqual(10000, (int)balance); } @@ -43,7 +43,7 @@ public async Task TestGetName() byte[] testScript = NativeContract.GAS.Hash.MakeScript("name"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.String, Value = NativeContract.GAS.Name }); - var result = await nep5API.Name(NativeContract.GAS.Hash); + var result = await nep5API.NameAsync(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Name, result); } @@ -53,7 +53,7 @@ public async Task TestGetSymbol() byte[] testScript = NativeContract.GAS.Hash.MakeScript("symbol"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.String, Value = NativeContract.GAS.Symbol }); - var result = await nep5API.Symbol(NativeContract.GAS.Hash); + var result = await nep5API.SymbolAsync(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Symbol, result); } @@ -63,7 +63,7 @@ public async Task TestGetDecimals() byte[] testScript = NativeContract.GAS.Hash.MakeScript("decimals"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(NativeContract.GAS.Decimals) }); - var result = await nep5API.Decimals(NativeContract.GAS.Hash); + var result = await nep5API.DecimalsAsync(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Decimals, result); } @@ -73,7 +73,7 @@ public async Task TestGetTotalSupply() byte[] testScript = NativeContract.GAS.Hash.MakeScript("totalSupply"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var result = await nep5API.TotalSupply(NativeContract.GAS.Hash); + var result = await nep5API.TotalSupplyAsync(NativeContract.GAS.Hash); Assert.AreEqual(1_00000000, (int)result); } @@ -92,7 +92,7 @@ public async Task TestGetTokenInfo() new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(NativeContract.GAS.Decimals) }, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var result = await nep5API.GetTokenInfo(NativeContract.GAS.Hash); + var result = await nep5API.GetTokenInfoAsync(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Name, result.Name); Assert.AreEqual(NativeContract.GAS.Symbol, result.Symbol); Assert.AreEqual(8, (int)result.Decimals); @@ -105,7 +105,7 @@ public async Task TestTransfer() byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000)); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter()); - var result = await nep5API.CreateTransferTx(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000)); + var result = await nep5API.CreateTransferTxAsync(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000)); Assert.IsNotNull(result); } } diff --git a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs index 8437f567b..546e250e1 100644 --- a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs @@ -32,7 +32,7 @@ public async Task TestGetMaxTransactionsPerBlock() byte[] testScript = NativeContract.Policy.Hash.MakeScript("getMaxTransactionsPerBlock"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(512) }); - var result = await policyAPI.GetMaxTransactionsPerBlock(); + var result = await policyAPI.GetMaxTransactionsPerBlockAsync(); Assert.AreEqual(512u, result); } @@ -42,7 +42,7 @@ public async Task TestGetMaxBlockSize() byte[] testScript = NativeContract.Policy.Hash.MakeScript("getMaxBlockSize"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1024u * 256u) }); - var result = await policyAPI.GetMaxBlockSize(); + var result = await policyAPI.GetMaxBlockSizeAsync(); Assert.AreEqual(1024u * 256u, result); } @@ -52,7 +52,7 @@ public async Task TestGetFeePerByte() byte[] testScript = NativeContract.Policy.Hash.MakeScript("getFeePerByte"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1000) }); - var result = await policyAPI.GetFeePerByte(); + var result = await policyAPI.GetFeePerByteAsync(); Assert.AreEqual(1000L, result); } @@ -62,7 +62,7 @@ public async Task TestGetBlockedAccounts() byte[] testScript = NativeContract.Policy.Hash.MakeScript("getBlockedAccounts"); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Array, Value = new[] { new ContractParameter { Type = ContractParameterType.Hash160, Value = UInt160.Zero } } }); - var result = await policyAPI.GetBlockedAccounts(); + var result = await policyAPI.GetBlockedAccountsAsync(); Assert.AreEqual(UInt160.Zero, result[0]); } } diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs index fc0b3e825..9f256087a 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs @@ -56,10 +56,10 @@ private void MockResponse(RpcRequest request, RpcResponse response) [TestMethod] public async Task TestErrorResponse() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == (nameof(rpc.SendRawTransaction) + "error").ToLower()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == (nameof(rpc.SendRawTransactionAsync) + "error").ToLower()); try { - var result = await rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); + var result = await rpc.SendRawTransactionAsync(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); } catch (RpcException ex) { @@ -89,18 +89,18 @@ public void TestConstructorWithBasicAuth() [TestMethod] public async Task TestGetBestBlockHash() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBestBlockHash).ToLower()); - var result = await rpc.GetBestBlockHash(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBestBlockHashAsync).ToLower()); + var result = await rpc.GetBestBlockHashAsync(); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] public async Task TestGetBlockHex() { - var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHex).ToLower()); + var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHexAsync).ToLower()); foreach (var test in tests) { - var result = await rpc.GetBlockHex(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHexAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } } @@ -108,10 +108,10 @@ public async Task TestGetBlockHex() [TestMethod] public async Task TestGetBlock() { - var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlock).ToLower()); + var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockAsync).ToLower()); foreach (var test in tests) { - var result = await rpc.GetBlock(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result.ToJson().ToString()); } } @@ -119,26 +119,26 @@ public async Task TestGetBlock() [TestMethod] public async Task TestGetBlockCount() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockCount).ToLower()); - var result = await rpc.GetBlockCount(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockCountAsync).ToLower()); + var result = await rpc.GetBlockCountAsync(); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] public async Task TestGetBlockHash() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockHash).ToLower()); - var result = await rpc.GetBlockHash((int)test.Request.Params[0].AsNumber()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetBlockHashAsync).ToLower()); + var result = await rpc.GetBlockHashAsync((int)test.Request.Params[0].AsNumber()); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] public async Task TestGetBlockHeaderHex() { - var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeaderHex).ToLower()); + var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeaderHexAsync).ToLower()); foreach (var test in tests) { - var result = await rpc.GetBlockHeaderHex(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHeaderHexAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } } @@ -146,10 +146,10 @@ public async Task TestGetBlockHeaderHex() [TestMethod] public async Task TestGetBlockHeader() { - var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeader).ToLower()); + var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetBlockHeaderAsync).ToLower()); foreach (var test in tests) { - var result = await rpc.GetBlockHeader(test.Request.Params[0].AsString()); + var result = await rpc.GetBlockHeaderAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } } @@ -157,10 +157,10 @@ public async Task TestGetBlockHeader() [TestMethod] public async Task TestGetContractState() { - var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetContractState).ToLower()); + var tests = TestUtils.RpcTestCases.Where(p => p.Name == nameof(rpc.GetContractStateAsync).ToLower()); foreach (var test in tests) { - var result = await rpc.GetContractState(test.Request.Params[0].AsString()); + var result = await rpc.GetContractStateAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } } @@ -168,56 +168,56 @@ public async Task TestGetContractState() [TestMethod] public async Task TestGetRawMempool() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempool).ToLower()); - var result = await rpc.GetRawMempool(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempoolAsync).ToLower()); + var result = await rpc.GetRawMempoolAsync(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => (JObject)p).ToArray()).ToString()); } [TestMethod] public async Task TestGetRawMempoolBoth() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempoolBoth).ToLower()); - var result = await rpc.GetRawMempoolBoth(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawMempoolBothAsync).ToLower()); + var result = await rpc.GetRawMempoolBothAsync(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestGetRawTransactionHex() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransactionHex).ToLower()); - var result = await rpc.GetRawTransactionHex(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransactionHexAsync).ToLower()); + var result = await rpc.GetRawTransactionHexAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] public async Task TestGetRawTransaction() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransaction).ToLower()); - var result = await rpc.GetRawTransaction(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetRawTransactionAsync).ToLower()); + var result = await rpc.GetRawTransactionAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestGetStorage() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetStorage).ToLower()); - var result = await rpc.GetStorage(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetStorageAsync).ToLower()); + var result = await rpc.GetStorageAsync(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] public async Task TestGetTransactionHeight() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetTransactionHeight).ToLower()); - var result = await rpc.GetTransactionHeight(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetTransactionHeightAsync).ToLower()); + var result = await rpc.GetTransactionHeightAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] public async Task TestGetValidators() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetValidators).ToLower()); - var result = await rpc.GetValidators(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetValidatorsAsync).ToLower()); + var result = await rpc.GetValidatorsAsync(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } @@ -228,41 +228,41 @@ public async Task TestGetValidators() [TestMethod] public async Task TestGetConnectionCount() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetConnectionCount).ToLower()); - var result = await rpc.GetConnectionCount(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetConnectionCountAsync).ToLower()); + var result = await rpc.GetConnectionCountAsync(); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] public async Task TestGetPeers() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetPeers).ToLower()); - var result = await rpc.GetPeers(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetPeersAsync).ToLower()); + var result = await rpc.GetPeersAsync(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestGetVersion() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetVersion).ToLower()); - var result = await rpc.GetVersion(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetVersionAsync).ToLower()); + var result = await rpc.GetVersionAsync(); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestSendRawTransaction() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendRawTransaction).ToLower()); - var result = await rpc.SendRawTransaction(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendRawTransactionAsync).ToLower()); + var result = await rpc.SendRawTransactionAsync(test.Request.Params[0].AsString().HexToBytes().AsSerializable()); Assert.AreEqual(test.Response.Result["hash"].AsString(), result.ToString()); } [TestMethod] public async Task TestSubmitBlock() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SubmitBlock).ToLower()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SubmitBlockAsync).ToLower()); var block = TestUtils.GetBlock(2).Hash; - var result = await rpc.SubmitBlock(test.Request.Params[0].AsString().HexToBytes()); + var result = await rpc.SubmitBlockAsync(test.Request.Params[0].AsString().HexToBytes()); Assert.AreEqual(test.Response.Result["hash"].AsString(), result.ToString()); } @@ -273,8 +273,8 @@ public async Task TestSubmitBlock() [TestMethod] public async Task TestInvokeFunction() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeFunction).ToLower()); - var result = await rpc.InvokeFunction(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeFunctionAsync).ToLower()); + var result = await rpc.InvokeFunctionAsync(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), ((JArray)test.Request.Params[2]).Select(p => RpcStack.FromJson(p)).ToArray()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } @@ -282,16 +282,16 @@ public async Task TestInvokeFunction() [TestMethod] public async Task TestInvokeScript() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeScript).ToLower()); - var result = await rpc.InvokeScript(test.Request.Params[0].AsString().HexToBytes()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.InvokeScriptAsync).ToLower()); + var result = await rpc.InvokeScriptAsync(test.Request.Params[0].AsString().HexToBytes()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestGetUnclaimedGas() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetUnclaimedGas).ToLower()); - var result = await rpc.GetUnclaimedGas(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetUnclaimedGasAsync).ToLower()); + var result = await rpc.GetUnclaimedGasAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result["unclaimed"].AsString(), result.Unclaimed.ToString()); } @@ -302,16 +302,16 @@ public async Task TestGetUnclaimedGas() [TestMethod] public async Task TestListPlugins() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListPlugins).ToLower()); - var result = await rpc.ListPlugins(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListPluginsAsync).ToLower()); + var result = await rpc.ListPluginsAsync(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } [TestMethod] public async Task TestValidateAddress() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ValidateAddress).ToLower()); - var result = await rpc.ValidateAddress(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ValidateAddressAsync).ToLower()); + var result = await rpc.ValidateAddressAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } @@ -322,72 +322,72 @@ public async Task TestValidateAddress() [TestMethod] public async Task TestCloseWallet() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.CloseWallet).ToLower()); - var result = await rpc.CloseWallet(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.CloseWalletAsync).ToLower()); + var result = await rpc.CloseWalletAsync(); Assert.AreEqual(test.Response.Result.AsBoolean(), result); } [TestMethod] public async Task TestDumpPrivKey() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.DumpPrivKey).ToLower()); - var result = await rpc.DumpPrivKey(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.DumpPrivKeyAsync).ToLower()); + var result = await rpc.DumpPrivKeyAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] public async Task TestGetNewAddress() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNewAddress).ToLower()); - var result = await rpc.GetNewAddress(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNewAddressAsync).ToLower()); + var result = await rpc.GetNewAddressAsync(); Assert.AreEqual(test.Response.Result.AsString(), result); } [TestMethod] public async Task TestGetWalletBalance() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletBalance).ToLower()); - var result = await rpc.GetWalletBalance(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletBalanceAsync).ToLower()); + var result = await rpc.GetWalletBalanceAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result["balance"].AsString(), result.Value.ToString()); } [TestMethod] public async Task TestGetWalletUnclaimedGas() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletUnclaimedGas).ToLower()); - var result = await rpc.GetWalletUnclaimedGas(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetWalletUnclaimedGasAsync).ToLower()); + var result = await rpc.GetWalletUnclaimedGasAsync(); Assert.AreEqual(test.Response.Result.AsString(), result.ToString()); } [TestMethod] public async Task TestImportPrivKey() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ImportPrivKey).ToLower()); - var result = await rpc.ImportPrivKey(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ImportPrivKeyAsync).ToLower()); + var result = await rpc.ImportPrivKeyAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod] public async Task TestListAddress() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListAddress).ToLower()); - var result = await rpc.ListAddress(); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.ListAddressAsync).ToLower()); + var result = await rpc.ListAddressAsync(); Assert.AreEqual(test.Response.Result.ToString(), ((JArray)result.Select(p => p.ToJson()).ToArray()).ToString()); } [TestMethod] public async Task TestOpenWallet() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.OpenWallet).ToLower()); - var result = await rpc.OpenWallet(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.OpenWalletAsync).ToLower()); + var result = await rpc.OpenWalletAsync(test.Request.Params[0].AsString(), test.Request.Params[1].AsString()); Assert.AreEqual(test.Response.Result.AsBoolean(), result); } [TestMethod] public async Task TestSendFrom() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendFrom).ToLower()); - var result = await rpc.SendFrom(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendFromAsync).ToLower()); + var result = await rpc.SendFromAsync(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString(), test.Request.Params[3].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } @@ -395,16 +395,16 @@ public async Task TestSendFrom() [TestMethod] public async Task TestSendMany() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendMany).ToLower()); - var result = await rpc.SendMany(test.Request.Params[0].AsString(), ((JArray)test.Request.Params[1]).Select(p => RpcTransferOut.FromJson(p))); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendManyAsync).ToLower()); + var result = await rpc.SendManyAsync(test.Request.Params[0].AsString(), ((JArray)test.Request.Params[1]).Select(p => RpcTransferOut.FromJson(p))); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } [TestMethod] public async Task TestSendToAddress() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendToAddress).ToLower()); - var result = await rpc.SendToAddress(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.SendToAddressAsync).ToLower()); + var result = await rpc.SendToAddressAsync(test.Request.Params[0].AsString(), test.Request.Params[1].AsString(), test.Request.Params[2].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToString()); } @@ -415,16 +415,16 @@ public async Task TestSendToAddress() [TestMethod()] public async Task GetApplicationLogTest() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetApplicationLog).ToLower()); - var result = await rpc.GetApplicationLog(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetApplicationLogAsync).ToLower()); + var result = await rpc.GetApplicationLogAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } [TestMethod()] public async Task GetNep5TransfersTest() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5Transfers).ToLower()); - var result = await rpc.GetNep5Transfers(test.Request.Params[0].AsString(), (ulong)test.Request.Params[1].AsNumber(), + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5TransfersAsync).ToLower()); + var result = await rpc.GetNep5TransfersAsync(test.Request.Params[0].AsString(), (ulong)test.Request.Params[1].AsNumber(), (ulong)test.Request.Params[2].AsNumber()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } @@ -432,8 +432,8 @@ public async Task GetNep5TransfersTest() [TestMethod()] public async Task GetNep5BalancesTest() { - var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5Balances).ToLower()); - var result = await rpc.GetNep5Balances(test.Request.Params[0].AsString()); + var test = TestUtils.RpcTestCases.Find(p => p.Name == nameof(rpc.GetNep5BalancesAsync).ToLower()); + var result = await rpc.GetNep5BalancesAsync(test.Request.Params[0].AsString()); Assert.AreEqual(test.Response.Result.ToString(), result.ToJson().ToString()); } diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs b/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs index 313f757f6..de6829c25 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs @@ -11,7 +11,7 @@ public class UT_RpcModels [TestMethod()] public void TestRpcAccount() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ImportPrivKey).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ImportPrivKeyAsync).ToLower()).Response.Result; var item = RpcAccount.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -19,7 +19,7 @@ public void TestRpcAccount() [TestMethod()] public void TestRpcApplicationLog() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetApplicationLog).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetApplicationLogAsync).ToLower()).Response.Result; var item = RpcApplicationLog.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -27,7 +27,7 @@ public void TestRpcApplicationLog() [TestMethod()] public void TestRpcBlock() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetBlock).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetBlockAsync).ToLower()).Response.Result; var item = RpcBlock.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -35,7 +35,7 @@ public void TestRpcBlock() [TestMethod()] public void TestRpcBlockHeader() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetBlockHeader).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetBlockHeaderAsync).ToLower()).Response.Result; var item = RpcBlockHeader.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -43,7 +43,7 @@ public void TestRpcBlockHeader() [TestMethod()] public void TestGetContractState() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetContractState).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetContractStateAsync).ToLower()).Response.Result; var item = RpcContractState.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -51,7 +51,7 @@ public void TestGetContractState() [TestMethod()] public void TestRpcInvokeResult() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.InvokeFunction).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.InvokeFunctionAsync).ToLower()).Response.Result; var item = RpcInvokeResult.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -59,7 +59,7 @@ public void TestRpcInvokeResult() [TestMethod()] public void TestRpcNep5Balances() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetNep5Balances).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetNep5BalancesAsync).ToLower()).Response.Result; var item = RpcNep5Balances.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -67,7 +67,7 @@ public void TestRpcNep5Balances() [TestMethod()] public void TestRpcNep5Transfers() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetNep5Transfers).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetNep5TransfersAsync).ToLower()).Response.Result; var item = RpcNep5Transfers.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -75,7 +75,7 @@ public void TestRpcNep5Transfers() [TestMethod()] public void TestRpcPeers() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetPeers).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetPeersAsync).ToLower()).Response.Result; var item = RpcPeers.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -83,7 +83,7 @@ public void TestRpcPeers() [TestMethod()] public void TestRpcPlugin() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ListPlugins).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ListPluginsAsync).ToLower()).Response.Result; var item = ((JArray)json).Select(p => RpcPlugin.FromJson(p)); Assert.AreEqual(json.ToString(), ((JArray)item.Select(p => p.ToJson()).ToArray()).ToString()); } @@ -91,7 +91,7 @@ public void TestRpcPlugin() [TestMethod()] public void TestRpcRawMemPool() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetRawMempoolBoth).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetRawMempoolBothAsync).ToLower()).Response.Result; var item = RpcRawMemPool.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -99,7 +99,7 @@ public void TestRpcRawMemPool() [TestMethod()] public void TestRpcTransaction() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetRawTransaction).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetRawTransactionAsync).ToLower()).Response.Result; var item = RpcTransaction.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -107,7 +107,7 @@ public void TestRpcTransaction() [TestMethod()] public void TestRpcTransferOut() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.SendMany).ToLower()).Request.Params[1]; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.SendManyAsync).ToLower()).Request.Params[1]; var item = ((JArray)json).Select(p => RpcTransferOut.FromJson(p)); Assert.AreEqual(json.ToString(), ((JArray)item.Select(p => p.ToJson()).ToArray()).ToString()); } @@ -115,7 +115,7 @@ public void TestRpcTransferOut() [TestMethod()] public void TestRpcValidateAddressResult() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ValidateAddress).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.ValidateAddressAsync).ToLower()).Response.Result; var item = RpcValidateAddressResult.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } @@ -123,7 +123,7 @@ public void TestRpcValidateAddressResult() [TestMethod()] public void TestRpcValidator() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetValidators).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetValidatorsAsync).ToLower()).Response.Result; var item = ((JArray)json).Select(p => RpcValidator.FromJson(p)); Assert.AreEqual(json.ToString(), ((JArray)item.Select(p => p.ToJson()).ToArray()).ToString()); } @@ -131,7 +131,7 @@ public void TestRpcValidator() [TestMethod()] public void TestRpcVersion() { - JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetVersion).ToLower()).Response.Result; + JObject json = TestUtils.RpcTestCases.Find(p => p.Name == nameof(RpcClient.GetVersionAsync).ToLower()).Response.Result; var item = RpcVersion.FromJson(json); Assert.AreEqual(json.ToString(), item.ToJson().ToString()); } diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 984f737c2..ebfbcb51b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -39,7 +39,7 @@ public async Task TestGetUnclaimedGas() byte[] testScript = NativeContract.NEO.Hash.MakeScript("unclaimedGas", sender, 99); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = await walletAPI.GetUnclaimedGas(address1); + var balance = await walletAPI.GetUnclaimedGasAsync(address1); Assert.AreEqual(1.1m, balance); } @@ -49,7 +49,7 @@ public async Task TestGetNeoBalance() byte[] testScript = NativeContract.NEO.Hash.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_00000000) }); - var balance = await walletAPI.GetNeoBalance(address1); + var balance = await walletAPI.GetNeoBalanceAsync(address1); Assert.AreEqual(1_00000000u, balance); } @@ -59,7 +59,7 @@ public async Task TestGetGasBalance() byte[] testScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = await walletAPI.GetGasBalance(address1); + var balance = await walletAPI.GetGasBalanceAsync(address1); Assert.AreEqual(1.1m, balance); } @@ -69,7 +69,7 @@ public async Task TestGetTokenBalance() byte[] testScript = UInt160.Zero.MakeScript("balanceOf", sender); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - var balance = await walletAPI.GetTokenBalance(UInt160.Zero.ToString(), address1); + var balance = await walletAPI.GetTokenBalanceAsync(UInt160.Zero.ToString(), address1); Assert.AreEqual(1_10000000, balance); } @@ -86,7 +86,7 @@ public async Task TestClaimGas() json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.ClaimGas(keyPair1.Export()); + var tranaction = await walletAPI.ClaimGasAsync(keyPair1.Export()); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } @@ -103,7 +103,7 @@ public async Task TestTransfer() json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); + var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(), 100); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } @@ -125,7 +125,7 @@ public async Task TestTransferfromMultiSigAccount() json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.Transfer(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); + var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.ToHexString()); } @@ -136,7 +136,7 @@ public async Task TestWaitTransaction() rpcClientMock.Setup(p => p.RpcSendAsync("getrawtransaction", It.Is(j => j[0].AsString() == transaction.Hash.ToString()))) .ReturnsAsync(new RpcTransaction { Transaction = transaction, VMState = VMState.HALT, BlockHash = UInt256.Zero, BlockTime = 100, Confirmations = 1 }.ToJson()); - var tx = await walletAPI.WaitTransaction(transaction); + var tx = await walletAPI.WaitTransactionAsync(transaction); Assert.AreEqual(VMState.HALT, tx.VMState); Assert.AreEqual(UInt256.Zero, tx.BlockHash); } From 651dd97211b07508e64e046e5a46e06094c54944 Mon Sep 17 00:00:00 2001 From: Harry Date: Tue, 15 Sep 2020 09:13:51 -0700 Subject: [PATCH 16/21] GetCommitteeAsync --- src/RpcClient/RpcClient.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 1f4d4adbe..0b7385223 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -259,9 +259,10 @@ public async Task GetValidatorsAsync() /// /// Returns the current NEO committee members. /// - public string[] GetCommittee() + public async Task GetCommitteeAsync() { - return ((JArray)RpcSend("getcommittee")).Select(p => p.AsString()).ToArray(); + var result = await RpcSendAsync("getcommittee").ConfigureAwait(false); + return ((JArray)result).Select(p => p.AsString()).ToArray(); } #endregion Blockchain From e8e3c12580744bbb66c5a0e663ad4814b205c30b Mon Sep 17 00:00:00 2001 From: Harry Date: Wed, 16 Sep 2020 08:35:52 -0700 Subject: [PATCH 17/21] add custom magic support to tx manager --- src/RpcClient/TransactionManager.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index c921d515b..9d83f6f5e 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -20,6 +20,12 @@ public class TransactionManager private class SignItem { public Contract Contract; public HashSet KeyPairs; } private readonly RpcClient rpcClient; + + /// + /// protocol settings Magic value to use for hashing transactions. + /// defaults to ProtocolSettings.Default.Magic if unspecified + /// + private readonly uint magic; /// /// The Transaction context to manage the witnesses @@ -43,9 +49,10 @@ private class SignItem { public Contract Contract; public HashSet KeyPa /// TransactionManager Constructor /// /// the RPC client to call NEO RPC API - public TransactionManager(RpcClient rpcClient) + public TransactionManager(RpcClient rpcClient, uint? magic = null) { this.rpcClient = rpcClient; + this.magic = magic ?? ProtocolSettings.Default.Magic; } /// @@ -178,7 +185,7 @@ public async Task SignAsync() SignItem item = signStore[i]; foreach (var key in item.KeyPairs) { - byte[] signature = Tx.Sign(key); + byte[] signature = Tx.Sign(key, magic); if (!context.AddSignature(item.Contract, key.PublicKey, signature)) { throw new Exception("AddSignature failed!"); From 2a9e42a165517a76b75f24e08f86b295b8daea98 Mon Sep 17 00:00:00 2001 From: Harry Date: Wed, 16 Sep 2020 08:36:31 -0700 Subject: [PATCH 18/21] fix format --- src/RpcClient/TransactionManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 9d83f6f5e..dfa86cbcf 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -20,7 +20,7 @@ public class TransactionManager private class SignItem { public Contract Contract; public HashSet KeyPairs; } private readonly RpcClient rpcClient; - + /// /// protocol settings Magic value to use for hashing transactions. /// defaults to ProtocolSettings.Default.Magic if unspecified From 59bc42945b92ec7aae49e934a7cd678926297c0f Mon Sep 17 00:00:00 2001 From: Harry Pierson Date: Fri, 18 Sep 2020 08:34:45 -0700 Subject: [PATCH 19/21] add magic param comment --- src/RpcClient/TransactionManager.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index dfa86cbcf..9c1cdf745 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -49,6 +49,10 @@ private class SignItem { public Contract Contract; public HashSet KeyPa /// TransactionManager Constructor /// /// the RPC client to call NEO RPC API + /// + /// the network Magic value to use when signing transactions. + /// Defaults to ProtocolSettings.Default.Magic if not specified. + /// public TransactionManager(RpcClient rpcClient, uint? magic = null) { this.rpcClient = rpcClient; From 0c97cbf26c392b9c3aea1dfed39e1d1c05b66d2b Mon Sep 17 00:00:00 2001 From: Harry Date: Fri, 18 Sep 2020 09:43:41 -0700 Subject: [PATCH 20/21] CR Feedback --- src/RpcClient/ContractClient.cs | 16 ++- src/RpcClient/Nep5API.cs | 15 +-- src/RpcClient/TransactionManager.cs | 126 ++++++------------ src/RpcClient/TransactionManagerFactory.cs | 57 ++++++++ .../UT_TransactionManager.cs | 20 +-- 5 files changed, 121 insertions(+), 113 deletions(-) create mode 100644 src/RpcClient/TransactionManagerFactory.cs diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index ef7589fd5..a6ffb8f28 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -15,14 +15,21 @@ namespace Neo.Network.RPC public class ContractClient { protected readonly RpcClient rpcClient; + protected readonly uint? magic; + /// /// ContractClient Constructor /// /// the RPC client to call NEO RPC methods - public ContractClient(RpcClient rpc) + /// + /// the network Magic value to use when signing transactions. + /// Defaults to ProtocolSettings.Default.Magic if not specified. + /// + public ContractClient(RpcClient rpc, uint? magic = null) { rpcClient = rpc; + this.magic = magic; } /// @@ -56,12 +63,11 @@ public async Task CreateDeployContractTxAsync(byte[] contractScript UInt160 sender = Contract.CreateSignatureRedeemScript(key.PublicKey).ToScriptHash(); Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; - Transaction tx = await new TransactionManager(rpcClient) - .MakeTransaction(script, signers) + TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient, magic); + TransactionManager manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false); + return await manager .AddSignature(key) .SignAsync().ConfigureAwait(false); - - return tx; } } } diff --git a/src/RpcClient/Nep5API.cs b/src/RpcClient/Nep5API.cs index b0f510c2e..59cadd67e 100644 --- a/src/RpcClient/Nep5API.cs +++ b/src/RpcClient/Nep5API.cs @@ -119,12 +119,12 @@ public async Task CreateTransferTxAsync(UInt160 scriptHash, KeyPair Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - var tx = await new TransactionManager(rpcClient) - .MakeTransaction(script, signers) + + TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient, magic); + TransactionManager manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false); + return await manager .AddSignature(fromKey) .SignAsync().ConfigureAwait(false); - - return tx; } /// @@ -146,12 +146,11 @@ public async Task CreateTransferTxAsync(UInt160 scriptHash, int m, byte[] script = scriptHash.MakeScript("transfer", sender, to, amount); - Transaction tx = await new TransactionManager(rpcClient) - .MakeTransaction(script, signers) + TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient, magic); + TransactionManager manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false); + return await manager .AddMultiSig(fromKeys, m, pubKeys) .SignAsync().ConfigureAwait(false); - - return tx; } } } diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 9c1cdf745..821520127 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -1,7 +1,6 @@ using Neo.Cryptography.ECC; using Neo.IO; using Neo.Network.P2P.Payloads; -using Neo.Network.RPC.Models; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.Wallets; @@ -12,6 +11,7 @@ namespace Neo.Network.RPC { + /// /// This class helps to create transaction with RPC API. /// @@ -23,74 +23,50 @@ private class SignItem { public Contract Contract; public HashSet KeyPa /// /// protocol settings Magic value to use for hashing transactions. - /// defaults to ProtocolSettings.Default.Magic if unspecified /// private readonly uint magic; /// /// The Transaction context to manage the witnesses /// - private ContractParametersContext context; + private readonly ContractParametersContext context; /// /// This container stores the keys for sign the transaction /// private readonly List signStore = new List(); - // task to manage fluent async operations - private Task fluentOperationsTask = Task.FromResult(0); - /// - /// The Transaction managed by this class + /// The Transaction managed by this instance /// - public Transaction Tx { get; private set; } + private readonly Transaction tx; + + public Transaction Tx => tx; /// /// TransactionManager Constructor /// - /// the RPC client to call NEO RPC API + /// the transaction to manage. Typically buildt + /// the RPC client to call NEO RPC API /// /// the network Magic value to use when signing transactions. /// Defaults to ProtocolSettings.Default.Magic if not specified. /// - public TransactionManager(RpcClient rpcClient, uint? magic = null) + public TransactionManager(Transaction tx, RpcClient rpcClient, uint magic) { + this.tx = tx; + this.context = new ContractParametersContext(tx); this.rpcClient = rpcClient; - this.magic = magic ?? ProtocolSettings.Default.Magic; + this.magic = magic; } /// - /// Create an unsigned Transaction object with given parameters. + /// Helper function for one-off TransactionManager creation /// - /// Transaction Script - /// Transaction Attributes - /// - public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + public static Task MakeTransactionAsync(RpcClient rpcClient, byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null, uint? magic = null) { - Tx = new Transaction - { - Version = 0, - Nonce = (uint)new Random().Next(), - Script = script, - Signers = signers ?? Array.Empty(), - Attributes = attributes ?? Array.Empty(), - }; - - context = new ContractParametersContext(Tx); - - QueueWork(async _ => - { - uint height = await rpcClient.GetBlockCountAsync().ConfigureAwait(false) - 1; - Tx.ValidUntilBlock = height + Transaction.MaxValidUntilBlockIncrement; - }); - - QueueWork(async _ => - { - RpcInvokeResult result = await rpcClient.InvokeScriptAsync(script, signers).ConfigureAwait(false); - Tx.SystemFee = long.Parse(result.GasConsumed); - }); - - return this; + var factory = new TransactionManagerFactory(rpcClient, magic); + return factory.MakeTransactionAsync(script, signers, attributes); } /// @@ -134,6 +110,24 @@ public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] pu return this; } + private void AddSignItem(Contract contract, KeyPair key) + { + if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) + { + throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); + } + + SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); + if (item is null) + { + signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); + } + else if (!item.KeyPairs.Contains(key)) + { + item.KeyPairs.Add(key); + } + } + /// /// Add Witness with contract /// @@ -141,13 +135,10 @@ public TransactionManager AddMultiSig(KeyPair[] keys, int m, params ECPoint[] pu /// The witness invocation parameters public TransactionManager AddWitness(Contract contract, params object[] parameters) { - QueueWork(() => + if (!context.Add(contract, parameters)) { - if (!context.Add(contract, parameters)) - { - throw new Exception("AddWitness failed!"); - }; - }); + throw new Exception("AddWitness failed!"); + }; return this; } @@ -167,9 +158,6 @@ public TransactionManager AddWitness(UInt160 scriptHash, params object[] paramet /// public async Task SignAsync() { - // wait for all queued work to complete - await fluentOperationsTask; - // Calculate NetworkFee Tx.Witnesses = Tx.GetScriptHashesForVerifying(null).Select(u => new Witness() { @@ -186,11 +174,10 @@ public async Task SignAsync() // Sign with signStore for (int i = 0; i < signStore.Count; i++) { - SignItem item = signStore[i]; - foreach (var key in item.KeyPairs) + foreach (var key in signStore[i].KeyPairs) { byte[] signature = Tx.Sign(key, magic); - if (!context.AddSignature(item.Contract, key.PublicKey, signature)) + if (!context.AddSignature(signStore[i].Contract, key.PublicKey, signature)) { throw new Exception("AddSignature failed!"); } @@ -206,41 +193,6 @@ public async Task SignAsync() return Tx; } - private void AddSignItem(Contract contract, KeyPair key) - { - QueueWork(() => - { - if (!Tx.GetScriptHashesForVerifying(null).Contains(contract.ScriptHash)) - { - throw new Exception($"Add SignItem error: Mismatch ScriptHash ({contract.ScriptHash.ToString()})"); - } - - SignItem item = signStore.FirstOrDefault(p => p.Contract.ScriptHash == contract.ScriptHash); - if (item is null) - { - signStore.Add(new SignItem { Contract = contract, KeyPairs = new HashSet { key } }); - } - else if (!item.KeyPairs.Contains(key)) - { - item.KeyPairs.Add(key); - } - }); - } - - private void QueueWork(Func action) - { - fluentOperationsTask = fluentOperationsTask.ContinueWith(action, TaskContinuationOptions.OnlyOnRanToCompletion); - } - - private void QueueWork(Action action) - { - QueueWork(_ => - { - action(); - return Task.FromResult(0); - }); - } - private byte[] GetVerificationScript(UInt160 hash) { foreach (var item in signStore) diff --git a/src/RpcClient/TransactionManagerFactory.cs b/src/RpcClient/TransactionManagerFactory.cs new file mode 100644 index 000000000..0f7277a2c --- /dev/null +++ b/src/RpcClient/TransactionManagerFactory.cs @@ -0,0 +1,57 @@ +using Neo.Network.P2P.Payloads; +using Neo.Network.RPC.Models; +using System; +using System.Threading.Tasks; + +namespace Neo.Network.RPC +{ + public class TransactionManagerFactory + { + private readonly RpcClient rpcClient; + + /// + /// protocol settings Magic value to use for hashing transactions. + /// defaults to ProtocolSettings.Default.Magic if unspecified + /// + private readonly uint magic; + + /// + /// TransactionManagerFactory Constructor + /// + /// the RPC client to call NEO RPC API + /// + /// the network Magic value to use when signing transactions. + /// Defaults to ProtocolSettings.Default.Magic if not specified. + /// + public TransactionManagerFactory(RpcClient rpcClient, uint? magic = null) + { + this.rpcClient = rpcClient; + this.magic = magic ?? ProtocolSettings.Default.Magic; + } + + /// + /// Create an unsigned Transaction object with given parameters. + /// + /// Transaction Script + /// Transaction Attributes + /// + public async Task MakeTransactionAsync(byte[] script, Signer[] signers = null, TransactionAttribute[] attributes = null) + { + uint blockCount = await rpcClient.GetBlockCountAsync().ConfigureAwait(false) - 1; + RpcInvokeResult invokeResult = await rpcClient.InvokeScriptAsync(script, signers).ConfigureAwait(false); + + var tx = new Transaction + { + Version = 0, + Nonce = (uint)new Random().Next(), + Script = script, + Signers = signers ?? Array.Empty(), + ValidUntilBlock = blockCount - 1 + Transaction.MaxValidUntilBlockIncrement, + SystemFee = long.Parse(invokeResult.GasConsumed), + Attributes = attributes ?? Array.Empty(), + }; + + return new TransactionManager(tx, rpcClient, magic); + } + } +} diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index d86808dc5..c5d8a1d4b 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -122,10 +122,8 @@ public static void MockInvokeScript(Mock mockClient, byte[] script, p } [TestMethod] - public void TestMakeTransaction() + public async Task TestMakeTransaction() { - txManager = new TransactionManager(rpcClientMock.Object); - Signer[] signers = new Signer[1] { new Signer @@ -136,7 +134,7 @@ public void TestMakeTransaction() }; byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers); + txManager = await TransactionManager.MakeTransactionAsync(rpcClientMock.Object, script, signers); var tx = txManager.Tx; Assert.AreEqual(WitnessScope.Global, tx.Signers[0].Scopes); @@ -145,8 +143,6 @@ public void TestMakeTransaction() [TestMethod] public async Task TestSign() { - txManager = new TransactionManager(rpcClientMock.Object); - Signer[] signers = new Signer[1] { new Signer @@ -157,7 +153,8 @@ public async Task TestSign() }; byte[] script = new byte[1]; - await txManager.MakeTransaction(script, signers) + txManager = await TransactionManager.MakeTransactionAsync(rpcClientMock.Object, script, signers); + await txManager .AddSignature(keyPair1) .SignAsync(); @@ -205,8 +202,6 @@ static async Task ThrowsAsync(Func action, bool al [TestMethod] public async Task TestSignMulti() { - txManager = new TransactionManager(multiSigMock.Object); - // Cosigner needs multi signature Signer[] signers = new Signer[1] { @@ -218,7 +213,8 @@ public async Task TestSignMulti() }; byte[] script = new byte[1]; - await txManager.MakeTransaction(script, signers) + txManager = await TransactionManager.MakeTransactionAsync(multiSigMock.Object, script, signers); + await txManager .AddMultiSig(keyPair1, 2, keyPair1.PublicKey, keyPair2.PublicKey) .AddMultiSig(keyPair2, 2, keyPair1.PublicKey, keyPair2.PublicKey) .SignAsync(); @@ -227,8 +223,6 @@ await txManager.MakeTransaction(script, signers) [TestMethod] public async Task TestAddWitness() { - txManager = new TransactionManager(rpcClientMock.Object); - // Cosigner as contract scripthash Signer[] signers = new Signer[2] { @@ -245,7 +239,7 @@ public async Task TestAddWitness() }; byte[] script = new byte[1]; - txManager.MakeTransaction(script, signers); + txManager = await TransactionManager.MakeTransactionAsync(rpcClientMock.Object, script, signers); txManager.AddWitness(UInt160.Zero); txManager.AddSignature(keyPair1); await txManager.SignAsync(); From 3a7d2cc97d3fdbe6ae27c2cbd6f8e2ba3bda4a37 Mon Sep 17 00:00:00 2001 From: Shargon Date: Mon, 12 Oct 2020 23:11:39 +0200 Subject: [PATCH 21/21] Clean enter --- src/RpcClient/TransactionManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 821520127..7e35e25f0 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -11,7 +11,6 @@ namespace Neo.Network.RPC { - /// /// This class helps to create transaction with RPC API. ///