Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust the Charge for Storage Writting #1441

Merged
merged 60 commits into from
Mar 13, 2020
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
805d370
Rebase
lock9 Dec 16, 2019
21ced64
Refactor, more tests
lock9 Dec 17, 2019
a376c48
Discarding changes
lock9 Dec 17, 2019
0239d04
Fixes, tests and refactor
lock9 Dec 19, 2019
92b256a
Calculating final fee during onPersist
lock9 Dec 19, 2019
26c50fa
Rebase
lock9 Dec 19, 2019
1fb19e4
dotnet format + missing change
lock9 Dec 19, 2019
daa4e2b
Minor improvements
lock9 Dec 19, 2019
42c6dd3
fix
lock9 Dec 19, 2019
c2aa683
Removing empty lines
lock9 Dec 19, 2019
cb33f47
add comment
eryeer Feb 6, 2020
50762dc
merge conflict
eryeer Feb 6, 2020
6238206
remove checkStorageContext
eryeer Feb 6, 2020
a600683
update ut
eryeer Feb 6, 2020
b5b0fb4
revert modification
eryeer Feb 7, 2020
96aca15
revert
eryeer Feb 7, 2020
5074592
add recycle reward gas
eryeer Feb 7, 2020
764c67d
update
eryeer Feb 7, 2020
54efe6a
fix ut
eryeer Feb 7, 2020
3174c0d
fix
eryeer Feb 7, 2020
51643d7
add OnRecycleRewardGas test
eryeer Feb 7, 2020
7131999
optimise
eryeer Feb 10, 2020
b5dac3d
update
eryeer Feb 10, 2020
1da5ebf
optimise
eryeer Feb 11, 2020
3996853
Merge branch 'master' into storage-payback
eryeer Feb 11, 2020
dfc3d7a
Removing extra space
vncoelho Feb 11, 2020
a856d44
update comment
eryeer Feb 12, 2020
ddac1f5
update static
eryeer Feb 12, 2020
5c61cbd
format
eryeer Feb 12, 2020
cbb8531
revert virtual
eryeer Feb 14, 2020
c661c41
format
eryeer Feb 14, 2020
1bf3815
update
eryeer Feb 18, 2020
5be0d71
remove ThrowIfNot
eryeer Feb 18, 2020
3d21376
update TryGet and engine notify
eryeer Feb 19, 2020
938af95
format
eryeer Feb 19, 2020
c39bb89
format
eryeer Feb 19, 2020
b8a6824
Update ApplicationEngine.cs
shargon Feb 19, 2020
ca9ab68
update mint
eryeer Feb 20, 2020
1196f86
Merge branch 'storage-payback' of github.com:eryeer/neoUT into storag…
eryeer Feb 20, 2020
d233346
format
eryeer Feb 20, 2020
e7c5d23
Fix typo
shargon Feb 20, 2020
e567bd3
Simplify
shargon Feb 20, 2020
45eaf5e
Merge branch 'master' into storage-payback
eryeer Feb 21, 2020
8eb8cf4
Merge branch 'master' into storage-payback
eryeer Feb 27, 2020
ed1d0d6
Merge branch 'master' into storage-payback
eryeer Feb 28, 2020
7134701
reset, charge only for increment of data, add put basic fee
Mar 3, 2020
1cd0e25
fix ut
Mar 3, 2020
7b0ad73
fix ut
Mar 3, 2020
d638d5c
Merge branch 'master' into storage-payback
Mar 4, 2020
0fe0c2e
Clean
shargon Mar 4, 2020
0e0b63c
add throw in GetStoragePrice if non-interface
Mar 5, 2020
bec4313
Merge branch 'storage-payback' of https://github.com/eryeer/neoUT int…
Mar 5, 2020
a4893df
fix ut
Mar 5, 2020
8acfe41
Merge branch 'master' into storage-payback
eryeer Mar 10, 2020
ffad20a
fix GetPrice parameters
Mar 11, 2020
c9e6b7a
Merge branch 'master' into storage-payback
Mar 12, 2020
2b1939e
Update InteropService.Storage.cs
erikzhang Mar 12, 2020
d683efd
add check: skeyValue.Value is null
Mar 12, 2020
073849f
reset, fix ut
Mar 12, 2020
5242131
adjust Storage.Delete price = 1 * GasPerByte
Mar 12, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/neo/IO/Caching/DataCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public TValue GetOrAdd(TKey key, Func<TValue> factory)
}
}

