Skip to content

Commit

Permalink
rename snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
Jim8y committed Jul 7, 2024
1 parent 94f1a72 commit 970c411
Show file tree
Hide file tree
Showing 32 changed files with 118 additions and 96 deletions.
2 changes: 1 addition & 1 deletion benchmarks/Neo.Benchmarks/Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ private static void Run(string name, string poc)
Script = Convert.FromBase64String(poc),
Witnesses = Array.Empty<Witness>()
};
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
using var engine = ApplicationEngine.Create(TriggerType.Application, tx, snapshot, system.GenesisBlock, protocol, tx.SystemFee);
engine.LoadScript(tx.Script);
Stopwatch stopwatch = Stopwatch.StartNew();
Expand Down
2 changes: 1 addition & 1 deletion src/Neo.GUI/GUI/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ private void timer1_Tick(object sender, EventArgs e)
check_nep5_balance = false;
UInt160[] addresses = Service.CurrentWallet.GetAccounts().Select(p => p.ScriptHash).ToArray();
if (addresses.Length == 0) return;
using var snapshot = Service.NeoSystem.GetSnapshot();
using var snapshot = Service.NeoSystem.GetSnapshotCache();
foreach (UInt160 assetId in NEP5Watched)
{
byte[] script;
Expand Down
4 changes: 2 additions & 2 deletions src/Neo/Ledger/Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ private void Persist(Block block)
all_application_executed.Add(application_executed);
transactionStates = engine.GetState<TransactionState[]>();
}
DataCache clonedSnapshot = snapshot.CreateSnapshot();
DataCache clonedSnapshot = snapshot.CloneCache();
// Warning: Do not write into variable snapshot directly. Write into variable clonedSnapshot and commit instead.
foreach (TransactionState transactionState in transactionStates)
{
Expand All @@ -453,7 +453,7 @@ private void Persist(Block block)
}
else
{
clonedSnapshot = snapshot.CreateSnapshot();
clonedSnapshot = snapshot.CloneCache();
}
ApplicationExecuted application_executed = new(engine);
Context.System.EventStream.Publish(application_executed);
Expand Down
14 changes: 13 additions & 1 deletion src/Neo/NeoSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,12 +275,24 @@ public void SuspendNodeStartup()
/// <summary>
/// Gets a snapshot of the blockchain storage.
/// </summary>
/// <returns></returns>
/// <returns>An instance of <see cref="SnapshotCache"/></returns>
[Obsolete("This method is obsolete, use GetSnapshotCache instead.")]
public SnapshotCache GetSnapshot()
{
return new SnapshotCache(store.GetSnapshot());
}

/// <summary>
/// Gets a snapshot of the blockchain storage with an execution cache.
/// With the snapshot, we have the latest state of the blockchain, with the cache,
/// we can run transactions in a sandboxed environment.
/// </summary>
/// <returns>An instance of <see cref="SnapshotCache"/></returns>
public SnapshotCache GetSnapshotCache()
{
return new SnapshotCache(store.GetSnapshot());
}

/// <summary>
/// Determines whether the specified transaction exists in the memory pool or storage.
/// </summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Neo/Persistence/DataCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,21 @@ public virtual void Commit()
/// Creates a snapshot, which uses this instance as the underlying storage.
/// </summary>
/// <returns>The snapshot of this instance.</returns>
[Obsolete("CreateSnapshot is deprecated, please use CloneCache instead.")]
public DataCache CreateSnapshot()
{
return new ClonedCache(this);
}

/// <summary>
/// Creates a clone of the snapshot cache, which uses this instance as the underlying storage.
/// </summary>
/// <returns>The <see cref="DataCache"/> of this <see cref="SnapshotCache"/> instance.</returns>
public DataCache CloneCache()
{
return new ClonedCache(this);
}

/// <summary>
/// Deletes an entry from the cache.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Neo/SmartContract/ApplicationEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,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?.CreateSnapshot();
state.Snapshot = Snapshot?.CloneCache();
configureState?.Invoke(state);

