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

Create ManagementContract #2119

Merged
merged 22 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
51 changes: 4 additions & 47 deletions src/neo/Ledger/Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using Neo.Persistence;
using Neo.Plugins;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using System;
using System.Collections.Concurrent;
Expand Down Expand Up @@ -53,7 +52,7 @@ private class UnverifiedBlocksList { public LinkedList<Block> Blocks = new Linke
PrimaryIndex = 0,
Nonce = 2083236893
},
Transactions = new[] { DeployNativeContracts() }
Transactions = Array.Empty<Transaction>()
};

private readonly static Script onPersistScript, postPersistScript;
Expand Down Expand Up @@ -92,20 +91,12 @@ static Blockchain()

using (ScriptBuilder sb = new ScriptBuilder())
{
foreach (NativeContract contract in new NativeContract[] { NativeContract.GAS, NativeContract.NEO })
{
sb.EmitAppCall(contract.Hash, "onPersist");
sb.Emit(OpCode.DROP);
}
sb.EmitSysCall(ApplicationEngine.System_Contract_NativeOnPersist);
onPersistScript = sb.ToArray();
}
using (ScriptBuilder sb = new ScriptBuilder())
{
foreach (NativeContract contract in new NativeContract[] { NativeContract.NEO, NativeContract.Oracle })
{
sb.EmitAppCall(contract.Hash, "postPersist");
sb.Emit(OpCode.DROP);
}
sb.EmitSysCall(ApplicationEngine.System_Contract_NativePostPersist);
postPersistScript = sb.ToArray();
}
}
Expand Down Expand Up @@ -165,39 +156,6 @@ public bool ContainsTransaction(UInt256 hash)
return View.ContainsTransaction(hash);
}

private static Transaction DeployNativeContracts()
{
byte[] script;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitSysCall(ApplicationEngine.Neo_Native_Deploy);
script = sb.ToArray();
}
return new Transaction
{
Version = 0,
Script = script,
SystemFee = 0,
Signers = new[]
{
new Signer
{
Account = (new[] { (byte)OpCode.PUSH1 }).ToScriptHash(),
Scopes = WitnessScope.None
}
},
Attributes = Array.Empty<TransactionAttribute>(),
Witnesses = new[]
{
new Witness
{
InvocationScript = Array.Empty<byte>(),
VerificationScript = new[] { (byte)OpCode.PUSH1 }
}
}
};
}

public Block GetBlock(uint index)
{
if (index == 0) return GenesisBlock;
Expand Down Expand Up @@ -437,9 +395,8 @@ private void Persist(Block block)
}
List<ApplicationExecuted> all_application_executed = new List<ApplicationExecuted>();
snapshot.PersistingBlock = block;
if (block.Index > 0)
using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot))
{
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot);
engine.LoadScript(onPersistScript);
if (engine.Execute() != VMState.HALT) throw new InvalidOperationException();
ApplicationExecuted application_executed = new ApplicationExecuted(engine);
Expand Down
37 changes: 0 additions & 37 deletions src/neo/Ledger/ContractIdState.cs

This file was deleted.

2 changes: 0 additions & 2 deletions src/neo/Persistence/ClonedView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ internal class ClonedView : StoreView
public override DataCache<SerializableWrapper<uint>, HeaderHashList> HeaderHashList { get; }
public override MetaDataCache<HashIndexState> BlockHashIndex { get; }
public override MetaDataCache<HashIndexState> HeaderHashIndex { get; }
public override MetaDataCache<ContractIdState> ContractId { get; }

public ClonedView(StoreView view)
{
Expand All @@ -25,7 +24,6 @@ public ClonedView(StoreView view)
this.HeaderHashList = view.HeaderHashList.CreateSnapshot();
this.BlockHashIndex = view.BlockHashIndex.CreateSnapshot();
this.HeaderHashIndex = view.HeaderHashIndex.CreateSnapshot();
this.ContractId = view.ContractId.CreateSnapshot();
}
}
}
1 change: 0 additions & 1 deletion src/neo/Persistence/Prefixes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ internal static class Prefixes
public const byte IX_HeaderHashList = 0x80;
public const byte IX_CurrentBlock = 0xc0;
public const byte IX_CurrentHeader = 0xc1;
public const byte IX_ContractId = 0xc2;