public TValue TryGet(TKey key)
public virtual TValue TryGet(TKey key)
eryeer marked this conversation as resolved.
Show resolved Hide resolved
{
lock (dictionary)
{
Expand Down
29 changes: 28 additions & 1 deletion src/neo/Ledger/Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,6 @@ private void OnFillMemoryPool(IEnumerable<Transaction> transactions)
MemPool.TryAdd(tx.Hash, tx);
}
// Transactions originally in the pool will automatically be reverified based on their priority.

Sender.Tell(new FillCompleted());
}

Expand Down Expand Up @@ -493,6 +492,7 @@ private void Persist(Block block)
using (SnapshotView snapshot = GetSnapshot())
{
List<ApplicationExecuted> all_application_executed = new List<ApplicationExecuted>();
List<Tuple<Transaction, long>> recycleRewardGasTxs = new List<Tuple<Transaction, long>>();
snapshot.PersistingBlock = block;
if (block.Index > 0)
{
Expand Down Expand Up @@ -522,13 +522,16 @@ private void Persist(Block block)
state.VMState = engine.Execute();
if (state.VMState == VMState.HALT)
{
if (engine.RecyclingRewardGas > 0)
recycleRewardGasTxs.Add(new Tuple<Transaction, long>(tx, engine.RecyclingRewardGas));
engine.Snapshot.Commit();
}
ApplicationExecuted application_executed = new ApplicationExecuted(engine);
Context.System.EventStream.Publish(application_executed);
all_application_executed.Add(application_executed);
}
}
RecycleRewardGas(snapshot, all_application_executed, recycleRewardGasTxs);
snapshot.BlockHashIndex.GetAndChange().Set(block);
if (block.Index == header_index.Count)
{
Expand Down Expand Up @@ -562,6 +565,30 @@ private void Persist(Block block)
OnPersistCompleted(block);
}

private void RecycleRewardGas(SnapshotView snapshot, List<ApplicationExecuted> all_application_executed, List<Tuple<Transaction, long>> recycleRewardGasTxs)
{
foreach (var tuple in recycleRewardGasTxs)
{
var tx = tuple.Item1;
var recycleRewardGas = tuple.Item2;
Script onRecycleRewardGasScript = null;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitAppCall(NativeContract.GAS.Hash, "onRecycleRewardGas", tx.Sender, recycleRewardGas);
eryeer marked this conversation as resolved.
Show resolved Hide resolved
sb.Emit(OpCode.THROWIFNOT);
onRecycleRewardGasScript = sb.ToArray();
}
using (ApplicationEngine engine = new ApplicationEngine(TriggerType.System, null, snapshot, 0, true))
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
{
engine.LoadScript(onRecycleRewardGasScript);
if (engine.Execute() != VMState.HALT) throw new InvalidOperationException();
ApplicationExecuted application_executed = new ApplicationExecuted(engine);
Context.System.EventStream.Publish(application_executed);
all_application_executed.Add(application_executed);
}
}
}

protected override void PostStop()
{
base.PostStop();
Expand Down
29 changes: 27 additions & 2 deletions src/neo/SmartContract/ApplicationEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,17 @@ public partial class ApplicationEngine : ExecutionEngine
private readonly bool testMode;
private readonly List<NotifyEventArgs> notifications = new List<NotifyEventArgs>();
private readonly List<IDisposable> disposables = new List<IDisposable>();
private readonly List<StorageKey> updatedKeys = new List<StorageKey>();

public TriggerType Trigger { get; }
public IVerifiable ScriptContainer { get; }
public StoreView Snapshot { get; }
public long GasConsumed { get; private set; } = 0;

/// <summary>
/// RecyclingRewardGas shows how many gas should be recycled as a reward
/// </summary>
public long RecyclingRewardGas { get; private set; } = 0;
public UInt160 CurrentScriptHash => CurrentContext?.GetState<ExecutionContextState>().ScriptHash;
public UInt160 CallingScriptHash => CurrentContext?.GetState<ExecutionContextState>().CallingScriptHash;
public UInt160 EntryScriptHash => EntryContext?.GetState<ExecutionContextState>().ScriptHash;
Expand All @@ -46,9 +52,28 @@ internal T AddDisposable<T>(T disposable) where T : IDisposable
return disposable;
}

