-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Transaction.cs
494 lines (454 loc) · 19.2 KB
/
Transaction.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright (C) 2015-2024 The Neo Project.
//
// Transaction.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository 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.Cryptography;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Json;
using Neo.Ledger;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.VM.Types;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static Neo.SmartContract.Helper;
using Array = Neo.VM.Types.Array;
namespace Neo.Network.P2P.Payloads
{
/// <summary>
/// Represents a transaction.
/// </summary>
public class Transaction : IEquatable<Transaction>, IInventory, IInteroperable
{
/// <summary>
/// The maximum size of a transaction.
/// </summary>
public const int MaxTransactionSize = 102400;
/// <summary>
/// The maximum number of attributes that can be contained within a transaction.
/// </summary>
public const int MaxTransactionAttributes = 16;
private byte version;
private uint nonce;
private long sysfee;
private long netfee;
private uint validUntilBlock;
private Signer[] _signers;
private TransactionAttribute[] attributes;
private ReadOnlyMemory<byte> script;
private Witness[] witnesses;
/// <summary>
/// The size of a transaction header.
/// </summary>
public const int HeaderSize =
sizeof(byte) + //Version
sizeof(uint) + //Nonce
sizeof(long) + //SystemFee
sizeof(long) + //NetworkFee
sizeof(uint); //ValidUntilBlock
private Dictionary<Type, TransactionAttribute[]> _attributesCache;
/// <summary>
/// The attributes of the transaction.
/// </summary>
public TransactionAttribute[] Attributes
{
get => attributes;
set { attributes = value; _attributesCache = null; _hash = null; _size = 0; }
}
/// <summary>
/// The <see cref="NetworkFee"/> for the transaction divided by its <see cref="Size"/>.
/// </summary>
public long FeePerByte => NetworkFee / Size;
private UInt256 _hash = null;
public UInt256 Hash
{
get
{
if (_hash == null)
{
_hash = this.CalculateHash();
}
return _hash;
}
}
InventoryType IInventory.InventoryType => InventoryType.TX;
/// <summary>
/// The network fee of the transaction.
/// </summary>
public long NetworkFee //Distributed to consensus nodes.
{
get => netfee;
set { netfee = value; _hash = null; }
}
/// <summary>
/// The nonce of the transaction.
/// </summary>
public uint Nonce
{
get => nonce;
set { nonce = value; _hash = null; }
}
/// <summary>
/// The script of the transaction.
/// </summary>
public ReadOnlyMemory<byte> Script
{
get => script;
set { script = value; _hash = null; _size = 0; }
}
/// <summary>
/// The sender is the first signer of the transaction, regardless of its <see cref="WitnessScope"/>.
/// </summary>
/// <remarks>Note: The sender will pay the fees of the transaction.</remarks>
public UInt160 Sender => _signers[0].Account;
/// <summary>
/// The signers of the transaction.
/// </summary>
public Signer[] Signers
{
get => _signers;
set { _signers = value; _hash = null; _size = 0; }
}
private int _size;
public int Size
{
get
{
if (_size == 0)
{
_size = HeaderSize +
Signers.GetVarSize() + // Signers
Attributes.GetVarSize() + // Attributes
Script.GetVarSize() + // Script
Witnesses.GetVarSize(); // Witnesses
}
return _size;
}
}
/// <summary>
/// The system fee of the transaction.
/// </summary>
public long SystemFee //Fee to be burned.
{
get => sysfee;
set { sysfee = value; _hash = null; }
}
/// <summary>
/// Indicates that the transaction is only valid before this block height.
/// </summary>
public uint ValidUntilBlock
{
get => validUntilBlock;
set { validUntilBlock = value; _hash = null; }
}
/// <summary>
/// The version of the transaction.
/// </summary>
public byte Version
{
get => version;
set { version = value; _hash = null; }
}
public Witness[] Witnesses
{
get => witnesses;
set { witnesses = value; _size = 0; }
}
void ISerializable.Deserialize(ref MemoryReader reader)
{
int startPosition = reader.Position;
DeserializeUnsigned(ref reader);
Witnesses = reader.ReadSerializableArray<Witness>(Signers.Length);
if (Witnesses.Length != Signers.Length) throw new FormatException();
_size = reader.Position - startPosition;
}
private static TransactionAttribute[] DeserializeAttributes(ref MemoryReader reader, int maxCount)
{
int count = (int)reader.ReadVarInt((ulong)maxCount);
TransactionAttribute[] attributes = new TransactionAttribute[count];
HashSet<TransactionAttributeType> hashset = new();
for (int i = 0; i < count; i++)
{
TransactionAttribute attribute = TransactionAttribute.DeserializeFrom(ref reader);
if (!attribute.AllowMultiple && !hashset.Add(attribute.Type))
throw new FormatException();
attributes[i] = attribute;
}
return attributes;
}
private static Signer[] DeserializeSigners(ref MemoryReader reader, int maxCount)
{
int count = (int)reader.ReadVarInt((ulong)maxCount);
if (count == 0) throw new FormatException();
Signer[] signers = new Signer[count];
HashSet<UInt160> hashset = new();
for (int i = 0; i < count; i++)
{
Signer signer = reader.ReadSerializable<Signer>();
if (!hashset.Add(signer.Account)) throw new FormatException();
signers[i] = signer;
}
return signers;
}
public void DeserializeUnsigned(ref MemoryReader reader)
{
Version = reader.ReadByte();
if (Version > 0) throw new FormatException();
Nonce = reader.ReadUInt32();
SystemFee = reader.ReadInt64();
if (SystemFee < 0) throw new FormatException();
NetworkFee = reader.ReadInt64();
if (NetworkFee < 0) throw new FormatException();
if (SystemFee + NetworkFee < SystemFee) throw new FormatException();
ValidUntilBlock = reader.ReadUInt32();
Signers = DeserializeSigners(ref reader, MaxTransactionAttributes);
Attributes = DeserializeAttributes(ref reader, MaxTransactionAttributes - Signers.Length);
Script = reader.ReadVarMemory(ushort.MaxValue);
if (Script.Length == 0) throw new FormatException();
}
public bool Equals(Transaction other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Hash.Equals(other.Hash);
}
public override bool Equals(object obj)
{
return Equals(obj as Transaction);
}
void IInteroperable.FromStackItem(StackItem stackItem)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets the attribute of the specified type.
/// </summary>
/// <typeparam name="T">The type of the attribute.</typeparam>
/// <returns>The first attribute of this type. Or <see langword="null"/> if there is no attribute of this type.</returns>
public T GetAttribute<T>() where T : TransactionAttribute
{
return GetAttributes<T>().FirstOrDefault();
}
/// <summary>
/// Gets all attributes of the specified type.
/// </summary>
/// <typeparam name="T">The type of the attributes.</typeparam>
/// <returns>All the attributes of this type.</returns>
public IEnumerable<T> GetAttributes<T>() where T : TransactionAttribute
{
_attributesCache ??= attributes.GroupBy(p => p.GetType()).ToDictionary(p => p.Key, p => p.ToArray());
if (_attributesCache.TryGetValue(typeof(T), out var result))
return result.OfType<T>();
return Enumerable.Empty<T>();
}
public override int GetHashCode()
{
return Hash.GetHashCode();
}
public UInt160[] GetScriptHashesForVerifying(DataCache snapshot)
{
return Signers.Select(p => p.Account).ToArray();
}
void ISerializable.Serialize(BinaryWriter writer)
{
((IVerifiable)this).SerializeUnsigned(writer);
writer.Write(Witnesses);
}
void IVerifiable.SerializeUnsigned(BinaryWriter writer)
{
writer.Write(Version);
writer.Write(Nonce);
writer.Write(SystemFee);
writer.Write(NetworkFee);
writer.Write(ValidUntilBlock);
writer.Write(Signers);
writer.Write(Attributes);
writer.WriteVarBytes(Script.Span);
}
/// <summary>
/// Converts the transaction to a JSON object.
/// </summary>
/// <param name="settings">The <see cref="ProtocolSettings"/> used during the conversion.</param>
/// <returns>The transaction represented by a JSON object.</returns>
public JObject ToJson(ProtocolSettings settings)
{
JObject json = new();
json["hash"] = Hash.ToString();
json["size"] = Size;
json["version"] = Version;
json["nonce"] = Nonce;
json["sender"] = Sender.ToAddress(settings.AddressVersion);
json["sysfee"] = SystemFee.ToString();
json["netfee"] = NetworkFee.ToString();
json["validuntilblock"] = ValidUntilBlock;
json["signers"] = Signers.Select(p => p.ToJson()).ToArray();
json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray();
json["script"] = Convert.ToBase64String(Script.Span);
json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray();
return json;
}
/// <summary>
/// Verifies the transaction.
/// </summary>
/// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param>
/// <param name="snapshot">The snapshot used to verify the transaction.</param>
/// <param name="context">The <see cref="TransactionVerificationContext"/> used to verify the transaction.</param>
/// <param name="conflictsList">The list of conflicting <see cref="Transaction"/> those fee should be excluded from sender's overall fee during <see cref="TransactionVerificationContext"/>-based verification in case of sender's match.</param>
/// <returns>The result of the verification.</returns>
public VerifyResult Verify(ProtocolSettings settings, DataCache snapshot, TransactionVerificationContext context, IEnumerable<Transaction> conflictsList)
{
VerifyResult result = VerifyStateIndependent(settings);
if (result != VerifyResult.Succeed) return result;
return VerifyStateDependent(settings, snapshot, context, conflictsList);
}
/// <summary>
/// Verifies the state-dependent part of the transaction.
/// </summary>
/// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param>
/// <param name="snapshot">The snapshot used to verify the transaction.</param>
/// <param name="context">The <see cref="TransactionVerificationContext"/> used to verify the transaction.</param>
/// <param name="conflictsList">The list of conflicting <see cref="Transaction"/> those fee should be excluded from sender's overall fee during <see cref="TransactionVerificationContext"/>-based verification in case of sender's match.</param>
/// <returns>The result of the verification.</returns>
public virtual VerifyResult VerifyStateDependent(ProtocolSettings settings, DataCache snapshot, TransactionVerificationContext context, IEnumerable<Transaction> conflictsList)
{
uint height = NativeContract.Ledger.CurrentIndex(snapshot);
if (ValidUntilBlock <= height || ValidUntilBlock > height + settings.MaxValidUntilBlockIncrement)
return VerifyResult.Expired;
UInt160[] hashes = GetScriptHashesForVerifying(snapshot);
foreach (UInt160 hash in hashes)
if (NativeContract.Policy.IsBlocked(snapshot, hash))
return VerifyResult.PolicyFail;
if (!(context?.CheckTransaction(this, conflictsList, snapshot) ?? true)) return VerifyResult.InsufficientFunds;
long attributesFee = 0;
foreach (TransactionAttribute attribute in Attributes)
if (!attribute.Verify(snapshot, this))
return VerifyResult.InvalidAttribute;
else
attributesFee += attribute.CalculateNetworkFee(snapshot, this);
long net_fee = NetworkFee - (Size * NativeContract.Policy.GetFeePerByte(snapshot)) - attributesFee;
if (net_fee < 0) return VerifyResult.InsufficientFunds;
if (net_fee > MaxVerificationGas) net_fee = MaxVerificationGas;
uint execFeeFactor = NativeContract.Policy.GetExecFeeFactor(snapshot);
for (int i = 0; i < hashes.Length; i++)
{
if (IsSignatureContract(witnesses[i].VerificationScript.Span))
net_fee -= execFeeFactor * SignatureContractCost();
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out int m, out int n))
{
net_fee -= execFeeFactor * MultiSignatureContractCost(m, n);
}
else
{
if (!this.VerifyWitness(settings, snapshot, hashes[i], witnesses[i], net_fee, out long fee))
return VerifyResult.Invalid;
net_fee -= fee;
}
if (net_fee < 0) return VerifyResult.InsufficientFunds;
}
return VerifyResult.Succeed;
}
/// <summary>
/// Verifies the state-independent part of the transaction.
/// </summary>
/// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param>
/// <returns>The result of the verification.</returns>
public virtual VerifyResult VerifyStateIndependent(ProtocolSettings settings)
{
if (Size > MaxTransactionSize) return VerifyResult.OverSize;
try
{
_ = new Script(Script, true);
}
catch (BadScriptException)
{
return VerifyResult.InvalidScript;
}
UInt160[] hashes = GetScriptHashesForVerifying(null);
for (int i = 0; i < hashes.Length; i++)
{
if (IsSignatureContract(witnesses[i].VerificationScript.Span))
{
if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid;
var pubkey = witnesses[i].VerificationScript.Span[2..35];
try
{
if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript.Span[2..], pubkey, ECCurve.Secp256r1))
return VerifyResult.InvalidSignature;
}
catch
{
return VerifyResult.Invalid;
}
}
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out var m, out ECPoint[] points))
{
if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid;
var signatures = GetMultiSignatures(witnesses[i].InvocationScript);
if (signatures.Length != m) return VerifyResult.Invalid;
var n = points.Length;
var message = this.GetSignData(settings.Network);
try
{
for (int x = 0, y = 0; x < m && y < n;)
{
if (Crypto.VerifySignature(message, signatures[x].Span, points[y]))
x++;
y++;
if (m - x > n - y)
return VerifyResult.InvalidSignature;
}
}
catch
{
return VerifyResult.Invalid;
}
}
}
return VerifyResult.Succeed;
}
public StackItem ToStackItem(ReferenceCounter referenceCounter)
{
if (_signers == null || _signers.Length == 0) throw new ArgumentException("Sender is not specified in the transaction.");
return new Array(referenceCounter, new StackItem[]
{
// Computed properties
Hash.ToArray(),
// Transaction properties
(int)Version,
Nonce,
Sender.ToArray(),
SystemFee,
NetworkFee,
ValidUntilBlock,
Script,
});
}
private static ReadOnlyMemory<byte>[] GetMultiSignatures(ReadOnlyMemory<byte> script)
{
ReadOnlySpan<byte> span = script.Span;
int i = 0;
var signatures = new List<ReadOnlyMemory<byte>>();
while (i < script.Length)
{
if (span[i++] != (byte)OpCode.PUSHDATA1) return null;
if (i + 65 > script.Length) return null;
if (span[i++] != 64) return null;
signatures.Add(script[i..(i + 64)]);
i += 64;
}
return signatures.ToArray();
}
}
}