// Load context
Expand Down
2 changes: 1 addition & 1 deletion src/Neo/SmartContract/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ internal static bool VerifyWitness(this IVerifiable verifiable, ProtocolSettings
{
return false;
}
using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.CreateSnapshot(), null, settings, datoshi))
using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.CloneCache(), null, settings, datoshi))
{
if (witness.VerificationScript.Length == 0)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Neo/Wallets/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public static long CalculateNetworkFee(this Transaction tx, DataCache snapshot,
size += Array.Empty<byte>().GetVarSize() + invSize;

// Check verify cost
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CreateSnapshot(), settings: settings, gas: maxExecutionCost);
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CloneCache(), settings: settings, gas: maxExecutionCost);
engine.LoadContract(contract, md, CallFlags.ReadOnly);
if (invocationScript != null) engine.LoadScript(invocationScript, configureState: p => p.CallFlags = CallFlags.None);
if (engine.Execute() == VMState.FAULT) throw new ArgumentException($"Smart contract {contract.Hash} verification fault.");
Expand Down
2 changes: 1 addition & 1 deletion src/Neo/Wallets/Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ private Transaction MakeTransaction(DataCache snapshot, ReadOnlyMemory<byte> scr
};

// will try to execute 'transfer' script to check if it works
using (ApplicationEngine engine = ApplicationEngine.Run(script, snapshot.CreateSnapshot(), tx, settings: ProtocolSettings, gas: maxGas, persistingBlock: persistingBlock))
using (ApplicationEngine engine = ApplicationEngine.Run(script, snapshot.CloneCache(), tx, settings: ProtocolSettings, gas: maxGas, persistingBlock: persistingBlock))
{
if (engine.State == VMState.FAULT)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public void Reset(byte viewNumber)
if (viewNumber == 0)
{
Snapshot?.Dispose();
Snapshot = neoSystem.GetSnapshot();
Snapshot = neoSystem.GetSnapshotCache();
uint height = NativeContract.Ledger.CurrentIndex(Snapshot);
Block = new Block
{
Expand Down
2 changes: 1 addition & 1 deletion src/Plugins/OracleService/OracleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ public static Transaction CreateResponseTx(DataCache snapshot, OracleRequest req
// Calculate network fee

var oracleContract = NativeContract.ContractManagement.GetContract(snapshot, NativeContract.Oracle.Hash);
var engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CreateSnapshot(), settings: settings);
var engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CloneCache(), settings: settings);
ContractMethodDescriptor md = oracleContract.Manifest.Abi.GetMethod(ContractBasicMethod.Verify, ContractBasicMethod.VerifyPCount);
engine.LoadContract(oracleContract, md, CallFlags.None);
if (engine.Execute() != VMState.HALT) return null;
Expand Down
10 changes: 5 additions & 5 deletions src/Plugins/RpcServer/RpcServer.Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected internal virtual JToken GetBlock(JArray _params)
{
JToken key = Result.Ok_Or(() => _params[0], RpcError.InvalidParams.WithData($"Invalid Block Hash or Index: {_params[0]}"));
bool verbose = _params.Count >= 2 && _params[1].AsBoolean();
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
Block block;
if (key is JNumber)
{
Expand Down Expand Up @@ -245,7 +245,7 @@ protected internal virtual JToken GetRawTransaction(JArray _params)
[RpcMethod]
protected internal virtual JToken GetStorage(JArray _params)
{
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
if (!int.TryParse(_params[0].AsString(), out int id))
{
UInt160 hash = Result.Ok_Or(() => UInt160.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid contract hash {_params[0]}"));
Expand Down Expand Up @@ -273,7 +273,7 @@ protected internal virtual JToken GetStorage(JArray _params)
[RpcMethod]
protected internal virtual JToken FindStorage(JArray _params)
{
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
if (!int.TryParse(_params[0].AsString(), out int id))
{
UInt160 hash = Result.Ok_Or(() => UInt160.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid contract hash {_params[0]}"));
Expand Down Expand Up @@ -341,7 +341,7 @@ protected internal virtual JToken GetTransactionHeight(JArray _params)
[RpcMethod]
protected internal virtual JToken GetNextBlockValidators(JArray _params)
{
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
var validators = NativeContract.NEO.GetNextBlockValidators(snapshot, system.Settings.ValidatorsCount);
return validators.Select(p =>
{
Expand All @@ -360,7 +360,7 @@ protected internal virtual JToken GetNextBlockValidators(JArray _params)
[RpcMethod]
protected internal virtual JToken GetCandidates(JArray _params)
{
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
byte[] script;
using (ScriptBuilder sb = new())
{
Expand Down
10 changes: 5 additions & 5 deletions src/Plugins/RpcServer/RpcServer.Wallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ protected virtual JToken SendFrom(JArray _params)
UInt160 assetId = Result.Ok_Or(() => UInt160.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid asset id: {_params[0]}"));
UInt160 from = AddressToScriptHash(_params[1].AsString(), system.Settings.AddressVersion);
UInt160 to = AddressToScriptHash(_params[2].AsString(), system.Settings.AddressVersion);
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
AssetDescriptor descriptor = new(snapshot, system.Settings, assetId);
BigDecimal amount = new(BigInteger.Parse(_params[3].AsString()), descriptor.Decimals);
(amount.Sign > 0).True_Or(RpcErrorFactory.InvalidParams("Amount can't be negative."));
Expand Down Expand Up @@ -243,7 +243,7 @@ protected virtual JToken SendMany(JArray _params)
Signer[] signers = _params.Count >= to_start + 2 ? ((JArray)_params[to_start + 1]).Select(p => new Signer() { Account = AddressToScriptHash(p.AsString(), system.Settings.AddressVersion), Scopes = WitnessScope.CalledByEntry }).ToArray() : null;

TransferOutput[] outputs = new TransferOutput[to.Count];
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
for (int i = 0; i < to.Count; i++)
{
UInt160 asset_id = UInt160.Parse(to[i]["asset"].AsString());
Expand Down Expand Up @@ -279,7 +279,7 @@ protected virtual JToken SendToAddress(JArray _params)
CheckWallet();
UInt160 assetId = Result.Ok_Or(() => UInt160.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid asset hash: {_params[0]}"));
UInt160 to = AddressToScriptHash(_params[1].AsString(), system.Settings.AddressVersion);
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
AssetDescriptor descriptor = new(snapshot, system.Settings, assetId);
BigDecimal amount = new(BigInteger.Parse(_params[2].AsString()), descriptor.Decimals);
(amount.Sign > 0).True_Or(RpcError.InvalidParams);
Expand Down Expand Up @@ -354,7 +354,7 @@ protected virtual JToken InvokeContractVerify(JArray _params)

private JObject GetVerificationResult(UInt160 scriptHash, ContractParameter[] args, Signer[] signers = null, Witness[] witnesses = null)
{
using var snapshot = system.GetSnapshot();
using var snapshot = system.GetSnapshotCache();
var contract = NativeContract.ContractManagement.GetContract(snapshot, scriptHash).NotNull_Or(RpcError.UnknownContract);
var md = contract.Manifest.Abi.GetMethod(ContractBasicMethod.Verify, ContractBasicMethod.VerifyPCount).NotNull_Or(RpcErrorFactory.InvalidContractVerification(contract.Hash));
(md.ReturnType == ContractParameterType.Boolean).True_Or(RpcErrorFactory.InvalidContractVerification("The verify method doesn't return boolean value."));
Expand All @@ -365,7 +365,7 @@ private JObject GetVerificationResult(UInt160 scriptHash, ContractParameter[] ar
Witnesses = witnesses,
Script = new[] { (byte)OpCode.RET }
};
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CreateSnapshot(), settings: system.Settings);
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CloneCache(), settings: system.Settings);
engine.LoadContract(contract, md, CallFlags.ReadOnly);

var invocationScript = Array.Empty<byte>();
Expand Down
2 changes: 1 addition & 1 deletion src/Plugins/RpcServer/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Session : IDisposable
public Session(NeoSystem system, byte[] script, Signer[] signers, Witness[] witnesses, long datoshi, Diagnostic diagnostic)
{
Random random = new();
Snapshot = system.GetSnapshot();
Snapshot = system.GetSnapshotCache();
Transaction tx = signers == null ? null : new Transaction
{
Version = 0,
Expand Down
2 changes: 1 addition & 1 deletion tests/Neo.Plugins.OracleService.Tests/TestBlockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static void InitializeMockNeoSystem()

internal static DataCache GetTestSnapshot()
{
return TheNeoSystem.GetSnapshot().CreateSnapshot();
return TheNeoSystem.GetSnapshotCache().CloneCache();
}
}
}
2 changes: 1 addition & 1 deletion tests/Neo.Plugins.RpcServer.Tests/TestBlockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ internal static void ResetStore()

internal static DataCache GetTestSnapshot()
{
return TheNeoSystem.GetSnapshot().CreateSnapshot();
return TheNeoSystem.GetSnapshotCache().CloneCache();
}
}
}
Loading

0 comments on commit 970c411

Please sign in to comment.