internal bool HasUpdatedKey(StorageKey key)
{
return updatedKeys.Contains(key);
}

internal bool TryAddUpdatedKey(StorageKey key)
{
bool keyAdded = false;
if (!updatedKeys.Contains(key))
{
updatedKeys.Add(key);
keyAdded = true;
}
return keyAdded;
}

private bool AddGas(long gas)
{
GasConsumed = checked(GasConsumed + gas);
if (gas < 0)
RecyclingRewardGas = checked(RecyclingRewardGas + (-gas));
eryeer marked this conversation as resolved.
Show resolved Hide resolved
else
GasConsumed = checked(GasConsumed + gas);
return testMode || GasConsumed <= gas_amount;
}

Expand Down Expand Up @@ -78,7 +103,7 @@ public override void Dispose()

protected override bool OnSysCall(uint method)
{
if (!AddGas(InteropService.GetPrice(method, CurrentContext.EvaluationStack)))
if (!AddGas(InteropService.GetPrice(method, this)))
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
return false;
return InteropService.Invoke(this, method);
}
Expand Down
34 changes: 34 additions & 0 deletions src/neo/SmartContract/InteropDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ public class InteropDescriptor
internal Func<ApplicationEngine, bool> Handler { get; }
public long Price { get; }
public Func<EvaluationStack, long> PriceCalculator { get; }
public Func<ApplicationEngine, long> StoragePriceCalculator { get; }
public bool IsStateful { get; } = false;
public TriggerType AllowedTriggers { get; }
public CallFlags RequiredCallFlags { get; }

Expand All @@ -19,6 +21,13 @@ internal InteropDescriptor(string method, Func<ApplicationEngine, bool> handler,
this.Price = price;
}

internal InteropDescriptor(string method, Func<ApplicationEngine, bool> handler, Func<ApplicationEngine, long> priceCalculator, TriggerType allowedTriggers, CallFlags requiredCallFlags)
: this(method, handler, allowedTriggers, requiredCallFlags)
{
this.StoragePriceCalculator = priceCalculator;
this.IsStateful = true;
}

