Skip to content

Commit

Permalink
Update dependencies (#338)
Browse files Browse the repository at this point in the history
  • Loading branch information
shargon authored Sep 16, 2020
1 parent c4de92b commit a849d05
Show file tree
Hide file tree
Showing 19 changed files with 124 additions and 50 deletions.
20 changes: 15 additions & 5 deletions src/LevelDBStore/IO/Data/LevelDB/DB.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ public byte[] Get(ReadOptions options, byte[] key)
IntPtr value = Native.leveldb_get(handle, options.handle, key, (UIntPtr)key.Length, out UIntPtr length, out IntPtr error);
try
{
if (error != IntPtr.Zero)
{
Native.leveldb_free(error);
return null;
}
NativeHelper.CheckError(error);
return value.ToByteArray(length);
}
finally
Expand All @@ -50,6 +46,20 @@ public byte[] Get(ReadOptions options, byte[] key)
}
}

public bool Contains(ReadOptions options, byte[] key)
{
IntPtr value = Native.leveldb_get(handle, options.handle, key, (UIntPtr)key.Length, out _, out IntPtr error);
NativeHelper.CheckError(error);

if (value != IntPtr.Zero)
{
Native.leveldb_free(value);
return true;
}

return false;
}

public Snapshot GetSnapshot()
{
return new Snapshot(handle);
Expand Down
2 changes: 2 additions & 0 deletions src/LevelDBStore/IO/Data/LevelDB/Native.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Neo.IO.Data.LevelDB
Expand Down Expand Up @@ -238,6 +239,7 @@ public static extern IntPtr /* leveldb_comparator_t* */

internal static class NativeHelper
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CheckError(IntPtr error)
{
if (error != IntPtr.Zero)
Expand Down
2 changes: 1 addition & 1 deletion src/LevelDBStore/LevelDBStore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Neo" Version="3.0.0-preview3-00" />
<PackageReference Include="Neo" Version="3.0.0-CI01025" />
</ItemGroup>

</Project>
5 changes: 5 additions & 0 deletions src/LevelDBStore/Plugins/Storage/Snapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public void Put(byte table, byte[] key, byte[] value)
batch.Put(LHelper.CreateKey(table, key), value);
}

public bool Contains(byte table, byte[] key)
{
return db.Contains(options, LHelper.CreateKey(table, key));
}

public byte[] TryGet(byte table, byte[] key)
{
return db.Get(options, LHelper.CreateKey(table, key));
Expand Down
5 changes: 5 additions & 0 deletions src/LevelDBStore/Plugins/Storage/Store.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ public void PutSync(byte table, byte[] key, byte[] value)
db.Put(WriteOptions.SyncWrite, LHelper.CreateKey(table, key), value);
}

public bool Contains(byte table, byte[] key)
{
return db.Contains(ReadOptions.Default, LHelper.CreateKey(table, key));
}

public byte[] TryGet(byte table, byte[] key)
{
return db.Get(ReadOptions.Default, LHelper.CreateKey(table, key));
Expand Down
5 changes: 5 additions & 0 deletions src/RocksDBStore/Plugins/Storage/Snapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ public void Put(byte table, byte[] key, byte[] value)
yield return (it.Key(), it.Value());
}

public bool Contains(byte table, byte[] key)
{
return db.Get(key ?? Array.Empty<byte>(), store.GetFamily(table), options) != null;
}

public byte[] TryGet(byte table, byte[] key)
{
return db.Get(key ?? Array.Empty<byte>(), store.GetFamily(table), options);
Expand Down
5 changes: 5 additions & 0 deletions src/RocksDBStore/Plugins/Storage/Store.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ public ISnapshot GetSnapshot()
yield return (it.Key(), it.Value());
}

public bool Contains(byte table, byte[] key)
{
return db.Get(key ?? Array.Empty<byte>(), GetFamily(table), Options.ReadDefault) != null;
}

public byte[] TryGet(byte table, byte[] key)
{
return db.Get(key ?? Array.Empty<byte>(), GetFamily(table), Options.ReadDefault);
Expand Down
2 changes: 1 addition & 1 deletion src/RocksDBStore/RocksDBStore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Neo" Version="3.0.0-preview3-00" />
<PackageReference Include="Neo" Version="3.0.0-CI01025" />
<PackageReference Include="RocksDbNative" Version="6.2.2" />
<PackageReference Include="RocksDbSharp" Version="6.2.2" />
</ItemGroup>
Expand Down
11 changes: 11 additions & 0 deletions src/RpcClient/RpcClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,17 @@ public RpcTransaction GetRawTransaction(string txHash)
return RpcTransaction.FromJson(RpcSend("getrawtransaction", txHash, true));
}

/// <summary>
/// Calculate network fee
/// </summary>
/// <param name="tx">Transaction</param>
/// <returns>NetworkFee</returns>
public long CalculateNetworkFee(Transaction tx)
{
var json = RpcSend("calculatenetworkfee", Convert.ToBase64String(tx.ToArray()));
return (long)json["networkfee"].AsNumber();
}

/// <summary>
/// Returns the stored value, according to the contract script hash (or Id) and the stored key.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/RpcClient/RpcClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Neo" Version="3.0.0-preview3-00" />
<PackageReference Include="Neo" Version="3.0.0-CI01025" />
</ItemGroup>

</Project>
51 changes: 18 additions & 33 deletions src/RpcClient/TransactionManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Network.RPC.Models;
using Neo.SmartContract;
Expand Down Expand Up @@ -77,37 +76,6 @@ public TransactionManager MakeTransaction(byte[] script, Signer[] signers = null
return this;
}

/// <summary>
/// Calculate NetworkFee
/// </summary>
/// <returns></returns>
private long 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
{
witness_script = rpcClient.GetContractState(hash.ToString())?.Script;
}
catch { }
}

