-
Notifications
You must be signed in to change notification settings - Fork 1k
/
LedgerContract.cs
321 lines (293 loc) · 14.9 KB
/
LedgerContract.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// 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.
#pragma warning disable IDE0051
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.VM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Neo.SmartContract.Native
{
/// <summary>
/// A native contract for storing all blocks and transactions.
/// </summary>
public sealed class LedgerContract : NativeContract
{
private const byte Prefix_BlockHash = 9;
private const byte Prefix_CurrentBlock = 12;
private const byte Prefix_Block = 5;
private const byte Prefix_Transaction = 11;
internal LedgerContract()
{
}
internal override ContractTask OnPersist(ApplicationEngine engine)
{
TransactionState[] transactions = engine.PersistingBlock.Transactions.Select(p => new TransactionState
{
BlockIndex = engine.PersistingBlock.Index,
Transaction = p,
State = VMState.NONE
}).ToArray();
engine.Snapshot.Add(CreateStorageKey(Prefix_BlockHash).AddBigEndian(engine.PersistingBlock.Index), new StorageItem(engine.PersistingBlock.Hash.ToArray()));
engine.Snapshot.Add(CreateStorageKey(Prefix_Block).Add(engine.PersistingBlock.Hash), new StorageItem(Trim(engine.PersistingBlock).ToArray()));
foreach (TransactionState tx in transactions)
{
engine.Snapshot.Add(CreateStorageKey(Prefix_Transaction).Add(tx.Transaction.Hash), new StorageItem(tx));
var conflictingSigners = tx.Transaction.Signers.Select(s => s.Account);
foreach (var attr in tx.Transaction.GetAttributes<Conflicts>())
{
var conflictRecord = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Transaction).Add(attr.Hash),
() => new StorageItem(new TransactionState { ConflictingSigners = Array.Empty<UInt160>() })).GetInteroperable<TransactionState>();
conflictRecord.ConflictingSigners = conflictRecord.ConflictingSigners.Concat(conflictingSigners).Distinct().ToArray();
}
}
engine.SetState(transactions);
return ContractTask.CompletedTask;
}
internal override ContractTask PostPersist(ApplicationEngine engine)
{
HashIndexState state = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_CurrentBlock), () => new StorageItem(new HashIndexState())).GetInteroperable<HashIndexState>();
state.Hash = engine.PersistingBlock.Hash;
state.Index = engine.PersistingBlock.Index;
return ContractTask.CompletedTask;
}
internal bool Initialized(DataCache snapshot)
{
return snapshot.Find(CreateStorageKey(Prefix_Block).ToArray()).Any();
}
private bool IsTraceableBlock(DataCache snapshot, uint index, uint maxTraceableBlocks)
{
uint currentIndex = CurrentIndex(snapshot);
if (index > currentIndex) return false;
return index + maxTraceableBlocks > currentIndex;
}
/// <summary>
/// Gets the hash of the specified block.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="index">The index of the block.</param>
/// <returns>The hash of the block.</returns>
public UInt256 GetBlockHash(DataCache snapshot, uint index)
{
StorageItem item = snapshot.TryGet(CreateStorageKey(Prefix_BlockHash).AddBigEndian(index));
if (item is null) return null;
return new UInt256(item.Value.Span);
}
/// <summary>
/// Gets the hash of the current block.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <returns>The hash of the current block.</returns>
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
public UInt256 CurrentHash(DataCache snapshot)
{
return snapshot[CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>().Hash;
}
/// <summary>
/// Gets the index of the current block.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <returns>The index of the current block.</returns>
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
public uint CurrentIndex(DataCache snapshot)
{
return snapshot[CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>().Index;
}
/// <summary>
/// Determine whether the specified block is contained in the blockchain.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the block.</param>
/// <returns><see langword="true"/> if the blockchain contains the block; otherwise, <see langword="false"/>.</returns>
public bool ContainsBlock(DataCache snapshot, UInt256 hash)
{
return snapshot.Contains(CreateStorageKey(Prefix_Block).Add(hash));
}
/// <summary>
/// Determine whether the specified transaction is contained in the blockchain.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the transaction.</param>
/// <returns><see langword="true"/> if the blockchain contains the transaction; otherwise, <see langword="false"/>.</returns>
public bool ContainsTransaction(DataCache snapshot, UInt256 hash)
{
var txState = GetTransactionState(snapshot, hash);
return txState != null;
}
/// <summary>
/// Determine whether the specified transaction hash is contained in the blockchain
/// as the hash of conflicting transaction.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the conflicting transaction.</param>
/// <param name="signers">The list of signer accounts of the conflicting transaction.</param>
/// <returns><see langword="true"/> if the blockchain contains the hash of the conflicting transaction; otherwise, <see langword="false"/>.</returns>
public bool ContainsConflictHash(DataCache snapshot, UInt256 hash, IEnumerable<UInt160> signers)
{
var state = snapshot.TryGet(CreateStorageKey(Prefix_Transaction).Add(hash))?.GetInteroperable<TransactionState>();
return state is not null && state.Transaction is null && (signers is null || state.ConflictingSigners.Intersect(signers).Any());
}
/// <summary>
/// Gets a <see cref="TrimmedBlock"/> with the specified hash.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the block.</param>
/// <returns>The trimmed block.</returns>
public TrimmedBlock GetTrimmedBlock(DataCache snapshot, UInt256 hash)
{
StorageItem item = snapshot.TryGet(CreateStorageKey(Prefix_Block).Add(hash));
if (item is null) return null;
return item.Value.AsSerializable<TrimmedBlock>();
}
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
private TrimmedBlock GetBlock(ApplicationEngine engine, byte[] indexOrHash)
{
UInt256 hash;
if (indexOrHash.Length < UInt256.Length)
hash = GetBlockHash(engine.Snapshot, (uint)new BigInteger(indexOrHash));
else if (indexOrHash.Length == UInt256.Length)
hash = new UInt256(indexOrHash);
else
throw new ArgumentException(null, nameof(indexOrHash));
if (hash is null) return null;
TrimmedBlock block = GetTrimmedBlock(engine.Snapshot, hash);
if (block is null || !IsTraceableBlock(engine.Snapshot, block.Index, engine.ProtocolSettings.MaxTraceableBlocks)) return null;
return block;
}
/// <summary>
/// Gets a block with the specified hash.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the block.</param>
/// <returns>The block with the specified hash.</returns>
public Block GetBlock(DataCache snapshot, UInt256 hash)
{
TrimmedBlock state = GetTrimmedBlock(snapshot, hash);
if (state is null) return null;
return new Block
{
Header = state.Header,
Transactions = state.Hashes.Select(p => GetTransaction(snapshot, p)).ToArray()
};
}
/// <summary>
/// Gets a block with the specified index.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="index">The index of the block.</param>
/// <returns>The block with the specified index.</returns>
public Block GetBlock(DataCache snapshot, uint index)
{
UInt256 hash = GetBlockHash(snapshot, index);
if (hash is null) return null;
return GetBlock(snapshot, hash);
}
/// <summary>
/// Gets a block header with the specified hash.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the block.</param>
/// <returns>The block header with the specified hash.</returns>
public Header GetHeader(DataCache snapshot, UInt256 hash)
{
return GetTrimmedBlock(snapshot, hash)?.Header;
}
/// <summary>
/// Gets a block header with the specified index.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="index">The index of the block.</param>
/// <returns>The block header with the specified index.</returns>
public Header GetHeader(DataCache snapshot, uint index)
{
UInt256 hash = GetBlockHash(snapshot, index);
if (hash is null) return null;
return GetHeader(snapshot, hash);
}
/// <summary>
/// Gets a <see cref="TransactionState"/> with the specified hash.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the transaction.</param>
/// <returns>The <see cref="TransactionState"/> with the specified hash.</returns>
public TransactionState GetTransactionState(DataCache snapshot, UInt256 hash)
{
var state = snapshot.TryGet(CreateStorageKey(Prefix_Transaction).Add(hash))?.GetInteroperable<TransactionState>();
if (state?.Transaction is null) return null;
return state;
}
/// <summary>
/// Gets a transaction with the specified hash.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="hash">The hash of the transaction.</param>
/// <returns>The transaction with the specified hash.</returns>
public Transaction GetTransaction(DataCache snapshot, UInt256 hash)
{
return GetTransactionState(snapshot, hash)?.Transaction;
}
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates, Name = "getTransaction")]
private Transaction GetTransactionForContract(ApplicationEngine engine, UInt256 hash)
{
TransactionState state = GetTransactionState(engine.Snapshot, hash);
if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return null;
return state.Transaction;
}
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
private Signer[] GetTransactionSigners(ApplicationEngine engine, UInt256 hash)
{
TransactionState state = GetTransactionState(engine.Snapshot, hash);
if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return null;
return state.Transaction.Signers;
}
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
private VMState GetTransactionVMState(ApplicationEngine engine, UInt256 hash)
{
TransactionState state = GetTransactionState(engine.Snapshot, hash);
if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return VMState.NONE;
return state.State;
}
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
private int GetTransactionHeight(ApplicationEngine engine, UInt256 hash)
{
TransactionState state = GetTransactionState(engine.Snapshot, hash);
if (state is null || !IsTraceableBlock(engine.Snapshot, state.BlockIndex, engine.ProtocolSettings.MaxTraceableBlocks)) return -1;
return (int)state.BlockIndex;
}
[ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.ReadStates)]
private Transaction GetTransactionFromBlock(ApplicationEngine engine, byte[] blockIndexOrHash, int txIndex)
{
UInt256 hash;
if (blockIndexOrHash.Length < UInt256.Length)
hash = GetBlockHash(engine.Snapshot, (uint)new BigInteger(blockIndexOrHash));
else if (blockIndexOrHash.Length == UInt256.Length)
hash = new UInt256(blockIndexOrHash);
else
throw new ArgumentException(null, nameof(blockIndexOrHash));
if (hash is null) return null;
TrimmedBlock block = GetTrimmedBlock(engine.Snapshot, hash);
if (block is null || !IsTraceableBlock(engine.Snapshot, block.Index, engine.ProtocolSettings.MaxTraceableBlocks)) return null;
if (txIndex < 0 || txIndex >= block.Hashes.Length)
throw new ArgumentOutOfRangeException(nameof(txIndex));
return GetTransaction(engine.Snapshot, block.Hashes[txIndex]);
}
private static TrimmedBlock Trim(Block block)
{
return new TrimmedBlock
{
Header = block.Header,
Hashes = block.Transactions.Select(p => p.Hash).ToArray()
};
}
}
}