internal InteropDescriptor(string method, Func<ApplicationEngine, bool> handler, Func<EvaluationStack, long> priceCalculator, TriggerType allowedTriggers, CallFlags requiredCallFlags)
: this(method, handler, allowedTriggers, requiredCallFlags)
{
Expand All @@ -34,8 +43,33 @@ private InteropDescriptor(string method, Func<ApplicationEngine, bool> handler,
this.RequiredCallFlags = requiredCallFlags;
}

public long GetPrice()
{
return Price;
}

public long GetPrice(ApplicationEngine applicationEngine)
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
{
long price = Price;
if (!IsStateful && PriceCalculator != null)
{
price = PriceCalculator(applicationEngine.CurrentContext.EvaluationStack);
}
else if (IsStateful && StoragePriceCalculator != null)
{
price = StoragePriceCalculator(applicationEngine);
}
return price;
}

public long GetPrice(EvaluationStack stack)
{
#if DEBUG
if (IsStateful)
{
throw new InvalidOperationException();
}
#endif
return PriceCalculator is null ? Price : PriceCalculator(stack);
}

Expand Down
52 changes: 49 additions & 3 deletions src/neo/SmartContract/InteropService.Storage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ partial class InteropService
public static class Storage
{
public const long GasPerByte = 100000;
public const long GasPerReleasedByte = -GasPerByte;
public const int MaxKeySize = 64;
public const int MaxValueSize = ushort.MaxValue;

Expand All @@ -22,11 +23,54 @@ public static class Storage
public static readonly InteropDescriptor Find = Register("System.Storage.Find", Storage_Find, 0_01000000, TriggerType.Application, CallFlags.None);
public static readonly InteropDescriptor Put = Register("System.Storage.Put", Storage_Put, GetStoragePrice, TriggerType.Application, CallFlags.AllowModifyStates);
public static readonly InteropDescriptor PutEx = Register("System.Storage.PutEx", Storage_PutEx, GetStoragePrice, TriggerType.Application, CallFlags.AllowModifyStates);
public static readonly InteropDescriptor Delete = Register("System.Storage.Delete", Storage_Delete, 0_01000000, TriggerType.Application, CallFlags.AllowModifyStates);
public static readonly InteropDescriptor Delete = Register("System.Storage.Delete", Storage_Delete, GetDeletePrice, TriggerType.Application, CallFlags.AllowModifyStates);

private static long GetStoragePrice(EvaluationStack stack)
private static long GetDeletePrice(ApplicationEngine engine)
{
return (stack.Peek(1).GetByteLength() + stack.Peek(2).GetByteLength()) * GasPerByte;
var stack = engine.CurrentContext.EvaluationStack;
var key = stack.Peek(1);
if (!(engine.CurrentContext.EvaluationStack.Peek() is InteropInterface _interface))
return 0_01000000;
StorageContext context = _interface.GetInterface<StorageContext>();
StorageKey skey = new StorageKey
{
Id = context.Id,
Key = key.GetSpan().ToArray()
};
var skeyValue = engine.Snapshot.Storages.TryGet(skey);
if (skeyValue == null || skeyValue.Value == null || skeyValue.Value.Length == 0 || engine.HasUpdatedKey(skey))
return 0_01000000;
return (skeyValue.Value.Length + key.GetByteLength()) * GasPerReleasedByte;
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
}

private static long GetStoragePrice(ApplicationEngine engine)
{
var stack = engine.CurrentContext.EvaluationStack;
var key = stack.Peek(1);
var value = stack.Peek(2);
var newDataSize = value.IsNull ? 0 : value.GetByteLength();
if (!(engine.CurrentContext.EvaluationStack.Peek() is InteropInterface _interface))
return (key.GetByteLength() + newDataSize) * GasPerByte;
shargon marked this conversation as resolved.
Show resolved Hide resolved
StorageContext context = _interface.GetInterface<StorageContext>();
StorageKey skey = new StorageKey
{
Id = context.Id,
Key = key.GetSpan().ToArray()
};
var skeyValue = engine.Snapshot.Storages.TryGet(skey);
if (skeyValue == null || skeyValue.Value == null || skeyValue.Value.Length == 0 || engine.HasUpdatedKey(skey))
return (key.GetByteLength() + newDataSize) * GasPerByte;
var currentOccupiedBytes = skeyValue.Value.Length;
if (newDataSize <= currentOccupiedBytes)
{
var releasedBytes = currentOccupiedBytes - newDataSize;
return releasedBytes * GasPerReleasedByte;
}
else
{
var reusedBytes = currentOccupiedBytes;
return (newDataSize - reusedBytes) * GasPerByte;
}
}

private static bool PutExInternal(ApplicationEngine engine, StorageContext context, byte[] key, byte[] value, StorageFlags flags)
Expand Down Expand Up @@ -54,6 +98,7 @@ private static bool PutExInternal(ApplicationEngine engine, StorageContext conte
item.Value = value;
item.IsConstant = flags.HasFlag(StorageFlags.Constant);
}
engine.TryAddUpdatedKey(skey);
return true;
}

Expand Down Expand Up @@ -165,6 +210,7 @@ private static bool Storage_Delete(ApplicationEngine engine)
};
if (engine.Snapshot.Storages.TryGet(key)?.IsConstant == true) return false;
engine.Snapshot.Storages.Delete(key);
engine.TryAddUpdatedKey(key);
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
return true;
}
return false;
Expand Down
17 changes: 17 additions & 0 deletions src/neo/SmartContract/InteropService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ static InteropService()
t.GetFields()[0].GetValue(null);
}

public static long GetPrice(uint hash)
{
return methods[hash].GetPrice();
eryeer marked this conversation as resolved.
Show resolved Hide resolved
}

public static long GetPrice(uint hash, ApplicationEngine applicationEngine)
{
return methods[hash].GetPrice(applicationEngine);
eryeer marked this conversation as resolved.
Show resolved Hide resolved
}

