Skip to content

Commit

Permalink
[Neo Core] Obsolete applicationengine snapshot (#3436)
Browse files Browse the repository at this point in the history
* Obsolete applicationengine snapshot

* fix UT names

* fix executioncontextstate

---------

Co-authored-by: Shargon <[email protected]>
Co-authored-by: NGD Admin <[email protected]>
  • Loading branch information
3 people authored Jul 29, 2024
1 parent 97a4417 commit eb167b3
Show file tree
Hide file tree
Showing 51 changed files with 875 additions and 855 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected override void DeserializeWithoutType(ref MemoryReader reader, int maxN
public override bool Match(ApplicationEngine engine)
{
engine.ValidateCallFlags(CallFlags.ReadStates);
ContractState contract = NativeContract.ContractManagement.GetContract(engine.Snapshot, engine.CallingScriptHash);
ContractState contract = NativeContract.ContractManagement.GetContract(engine.SnapshotCache, engine.CallingScriptHash);
return contract is not null && contract.Manifest.Groups.Any(p => p.PubKey.Equals(Group));
}

Expand Down
2 changes: 1 addition & 1 deletion src/Neo/Network/P2P/Payloads/Conditions/GroupCondition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected override void DeserializeWithoutType(ref MemoryReader reader, int maxN
public override bool Match(ApplicationEngine engine)
{
engine.ValidateCallFlags(CallFlags.ReadStates);
ContractState contract = NativeContract.ContractManagement.GetContract(engine.Snapshot, engine.CurrentScriptHash);
ContractState contract = NativeContract.ContractManagement.GetContract(engine.SnapshotCache, engine.CurrentScriptHash);
return contract is not null && contract.Manifest.Groups.Any(p => p.PubKey.Equals(Group));
}

Expand Down
4 changes: 2 additions & 2 deletions src/Neo/SmartContract/ApplicationEngine.Contract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ protected internal void CallContract(UInt160 contractHash, string method, CallFl
if ((callFlags & ~CallFlags.All) != 0)
throw new ArgumentOutOfRangeException(nameof(callFlags));

ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash);
ContractState contract = NativeContract.ContractManagement.GetContract(SnapshotCache, contractHash);
if (contract is null) throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}.{method}");
ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method, args.Count);
if (md is null) throw new InvalidOperationException($"Method \"{method}\" with {args.Count} parameter(s) doesn't exist in the contract {contractHash}.");
Expand All @@ -96,7 +96,7 @@ protected internal void CallNativeContract(byte version)
NativeContract contract = NativeContract.GetContract(CurrentScriptHash);
if (contract is null)
throw new InvalidOperationException("It is not allowed to use \"System.Contract.CallNative\" directly.");
if (!contract.IsActive(ProtocolSettings, NativeContract.Ledger.CurrentIndex(Snapshot)))
if (!contract.IsActive(ProtocolSettings, NativeContract.Ledger.CurrentIndex(SnapshotCache)))
throw new InvalidOperationException($"The native contract {contract.Name} is not active.");
contract.Invoke(this, version);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Neo/SmartContract/ApplicationEngine.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ protected internal bool CheckWitnessInternal(UInt160 hash)
}
else
{
OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id);
signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers;
OracleRequest request = NativeContract.Oracle.GetRequest(SnapshotCache, response.Id);
signers = NativeContract.Ledger.GetTransaction(SnapshotCache, request.OriginalTxid).Signers;
}
Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash));
if (signer is null) return false;
Expand All @@ -280,7 +280,7 @@ protected internal bool CheckWitnessInternal(UInt160 hash)
ValidateCallFlags(CallFlags.ReadStates);

// only for non-Transaction types (Block, etc)
return ScriptContainer.GetScriptHashesForVerifying(Snapshot).Contains(hash);
return ScriptContainer.GetScriptHashesForVerifying(SnapshotCache).Contains(hash);
}