if (witness_script is null) continue;
networkFee += Wallet.CalculateNetworkFee(witness_script, ref size);
}
networkFee += size * policyAPI.GetFeePerByte();
return networkFee;
}

/// <summary>
/// Add Signature
/// </summary>
Expand Down Expand Up @@ -197,7 +165,14 @@ public TransactionManager AddWitness(UInt160 scriptHash, params object[] paramet
public TransactionManager Sign()
{
// Calculate NetworkFee
Tx.NetworkFee = CalculateNetworkFee();
Tx.Witnesses = Tx.GetScriptHashesForVerifying(null).Select(u => new Witness()
{
InvocationScript = Array.Empty<byte>(),
VerificationScript = GetVerificationScript(u)
}).ToArray();
Tx.NetworkFee = rpcClient.CalculateNetworkFee(Tx);
Tx.Witnesses = null;

var gasBalance = nep5API.BalanceOf(NativeContract.GAS.Hash, Tx.Sender);
if (gasBalance < Tx.SystemFee + Tx.NetworkFee)
throw new InvalidOperationException($"Insufficient GAS in address: {Tx.Sender.ToAddress()}");
Expand All @@ -221,5 +196,15 @@ public TransactionManager Sign()
Tx.Witnesses = context.GetWitnesses();
return this;
}

private byte[] GetVerificationScript(UInt160 hash)
{
foreach (var item in signStore)
{
if (item.Contract.ScriptHash == hash) return item.Contract.Script;
}

return Array.Empty<byte>();
}
}
}
2 changes: 1 addition & 1 deletion src/RpcClient/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public static Signer SignerFromJson(JObject json)
public static ConsensusData ConsensusDataFromJson(JObject json)
{
ConsensusData block = new ConsensusData();
block.PrimaryIndex = (uint)json["primary"].AsNumber();
block.PrimaryIndex = (byte)json["primary"].AsNumber();
block.Nonce = ulong.Parse(json["nonce"].AsString(), NumberStyles.HexNumber);
return block;
}
Expand Down
5 changes: 5 additions & 0 deletions src/RpcNep5Tracker/DbCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ protected override TValue GetInternal(TKey key)
return TryGetInternal(key) ?? throw new InvalidOperationException();
}

protected override bool ContainsInternal(TKey key)
{
return db.Contains(options, CreateKey(prefix, key));
}

protected override TValue TryGetInternal(TKey key)
{
return db.Get(options, CreateKey(prefix, key))?.AsSerializable<TValue>();
Expand Down
4 changes: 2 additions & 2 deletions src/RpcServer/RpcServer.Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,10 @@ private JObject GetTransactionHeight(JArray _params)
}