public static long GetPrice(uint hash, EvaluationStack stack)
{
return methods[hash].GetPrice(stack);
Expand Down Expand Up @@ -50,5 +60,12 @@ private static InteropDescriptor Register(string method, Func<ApplicationEngine,
methods.Add(descriptor.Hash, descriptor);
return descriptor;
}

private static InteropDescriptor Register(string method, Func<ApplicationEngine, bool> handler, Func<ApplicationEngine, long> priceCalculator, TriggerType allowedTriggers, CallFlags flags)
{
InteropDescriptor descriptor = new InteropDescriptor(method, handler, priceCalculator, allowedTriggers, flags);
methods.Add(descriptor.Hash, descriptor);
return descriptor;
}
}
}
10 changes: 10 additions & 0 deletions src/neo/SmartContract/Native/Tokens/GasToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ protected override bool OnPersist(ApplicationEngine engine)
return true;
}

[ContractMethod(0, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.Hash160, ContractParameterType.Integer }, ParameterNames = new[] { "account", "amount" })]
private StackItem OnRecycleRewardGas(ApplicationEngine engine, VMArray args)
{
if (engine.Trigger != TriggerType.System) return false;
eryeer marked this conversation as resolved.
Show resolved Hide resolved
UInt160 acount = new UInt160(args[0].GetSpan());
BigInteger amount = args[1].GetBigInteger();
Mint(engine, acount, amount);
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
return true;
}

[ContractMethod(0_01000000, ContractParameterType.Integer, ParameterTypes = new[] { ContractParameterType.Integer }, ParameterNames = new[] { "index" }, SafeMethod = true)]
private StackItem GetSysFeeAmount(ApplicationEngine engine, VMArray args)
{
Expand Down
4 changes: 2 additions & 2 deletions src/neo/Wallets/Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ public static long CalculateNetworkFee(byte[] witness_script, ref int size)
if (witness_script.IsSignatureContract())
{
size += 67 + witness_script.GetVarSize();
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify, null);
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify);
}
else if (witness_script.IsMultiSigContract(out int m, out int n))
{
Expand All @@ -366,7 +366,7 @@ public static long CalculateNetworkFee(byte[] witness_script, ref int size)
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] * n;
using (ScriptBuilder sb = new ScriptBuilder())
networkFee += ApplicationEngine.OpCodePrices[(OpCode)sb.EmitPush(n).ToArray()[0]];
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify, null) * n;
networkFee += ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify) * n;
}
else
{
Expand Down
49 changes: 49 additions & 0 deletions tests/neo.UnitTests/SmartContract/Native/Tokens/UT_GasToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Neo.Network.P2P.Payloads;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.SmartContract.Native.Tokens;
using Neo.UnitTests.Extensions;
using Neo.VM;
using Neo.VM.Types;
Expand Down Expand Up @@ -179,5 +180,53 @@ public void TestGetSysFeeAmount2()

NativeContract.GAS.GetSysFeeAmount(snapshot, 1).Should().Be(sys_fee);
}

[TestMethod]
public void TestOnRecycleRewardGas()
{
var wallet = TestUtils.GenerateTestWallet();
var snapshot = Blockchain.Singleton.GetSnapshot();

using (var unlock = wallet.Unlock("123"))
{
var acc = wallet.CreateAccount();

// Fake balance
var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash);

var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem
{
Value = new Nep5AccountState().ToByteArray()
});

entry.Value = new Nep5AccountState()
{
Balance = 10000 * NativeContract.GAS.Factor
}
.ToByteArray();

snapshot.Commit();

NativeContract.GAS.BalanceOf(snapshot, acc.ScriptHash).Should().Be(10000 * NativeContract.GAS.Factor);

var tx = TestUtils.GetTransaction();
tx.Sender = acc.ScriptHash;
var recycleRewardGas = (long)(1000 * NativeContract.GAS.Factor);

Script onRecycleRewardGasScript = null;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitAppCall(NativeContract.GAS.Hash, "onRecycleRewardGas", tx.Sender, recycleRewardGas);
sb.Emit(OpCode.THROWIFNOT);
onRecycleRewardGasScript = sb.ToArray();
}
using (ApplicationEngine engine = new ApplicationEngine(TriggerType.System, null, snapshot, 0, true))
{
engine.LoadScript(onRecycleRewardGasScript);
engine.Execute().Should().Be(VMState.HALT);
}
NativeContract.GAS.BalanceOf(snapshot, acc.ScriptHash).Should().Be(11000 * NativeContract.GAS.Factor);
}
}
}
}
Loading