/// <summary>
Expand Down
14 changes: 7 additions & 7 deletions src/Neo/SmartContract/ApplicationEngine.Storage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ partial class ApplicationEngine
/// <returns>The storage context for the current contract.</returns>
protected internal StorageContext GetStorageContext()
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
ContractState contract = NativeContract.ContractManagement.GetContract(SnapshotCache, CurrentScriptHash);
return new StorageContext
{
Id = contract.Id,
Expand All @@ -92,7 +92,7 @@ protected internal StorageContext GetStorageContext()
/// <returns>The storage context for the current contract.</returns>
protected internal StorageContext GetReadOnlyContext()
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
ContractState contract = NativeContract.ContractManagement.GetContract(SnapshotCache, CurrentScriptHash);
return new StorageContext
{
Id = contract.Id,
Expand Down Expand Up @@ -126,7 +126,7 @@ protected internal static StorageContext AsReadOnly(StorageContext context)
/// <returns>The value of the entry. Or <see langword="null"/> if the entry doesn't exist.</returns>
protected internal ReadOnlyMemory<byte>? Get(StorageContext context, byte[] key)
{
return Snapshot.TryGet(new StorageKey
return SnapshotCache.TryGet(new StorageKey
{
Id = context.Id,
Key = key
Expand Down Expand Up @@ -155,7 +155,7 @@ protected internal IIterator Find(StorageContext context, byte[] prefix, FindOpt
throw new ArgumentException(null, nameof(options));
byte[] prefix_key = StorageKey.CreateSearchPrefix(context.Id, prefix);
SeekDirection direction = options.HasFlag(FindOptions.Backwards) ? SeekDirection.Backward : SeekDirection.Forward;
return new StorageIterator(Snapshot.Find(prefix_key, direction).GetEnumerator(), prefix.Length, options);
return new StorageIterator(SnapshotCache.Find(prefix_key, direction).GetEnumerator(), prefix.Length, options);
}

/// <summary>
Expand All @@ -177,11 +177,11 @@ protected internal void Put(StorageContext context, byte[] key, byte[] value)
Id = context.Id,
Key = key
};
StorageItem item = Snapshot.GetAndChange(skey);
StorageItem item = SnapshotCache.GetAndChange(skey);
if (item is null)
{
newDataSize = key.Length + value.Length;
Snapshot.Add(skey, item = new StorageItem());
SnapshotCache.Add(skey, item = new StorageItem());
}
else
{
Expand All @@ -208,7 +208,7 @@ protected internal void Put(StorageContext context, byte[] key, byte[] value)
protected internal void Delete(StorageContext context, byte[] key)
{
if (context.IsReadOnly) throw new ArgumentException(null, nameof(context));
Snapshot.Delete(new StorageKey
SnapshotCache.Delete(new StorageKey
{
Id = context.Id,
Key = key
Expand Down
30 changes: 18 additions & 12 deletions src/Neo/SmartContract/ApplicationEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public partial class ApplicationEngine : ExecutionEngine
// In the unit of datoshi, 1 datoshi = 1e-8 GAS, 1 GAS = 1e8 datoshi
private readonly long _feeAmount;
private Dictionary<Type, object> states;
private readonly DataCache originalSnapshot;
private readonly DataCache originalSnapshotCache;
private List<NotifyEventArgs> notifications;
private List<IDisposable> disposables;
private readonly Dictionary<UInt160, int> invocationCounter = new();
Expand Down Expand Up @@ -95,7 +95,13 @@ public partial class ApplicationEngine : ExecutionEngine
/// <summary>
/// The snapshot used to read or write data.
/// </summary>
public DataCache Snapshot => CurrentContext?.GetState<ExecutionContextState>().Snapshot ?? originalSnapshot;
[Obsolete("This property is deprecated. Use SnapshotCache instead.")]
public DataCache Snapshot => CurrentContext?.GetState<ExecutionContextState>().SnapshotCache ?? originalSnapshotCache;

/// <summary>
/// The snapshotcache <see cref="SnapshotCache"/> used to read or write data.
/// </summary>
public DataCache SnapshotCache => CurrentContext?.GetState<ExecutionContextState>().SnapshotCache ?? originalSnapshotCache;

/// <summary>
/// The block being persisted. This field could be <see langword="null"/> if the <see cref="Trigger"/> is <see cref="TriggerType.Verification"/>.
Expand Down Expand Up @@ -164,26 +170,26 @@ public virtual UInt160 CallingScriptHash
/// </summary>
/// <param name="trigger">The trigger of the execution.</param>
/// <param name="container">The container of the script.</param>
/// <param name="snapshot">The snapshot used by the engine during execution.</param>
/// <param name="snapshotCache">The snapshot used by the engine during execution.</param>
/// <param name="persistingBlock">The block being persisted. It should be <see langword="null"/> if the <paramref name="trigger"/> is <see cref="TriggerType.Verification"/>.</param>
/// <param name="settings">The <see cref="Neo.ProtocolSettings"/> used by the engine.</param>
/// <param name="gas">The maximum gas, in the unit of datoshi, used in this execution. The execution will fail when the gas is exhausted.</param>
/// <param name="diagnostic">The diagnostic to be used by the <see cref="ApplicationEngine"/>.</param>
/// <param name="jumpTable">The jump table to be used by the <see cref="ApplicationEngine"/>.</param>
protected unsafe ApplicationEngine(
TriggerType trigger, IVerifiable container, DataCache snapshot, Block persistingBlock,
TriggerType trigger, IVerifiable container, DataCache snapshotCache, Block persistingBlock,
ProtocolSettings settings, long gas, IDiagnostic diagnostic, JumpTable jumpTable = null)
: base(jumpTable ?? DefaultJumpTable)
{
Trigger = trigger;
ScriptContainer = container;
originalSnapshot = snapshot;
originalSnapshotCache = snapshotCache;
PersistingBlock = persistingBlock;
ProtocolSettings = settings;
_feeAmount = gas;
Diagnostic = diagnostic;
ExecFeeFactor = snapshot is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultExecFeeFactor : NativeContract.Policy.GetExecFeeFactor(snapshot);
StoragePrice = snapshot is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultStoragePrice : NativeContract.Policy.GetStoragePrice(snapshot);
ExecFeeFactor = snapshotCache is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultExecFeeFactor : NativeContract.Policy.GetExecFeeFactor(snapshotCache);
StoragePrice = snapshotCache is null || persistingBlock?.Index == 0 ? PolicyContract.DefaultStoragePrice : NativeContract.Policy.GetStoragePrice(snapshotCache);
nonceData = container is Transaction tx ? tx.Hash.ToArray()[..16] : new byte[16];
if (persistingBlock is not null)
{
Expand Down Expand Up @@ -274,7 +280,7 @@ internal void Throw(Exception ex)

private ExecutionContext CallContractInternal(UInt160 contractHash, string method, CallFlags flags, bool hasReturnValue, StackItem[] args)
{
ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash);
ContractState contract = NativeContract.ContractManagement.GetContract(SnapshotCache, contractHash);
if (contract is null) throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}");
ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method, args.Length);
if (md is null) throw new InvalidOperationException($"Method \"{method}\" with {args.Length} parameter(s) doesn't exist in the contract {contractHash}.");
Expand All @@ -283,7 +289,7 @@ private ExecutionContext CallContractInternal(UInt160 contractHash, string metho

private ExecutionContext CallContractInternal(ContractState contract, ContractMethodDescriptor method, CallFlags flags, bool hasReturnValue, IReadOnlyList<StackItem> args)
{
if (NativeContract.Policy.IsBlocked(Snapshot, contract.Hash))
if (NativeContract.Policy.IsBlocked(SnapshotCache, contract.Hash))
throw new InvalidOperationException($"The contract {contract.Hash} has been blocked.");

ExecutionContext currentContext = CurrentContext;
Expand All @@ -296,7 +302,7 @@ private ExecutionContext CallContractInternal(ContractState contract, ContractMe
{
var executingContract = IsHardforkEnabled(Hardfork.HF_Domovoi)
? state.Contract // use executing contract state to avoid possible contract update/destroy side-effects, ref. https://github.com/neo-project/neo/pull/3290.
: NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash);
: NativeContract.ContractManagement.GetContract(SnapshotCache, CurrentScriptHash);
if (executingContract?.CanCall(contract, method.Name) == false)
throw new InvalidOperationException($"Cannot Call Method {method.Name} Of Contract {contract.Hash} From Contract {CurrentScriptHash}");
}
Expand Down Expand Up @@ -352,7 +358,7 @@ internal override void UnloadContext(ExecutionContext context)
ExecutionContextState state = context.GetState<ExecutionContextState>();
if (UncaughtException is null)
{
state.Snapshot?.Commit();
state.SnapshotCache?.Commit();
if (CurrentContext != null)
{
ExecutionContextState contextState = CurrentContext.GetState<ExecutionContextState>();
Expand Down Expand Up @@ -460,7 +466,7 @@ public ExecutionContext LoadScript(Script script, int rvcount = -1, int initialP
// Create and configure context
ExecutionContext context = CreateContext(script, rvcount, initialPosition);
ExecutionContextState state = context.GetState<ExecutionContextState>();
state.Snapshot = Snapshot?.CloneCache();
state.SnapshotCache = SnapshotCache?.CloneCache();
configureState?.Invoke(state);

// Load context
Expand Down
21 changes: 16 additions & 5 deletions src/Neo/SmartContract/ContractParametersContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,18 @@ public JObject ToJson()
/// <summary>
/// The snapshot used to read data.
/// </summary>
public readonly DataCache Snapshot;
[Obsolete("Use SnapshotCache instead")]
public DataCache Snapshot => SnapshotCache;

/// <summary>
/// The snapshotcache <see cref="SnapshotCache"/> used to read data.
/// </summary>
public readonly DataCache SnapshotCache;

// /// <summary>
// /// The snapshot used to read data.
// /// </summary>
// public readonly DataCache Snapshot;

/// <summary>
/// The magic number of the network.
Expand All @@ -99,18 +110,18 @@ public bool Completed
/// <summary>
/// Gets the script hashes to be verified for the <see cref="Verifiable"/>.
/// </summary>
public IReadOnlyList<UInt160> ScriptHashes => _ScriptHashes ??= Verifiable.GetScriptHashesForVerifying(Snapshot);
public IReadOnlyList<UInt160> ScriptHashes => _ScriptHashes ??= Verifiable.GetScriptHashesForVerifying(SnapshotCache);

/// <summary>
/// Initializes a new instance of the <see cref="ContractParametersContext"/> class.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="snapshotCache">The snapshot used to read data.</param>
/// <param name="verifiable">The <see cref="IVerifiable"/> to add witnesses.</param>
/// <param name="network">The magic number of the network.</param>
public ContractParametersContext(DataCache snapshot, IVerifiable verifiable, uint network)
public ContractParametersContext(DataCache snapshotCache, IVerifiable verifiable, uint network)
{
Verifiable = verifiable;
Snapshot = snapshot;
SnapshotCache = snapshotCache;
ContextItems = new Dictionary<UInt160, ContextItem>();
Network = network;
}
Expand Down
6 changes: 5 additions & 1 deletion src/Neo/SmartContract/ExecutionContextState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

using Neo.Persistence;
using Neo.VM;
using System;

namespace Neo.SmartContract
{
Expand Down Expand Up @@ -44,7 +45,10 @@ public class ExecutionContextState
/// </summary>
public CallFlags CallFlags { get; set; } = CallFlags.All;

public DataCache Snapshot { get; set; }
[Obsolete("Use SnapshotCache instead")]
public DataCache Snapshot => SnapshotCache;

public DataCache SnapshotCache { get; set; }

public int NotificationCount { get; set; }

Expand Down
Loading

0 comments on commit eb167b3

Please sign in to comment.