/* Prefixes 0xf0 to 0xff are reserved for external use.
*
Expand Down
1 change: 0 additions & 1 deletion src/neo/Persistence/ReadOnlyView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public class ReadOnlyView : StoreView
public override DataCache<SerializableWrapper<uint>, HeaderHashList> HeaderHashList => new StoreDataCache<SerializableWrapper<uint>, HeaderHashList>(store, Prefixes.IX_HeaderHashList);
public override MetaDataCache<HashIndexState> BlockHashIndex => new StoreMetaDataCache<HashIndexState>(store, Prefixes.IX_CurrentBlock);
public override MetaDataCache<HashIndexState> HeaderHashIndex => new StoreMetaDataCache<HashIndexState>(store, Prefixes.IX_CurrentHeader);
public override MetaDataCache<ContractIdState> ContractId => new StoreMetaDataCache<ContractIdState>(store, Prefixes.IX_ContractId);

public ReadOnlyView(IReadOnlyStore store)
{
Expand Down
2 changes: 0 additions & 2 deletions src/neo/Persistence/SnapshotView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public class SnapshotView : StoreView, IDisposable
public override DataCache<SerializableWrapper<uint>, HeaderHashList> HeaderHashList { get; }
public override MetaDataCache<HashIndexState> BlockHashIndex { get; }
public override MetaDataCache<HashIndexState> HeaderHashIndex { get; }
public override MetaDataCache<ContractIdState> ContractId { get; }

public SnapshotView(IStore store)
{
Expand All @@ -31,7 +30,6 @@ public SnapshotView(IStore store)
HeaderHashList = new StoreDataCache<SerializableWrapper<uint>, HeaderHashList>(snapshot, Prefixes.IX_HeaderHashList);
BlockHashIndex = new StoreMetaDataCache<HashIndexState>(snapshot, Prefixes.IX_CurrentBlock);
HeaderHashIndex = new StoreMetaDataCache<HashIndexState>(snapshot, Prefixes.IX_CurrentHeader);
ContractId = new StoreMetaDataCache<ContractIdState>(snapshot, Prefixes.IX_ContractId);
}

public override void Commit()
Expand Down
2 changes: 0 additions & 2 deletions src/neo/Persistence/StoreView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public abstract class StoreView
public abstract DataCache<SerializableWrapper<uint>, HeaderHashList> HeaderHashList { get; }
public abstract MetaDataCache<HashIndexState> BlockHashIndex { get; }
public abstract MetaDataCache<HashIndexState> HeaderHashIndex { get; }
public abstract MetaDataCache<ContractIdState> ContractId { get; }

public uint Height => BlockHashIndex.Get().Index;
public uint HeaderHeight => HeaderHashIndex.Get().Index;
Expand All @@ -39,7 +38,6 @@ public virtual void Commit()
HeaderHashList.Commit();
BlockHashIndex.Commit();
HeaderHashIndex.Commit();
ContractId.Commit();
}

public bool ContainsBlock(UInt256 hash)
Expand Down
118 changes: 29 additions & 89 deletions src/neo/SmartContract/ApplicationEngine.Contract.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.SmartContract.Manifest;
Expand All @@ -12,103 +11,18 @@ namespace Neo.SmartContract
{
partial class ApplicationEngine
{
public static readonly InteropDescriptor System_Contract_Create = Register("System.Contract.Create", nameof(CreateContract), 0, CallFlags.AllowModifyStates, false);
public static readonly InteropDescriptor System_Contract_Update = Register("System.Contract.Update", nameof(UpdateContract), 0, CallFlags.AllowModifyStates, false);
public static readonly InteropDescriptor System_Contract_Destroy = Register("System.Contract.Destroy", nameof(DestroyContract), 0_01000000, CallFlags.AllowModifyStates, false);
public static readonly InteropDescriptor System_Contract_Call = Register("System.Contract.Call", nameof(CallContract), 0_01000000, CallFlags.AllowCall, false);
public static readonly InteropDescriptor System_Contract_CallEx = Register("System.Contract.CallEx", nameof(CallContractEx), 0_01000000, CallFlags.AllowCall, false);
public static readonly InteropDescriptor System_Contract_CallNative = Register("System.Contract.CallNative", nameof(CallNativeContract), 0, CallFlags.None, false);
public static readonly InteropDescriptor System_Contract_IsStandard = Register("System.Contract.IsStandard", nameof(IsStandardContract), 0_00030000, CallFlags.AllowStates, true);
public static readonly InteropDescriptor System_Contract_GetCallFlags = Register("System.Contract.GetCallFlags", nameof(GetCallFlags), 0_00030000, CallFlags.None, false);
/// <summary>
/// Calculate corresponding account scripthash for given public key
/// Warning: check first that input public key is valid, before creating the script.
/// </summary>
public static readonly InteropDescriptor System_Contract_CreateStandardAccount = Register("System.Contract.CreateStandardAccount", nameof(CreateStandardAccount), 0_00010000, CallFlags.None, true);

protected internal void CreateContract(byte[] nefFile, byte[] manifest)
{
if (!(ScriptContainer is Transaction tx))
throw new InvalidOperationException();
if (nefFile.Length == 0)
throw new ArgumentException($"Invalid NefFile Length: {nefFile.Length}");
if (manifest.Length == 0 || manifest.Length > ContractManifest.MaxLength)
throw new ArgumentException($"Invalid Manifest Length: {manifest.Length}");

AddGas(StoragePrice * (nefFile.Length + manifest.Length));

NefFile nef = nefFile.AsSerializable<NefFile>();
UInt160 hash = Helper.GetContractHash(tx.Sender, nef.Script);
ContractState contract = Snapshot.Contracts.TryGet(hash);
if (contract != null) throw new InvalidOperationException($"Contract Already Exists: {hash}");
contract = new ContractState
{
Id = Snapshot.ContractId.GetAndChange().NextId++,
UpdateCounter = 0,
Script = nef.Script,
Hash = hash,
Manifest = ContractManifest.Parse(manifest)
};

if (!contract.Manifest.IsValid(hash)) throw new InvalidOperationException($"Invalid Manifest Hash: {hash}");

Snapshot.Contracts.Add(hash, contract);

// We should push it onto the caller's stack.

Push(Convert(contract));

// Execute _deploy

ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod("_deploy");
if (md != null)
CallContractInternal(contract, md, new Array(ReferenceCounter) { false }, CallFlags.All, ReturnTypeConvention.EnsureIsEmpty);
}

protected internal void UpdateContract(byte[] nefFile, byte[] manifest)
{
if (nefFile is null && manifest is null) throw new ArgumentException();

AddGas(StoragePrice * ((nefFile?.Length ?? 0) + (manifest?.Length ?? 0)));

var contract = Snapshot.Contracts.GetAndChange(CurrentScriptHash);
if (contract is null) throw new InvalidOperationException($"Updating Contract Does Not Exist: {CurrentScriptHash}");

if (nefFile != null)
{
if (nefFile.Length == 0)
throw new ArgumentException($"Invalid NefFile Length: {nefFile.Length}");

NefFile nef = nefFile.AsSerializable<NefFile>();

// Update script
contract.Script = nef.Script;
}
if (manifest != null)
{
if (manifest.Length == 0 || manifest.Length > ContractManifest.MaxLength)
throw new ArgumentException($"Invalid Manifest Length: {manifest.Length}");
contract.Manifest = ContractManifest.Parse(manifest);
if (!contract.Manifest.IsValid(contract.Hash))
throw new InvalidOperationException($"Invalid Manifest Hash: {contract.Hash}");
}
contract.UpdateCounter++; // Increase update counter
if (nefFile != null)
{
ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod("_deploy");
if (md != null)
CallContractInternal(contract, md, new Array(ReferenceCounter) { true }, CallFlags.All, ReturnTypeConvention.EnsureIsEmpty);
}
}

protected internal void DestroyContract()
{
UInt160 hash = CurrentScriptHash;
ContractState contract = Snapshot.Contracts.TryGet(hash);
if (contract == null) return;
Snapshot.Contracts.Delete(hash);
foreach (var (key, _) in Snapshot.Storages.Find(BitConverter.GetBytes(contract.Id)))
Snapshot.Storages.Delete(key);
}
public static readonly InteropDescriptor System_Contract_NativeOnPersist = Register("System.Contract.NativeOnPersist", nameof(NativeOnPersist), 0, CallFlags.None, false);
public static readonly InteropDescriptor System_Contract_NativePostPersist = Register("System.Contract.NativePostPersist", nameof(NativePostPersist), 0, CallFlags.None, false);

protected internal void CallContract(UInt160 contractHash, string method, Array args)
{
Expand Down Expand Up @@ -172,6 +86,14 @@ private void CallContractInternal(ContractState contract, ContractMethodDescript
}
}

protected internal void CallNativeContract(string name)
{
NativeContract contract = NativeContract.GetContract(name);
if (contract is null || contract.ActiveBlockIndex > Snapshot.PersistingBlock.Index)
throw new InvalidOperationException();
contract.Invoke(this);
}

protected internal bool IsStandardContract(UInt160 hash)
{
ContractState contract = Snapshot.Contracts.TryGet(hash);
Expand Down Expand Up @@ -208,5 +130,23 @@ protected internal UInt160 CreateStandardAccount(ECPoint pubKey)
{
return Contract.CreateSignatureRedeemScript(pubKey).ToScriptHash();
}

protected internal void NativeOnPersist()
{
if (Trigger != TriggerType.OnPersist)
throw new InvalidOperationException();
foreach (NativeContract contract in NativeContract.Contracts)
if (contract.ActiveBlockIndex <= Snapshot.PersistingBlock.Index)
contract.OnPersist(this);
}

protected internal void NativePostPersist()
{
if (Trigger != TriggerType.PostPersist)
throw new InvalidOperationException();
foreach (NativeContract contract in NativeContract.Contracts)
if (contract.ActiveBlockIndex <= Snapshot.PersistingBlock.Index)
contract.PostPersist(this);
}
}
}
34 changes: 0 additions & 34 deletions src/neo/SmartContract/ApplicationEngine.Native.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public sealed class DesignateContract : NativeContract
{
public override string Name => "Designation";
public override int Id => -5;
public override uint ActiveBlockIndex => 0;

internal DesignateContract()
{
Expand Down
Loading