[RpcMethod]
private JObject GetValidators(JArray _params)
private JObject GetNextBlockValidators(JArray _params)
{
using SnapshotView snapshot = Blockchain.Singleton.GetSnapshot();
var validators = NativeContract.NEO.GetValidators(snapshot);
var validators = NativeContract.NEO.GetNextBlockValidators(snapshot);
return NativeContract.NEO.GetCandidates(snapshot).Select(p =>
{
JObject validator = new JObject();
Expand Down
29 changes: 28 additions & 1 deletion src/RpcServer/RpcServer.Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using Neo.IO;
using Neo.IO.Json;
using Neo.Ledger;
using Neo.Network.P2P;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
Expand All @@ -14,6 +13,7 @@
using Neo.Wallets.NEP6;
using Neo.Wallets.SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
Expand All @@ -23,6 +23,23 @@ namespace Neo.Plugins
{
partial class RpcServer
{
private class DummyWallet : Wallet
{
public DummyWallet() : base("") { }
public override string Name => "";
public override Version Version => new Version();

public override bool ChangePassword(string oldPassword, string newPassword) => false;
public override bool Contains(UInt160 scriptHash) => false;
public override WalletAccount CreateAccount(byte[] privateKey) => null;
public override WalletAccount CreateAccount(Contract contract, KeyPair key = null) => null;
public override WalletAccount CreateAccount(UInt160 scriptHash) => null;
public override bool DeleteAccount(UInt160 scriptHash) => false;
public override WalletAccount GetAccount(UInt160 scriptHash) => null;
public override IEnumerable<WalletAccount> GetAccounts() => Array.Empty<WalletAccount>();
public override bool VerifyPassword(string password) => false;
}

private Wallet wallet;

private void CheckWallet()
Expand Down Expand Up @@ -97,6 +114,16 @@ private JObject ImportPrivKey(JArray _params)
};
}

[RpcMethod]
private JObject CalculateNetworkFee(JArray _params)
{
byte[] tx = Convert.FromBase64String(_params[0].AsString());

JObject account = new JObject();
account["networkfee"] = (wallet ?? new DummyWallet()).CalculateNetworkFee(Blockchain.Singleton.GetSnapshot(), tx.AsSerializable<Transaction>());
return account;
}

[RpcMethod]
private JObject ListAddress(JArray _params)
{
Expand Down
2 changes: 1 addition & 1 deletion src/RpcServer/RpcServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" />
<PackageReference Include="Neo" Version="3.0.0-CI00986" />
<PackageReference Include="Neo" Version="3.0.0-CI01025" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/StatesDumper/StatesDumper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Neo" Version="3.0.0-preview3-00" />
<PackageReference Include="Neo" Version="3.0.0-CI01025" />
<PackageReference Include="Neo.ConsoleService" Version="1.0.0" />
</ItemGroup>

Expand Down
17 changes: 15 additions & 2 deletions tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ public static Mock<RpcClient> MockRpcClient(UInt160 sender, byte[] script)
// MockHeight
mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable();

// calculatenetworkfee
var networkfee = new JObject();
networkfee["networkfee"] = 100000000;
mockRpc.Setup(p => p.RpcSend("calculatenetworkfee", It.Is<JObject[]>(u => true)))
.Returns(networkfee)
.Verifiable();

// MockGasBalance
byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", sender);
var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") };
Expand All @@ -72,6 +79,13 @@ public static Mock<RpcClient> MockMultiSig(UInt160 multiHash, byte[] script)
// MockHeight
mockRpc.Setup(p => p.RpcSend("getblockcount")).Returns(100).Verifiable();

// calculatenetworkfee
var networkfee = new JObject();
networkfee["networkfee"] = 100000000;
mockRpc.Setup(p => p.RpcSend("calculatenetworkfee", It.Is<JObject[]>(u => true)))
.Returns(networkfee)
.Verifiable();

// MockGasBalance
byte[] balanceScript = NativeContract.GAS.Hash.MakeScript("balanceOf", multiHash);
var balanceResult = new ContractParameter() { Type = ContractParameterType.Integer, Value = BigInteger.Parse("10000000000000000") };
Expand Down Expand Up @@ -152,8 +166,7 @@ public void TestSign()

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(100000000/*Mock*/, tx.NetworkFee);
Assert.AreEqual(100, tx.SystemFee);

// duplicate sign should not add new witness
Expand Down
3 changes: 2 additions & 1 deletion tests/Neo.Plugins.Storage.Tests/StoreTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Persistence;
using System;

namespace Neo.Plugins.Storage.Tests
{
Expand Down Expand Up @@ -57,9 +56,11 @@ private void TestStorage(IStore store)
store.Put(0, new byte[] { 0x01, 0x02 }, new byte[] { 0x03, 0x04 });
ret = store.TryGet(0, new byte[] { 0x01, 0x02 });
CollectionAssert.AreEqual(new byte[] { 0x03, 0x04 }, ret);
Assert.IsTrue(store.Contains(0, new byte[] { 0x01, 0x02 }));

ret = store.TryGet(1, new byte[] { 0x01, 0x02 });
Assert.IsNull(ret);
Assert.IsFalse(store.Contains(1, new byte[] { 0x01, 0x02 }));

store.Delete(0, new byte[] { 0x01, 0x02 });

Expand Down

0 comments on commit a849d05

Please sign in to comment.