-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathNativeContract.cs
253 lines (225 loc) · 9.73 KB
/
NativeContract.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright (C) 2015-2022 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.IO;
using Neo.SmartContract.Manifest;
using Neo.VM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Neo.SmartContract.Native
{
/// <summary>
/// The base class of all native contracts.
/// </summary>
public abstract class NativeContract
{
private static readonly List<NativeContract> contractsList = new();
private static readonly Dictionary<UInt160, NativeContract> contractsDictionary = new();
private readonly Dictionary<int, ContractMethodMetadata> methods = new();
private static int id_counter = 0;
#region Named Native Contracts
/// <summary>
/// Gets the instance of the <see cref="Native.ContractManagement"/> class.
/// </summary>
public static ContractManagement ContractManagement { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.StdLib"/> class.
/// </summary>
public static StdLib StdLib { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.CryptoLib"/> class.
/// </summary>
public static CryptoLib CryptoLib { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="LedgerContract"/> class.
/// </summary>
public static LedgerContract Ledger { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="NeoToken"/> class.
/// </summary>
public static NeoToken NEO { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="GasToken"/> class.
/// </summary>
public static GasToken GAS { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="PolicyContract"/> class.
/// </summary>
public static PolicyContract Policy { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.RoleManagement"/> class.
/// </summary>
public static RoleManagement RoleManagement { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="OracleContract"/> class.
/// </summary>
public static OracleContract Oracle { get; } = new();
#endregion
/// <summary>
/// Gets all native contracts.
/// </summary>
public static IReadOnlyCollection<NativeContract> Contracts { get; } = contractsList;
/// <summary>
/// The name of the native contract.
/// </summary>
public string Name => GetType().Name;
/// <summary>
/// The nef of the native contract.
/// </summary>
public NefFile Nef { get; }
/// <summary>
/// The hash of the native contract.
/// </summary>
public UInt160 Hash { get; }
/// <summary>
/// The id of the native contract.
/// </summary>
public int Id { get; } = --id_counter;
/// <summary>
/// The manifest of the native contract.
/// </summary>
public ContractManifest Manifest { get; }
/// <summary>
/// Initializes a new instance of the <see cref="NativeContract"/> class.
/// </summary>
protected NativeContract()
{
List<ContractMethodMetadata> descriptors = new();
foreach (MemberInfo member in GetType().GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
ContractMethodAttribute attribute = member.GetCustomAttribute<ContractMethodAttribute>();
if (attribute is null) continue;
descriptors.Add(new ContractMethodMetadata(member, attribute));
}
descriptors = descriptors.OrderBy(p => p.Name, StringComparer.Ordinal).ThenBy(p => p.Parameters.Length).ToList();
byte[] script;
using (ScriptBuilder sb = new())
{
foreach (ContractMethodMetadata method in descriptors)
{
method.Descriptor.Offset = sb.Length;
sb.EmitPush(0); //version
methods.Add(sb.Length, method);
sb.EmitSysCall(ApplicationEngine.System_Contract_CallNative);
sb.Emit(OpCode.RET);
}
script = sb.ToArray();
}
this.Nef = new NefFile
{
Compiler = "neo-core-v3.0",
Source = string.Empty,
Tokens = Array.Empty<MethodToken>(),
Script = script
};
this.Nef.CheckSum = NefFile.ComputeChecksum(Nef);
this.Hash = Helper.GetContractHash(UInt160.Zero, 0, Name);
this.Manifest = new ContractManifest
{
Name = Name,
Groups = Array.Empty<ContractGroup>(),
SupportedStandards = Array.Empty<string>(),
Abi = new ContractAbi()
{
Events = Array.Empty<ContractEventDescriptor>(),
Methods = descriptors.Select(p => p.Descriptor).ToArray()
},
Permissions = new[] { ContractPermission.DefaultPermission },
Trusts = WildcardContainer<ContractPermissionDescriptor>.Create(),
Extra = null
};
contractsList.Add(this);
contractsDictionary.Add(Hash, this);
}
/// <summary>
/// Checks whether the committee has witnessed the current transaction.
/// </summary>
/// <param name="engine">The <see cref="ApplicationEngine"/> that is executing the contract.</param>
/// <returns><see langword="true"/> if the committee has witnessed the current transaction; otherwise, <see langword="false"/>.</returns>
protected static bool CheckCommittee(ApplicationEngine engine)
{
UInt160 committeeMultiSigAddr = NEO.GetCommitteeAddress(engine.Snapshot);
return engine.CheckWitnessInternal(committeeMultiSigAddr);
}
private protected KeyBuilder CreateStorageKey(byte prefix)
{
return new KeyBuilder(Id, prefix);
}
/// <summary>
/// Gets the native contract with the specified hash.
/// </summary>
/// <param name="hash">The hash of the native contract.</param>
/// <returns>The native contract with the specified hash.</returns>
public static NativeContract GetContract(UInt160 hash)
{
contractsDictionary.TryGetValue(hash, out var contract);
return contract;
}
internal async void Invoke(ApplicationEngine engine, byte version)
{
try
{
if (version != 0)
throw new InvalidOperationException($"The native contract of version {version} is not active.");
ExecutionContext context = engine.CurrentContext;
ContractMethodMetadata method = methods[context.InstructionPointer];
ExecutionContextState state = context.GetState<ExecutionContextState>();
if (!state.CallFlags.HasFlag(method.RequiredCallFlags))
throw new InvalidOperationException($"Cannot call this method with the flag {state.CallFlags}.");
engine.AddGas(method.CpuFee * engine.ExecFeeFactor + method.StorageFee * engine.StoragePrice);
List<object> parameters = new();
if (method.NeedApplicationEngine) parameters.Add(engine);
if (method.NeedSnapshot) parameters.Add(engine.Snapshot);
for (int i = 0; i < method.Parameters.Length; i++)
parameters.Add(engine.Convert(context.EvaluationStack.Peek(i), method.Parameters[i]));
object returnValue = method.Handler.Invoke(this, parameters.ToArray());
if (returnValue is ContractTask task)
{
await task;
returnValue = task.GetResult();
}
for (int i = 0; i < method.Parameters.Length; i++)
{
context.EvaluationStack.Pop();
}
if (method.Handler.ReturnType != typeof(void) && method.Handler.ReturnType != typeof(ContractTask))
{
context.EvaluationStack.Push(engine.Convert(returnValue));
}
}
catch (Exception ex)
{
engine.Throw(ex);
}
}
/// <summary>
/// Determine whether the specified contract is a native contract.
/// </summary>
/// <param name="hash">The hash of the contract.</param>
/// <returns><see langword="true"/> if the contract is native; otherwise, <see langword="false"/>.</returns>
public static bool IsNative(UInt160 hash)
{
return contractsDictionary.ContainsKey(hash);
}
internal virtual ContractTask Initialize(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
internal virtual ContractTask OnPersist(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
internal virtual ContractTask PostPersist(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
}
}