-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathUT_MemoryPool.cs
398 lines (343 loc) · 19.7 KB
/
UT_MemoryPool.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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Neo.Ledger;
using FluentAssertions;
using Neo.Cryptography.ECC;
using Neo.IO.Wrappers;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
namespace Neo.UnitTests
{
[TestClass]
public class UT_MemoryPool
{
private static NeoSystem TheNeoSystem;
private readonly Random _random = new Random(1337); // use fixed seed for guaranteed determinism
private MemoryPool _unit;
[TestInitialize]
public void TestSetup()
{
if (TheNeoSystem == null)
{
var mockSnapshot = new Mock<Snapshot>();
mockSnapshot.SetupGet(p => p.Blocks).Returns(new TestDataCache<UInt256, BlockState>());
mockSnapshot.SetupGet(p => p.Transactions).Returns(new TestDataCache<UInt256, TransactionState>());
mockSnapshot.SetupGet(p => p.Accounts).Returns(new TestDataCache<UInt160, AccountState>());
mockSnapshot.SetupGet(p => p.UnspentCoins).Returns(new TestDataCache<UInt256, UnspentCoinState>());
mockSnapshot.SetupGet(p => p.SpentCoins).Returns(new TestDataCache<UInt256, SpentCoinState>());
mockSnapshot.SetupGet(p => p.Validators).Returns(new TestDataCache<ECPoint, ValidatorState>());
mockSnapshot.SetupGet(p => p.Assets).Returns(new TestDataCache<UInt256, AssetState>());
mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache<UInt160, ContractState>());
mockSnapshot.SetupGet(p => p.Storages).Returns(new TestDataCache<StorageKey, StorageItem>());
mockSnapshot.SetupGet(p => p.HeaderHashList)
.Returns(new TestDataCache<UInt32Wrapper, HeaderHashList>());
mockSnapshot.SetupGet(p => p.ValidatorsCount).Returns(new TestMetaDataCache<ValidatorsCountState>());
mockSnapshot.SetupGet(p => p.BlockHashIndex).Returns(new TestMetaDataCache<HashIndexState>());
mockSnapshot.SetupGet(p => p.HeaderHashIndex).Returns(new TestMetaDataCache<HashIndexState>());
var mockStore = new Mock<Store>();
var defaultTx = CreateRandomHashInvocationMockTransaction().Object;
defaultTx.Outputs = new TransactionOutput[1];
defaultTx.Outputs[0] = new TransactionOutput
{
AssetId = Blockchain.UtilityToken.Hash,
Value = new Fixed8(1000000),
ScriptHash = UInt160.Zero // doesn't matter for our purposes.
};
mockStore.Setup(p => p.GetBlocks()).Returns(new TestDataCache<UInt256, BlockState>());
mockStore.Setup(p => p.GetTransactions()).Returns(new TestDataCache<UInt256, TransactionState>(
new TransactionState
{
BlockIndex = 1,
Transaction = defaultTx
}));
mockStore.Setup(p => p.GetAccounts()).Returns(new TestDataCache<UInt160, AccountState>());
mockStore.Setup(p => p.GetUnspentCoins()).Returns(new TestDataCache<UInt256, UnspentCoinState>());
mockStore.Setup(p => p.GetSpentCoins()).Returns(new TestDataCache<UInt256, SpentCoinState>());
mockStore.Setup(p => p.GetValidators()).Returns(new TestDataCache<ECPoint, ValidatorState>());
mockStore.Setup(p => p.GetAssets()).Returns(new TestDataCache<UInt256, AssetState>());
mockStore.Setup(p => p.GetContracts()).Returns(new TestDataCache<UInt160, ContractState>());
mockStore.Setup(p => p.GetStorages()).Returns(new TestDataCache<StorageKey, StorageItem>());
mockStore.Setup(p => p.GetHeaderHashList()).Returns(new TestDataCache<UInt32Wrapper, HeaderHashList>());
mockStore.Setup(p => p.GetValidatorsCount()).Returns(new TestMetaDataCache<ValidatorsCountState>());
mockStore.Setup(p => p.GetBlockHashIndex()).Returns(new TestMetaDataCache<HashIndexState>());
mockStore.Setup(p => p.GetHeaderHashIndex()).Returns(new TestMetaDataCache<HashIndexState>());
mockStore.Setup(p => p.GetSnapshot()).Returns(mockSnapshot.Object);
Console.WriteLine("initialize NeoSystem");
TheNeoSystem = new NeoSystem(mockStore.Object); // new Mock<NeoSystem>(mockStore.Object);
}
// Create a MemoryPool with capacity of 100
_unit = new MemoryPool(TheNeoSystem, 100);
// Verify capacity equals the amount specified
_unit.Capacity.ShouldBeEquivalentTo(100);
_unit.VerifiedCount.ShouldBeEquivalentTo(0);
_unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
_unit.Count.ShouldBeEquivalentTo(0);
}
private Mock<InvocationTransaction> CreateRandomHashInvocationMockTransaction()
{
var mockTx = new Mock<InvocationTransaction>();
mockTx.CallBase = true;
mockTx.Setup(p => p.Verify(It.IsAny<Snapshot>(), It.IsAny<IEnumerable<Transaction>>())).Returns(true);
var tx = mockTx.Object;
var randomBytes = new byte[16];
_random.NextBytes(randomBytes);
tx.Script = randomBytes;
tx.Attributes = new TransactionAttribute[0];
tx.Inputs = new CoinReference[0];
tx.Outputs = new TransactionOutput[0];
tx.Witnesses = new Witness[0];
return mockTx;
}
long LongRandom(long min, long max, Random rand)
{
// Only returns positive random long values.
long longRand = (long) rand.NextBigInteger(63);
return longRand % (max - min) + min;
}
private Transaction CreateMockTransactionWithFee(long fee)
{
var mockTx = CreateRandomHashInvocationMockTransaction();
mockTx.SetupGet(p => p.NetworkFee).Returns(new Fixed8(fee));
var tx = mockTx.Object;
if (fee > 0)
{
tx.Inputs = new CoinReference[1];
// Any input will trigger reading the transaction output and get our mocked transaction output.
tx.Inputs[0] = new CoinReference
{
PrevHash = UInt256.Zero,
PrevIndex = 0
};
}
return tx;
}
private Transaction CreateMockHighPriorityTransaction()
{
return CreateMockTransactionWithFee(LongRandom(100000, 100000000, _random));
}
private Transaction CreateMockLowPriorityTransaction()
{
long rNetFee = LongRandom(0, 100000, _random);
// [0,0.001] GAS a fee lower than the threshold of 0.001 GAS (not enough to be a high priority TX)
return CreateMockTransactionWithFee(rNetFee);
}
private void AddTransactions(int count, bool isHighPriority=false)
{
for (int i = 0; i < count; i++)
{
var txToAdd = isHighPriority ? CreateMockHighPriorityTransaction(): CreateMockLowPriorityTransaction();
Console.WriteLine($"created tx: {txToAdd.Hash}");
_unit.TryAdd(txToAdd.Hash, txToAdd);
}
}
private void AddLowPriorityTransactions(int count) => AddTransactions(count);
public void AddHighPriorityTransactions(int count) => AddTransactions(count, true);
[TestMethod]
public void LowPriorityCapacityTest()
{
// Add over the capacity items, verify that the verified count increases each time
AddLowPriorityTransactions(50);
_unit.VerifiedCount.ShouldBeEquivalentTo(50);
AddLowPriorityTransactions(51);
Console.WriteLine($"VerifiedCount: {_unit.VerifiedCount} LowPrioCount {_unit.SortedLowPrioTxCount} HighPrioCount {_unit.SortedHighPrioTxCount}");
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(100);
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.VerifiedCount.ShouldBeEquivalentTo(100);
_unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
_unit.Count.ShouldBeEquivalentTo(100);
}
[TestMethod]
public void HighPriorityCapacityTest()
{
// Add over the capacity items, verify that the verified count increases each time
AddHighPriorityTransactions(101);
Console.WriteLine($"VerifiedCount: {_unit.VerifiedCount} LowPrioCount {_unit.SortedLowPrioTxCount} HighPrioCount {_unit.SortedHighPrioTxCount}");
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(0);
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(100);
_unit.VerifiedCount.ShouldBeEquivalentTo(100);
_unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
_unit.Count.ShouldBeEquivalentTo(100);
}
[TestMethod]
public void HighPriorityPushesOutLowPriority()
{
// Add over the capacity items, verify that the verified count increases each time
AddLowPriorityTransactions(70);
AddHighPriorityTransactions(40);
Console.WriteLine($"VerifiedCount: {_unit.VerifiedCount} LowPrioCount {_unit.SortedLowPrioTxCount} HighPrioCount {_unit.SortedHighPrioTxCount}");
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(60);
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(40);
_unit.Count.ShouldBeEquivalentTo(100);
}
[TestMethod]
public void LowPriorityDoesNotPushOutHighPrority()
{
AddHighPriorityTransactions(70);
AddLowPriorityTransactions(40);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(30);
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(70);
_unit.Count.ShouldBeEquivalentTo(100);
}
[TestMethod]
public void BlockPersistMovesTxToUnverifiedAndReverification()
{
AddHighPriorityTransactions(70);
AddLowPriorityTransactions(30);
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(70);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(30);
var block = new Block
{
Transactions = _unit.GetSortedVerifiedTransactions().Take(10)
.Concat(_unit.GetSortedVerifiedTransactions().Where(x => x.IsLowPriority).Take(5)).ToArray()
};
_unit.UpdatePoolForBlockPersisted(block, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(60);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(25);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(9);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(1);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(51);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(24);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(18);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(2);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(42);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(23);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(27);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(3);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(33);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(22);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(36);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(4);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(24);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(21);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(45);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(5);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(15);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(20);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(54);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(6);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(6);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(19);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(60);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(10);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(15);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(60);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(20);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(5);
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(10, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(60);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(25);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(0);
}
private void verifyTransactionsSortedDescending(IEnumerable<Transaction> transactions)
{
Transaction lastTransaction = null;
foreach (var tx in transactions)
{
if (lastTransaction != null)
{
if (lastTransaction.FeePerByte == tx.FeePerByte)
{
if (lastTransaction.NetworkFee == tx.NetworkFee)
lastTransaction.Hash.Should().BeGreaterThan(tx.Hash);
else
lastTransaction.NetworkFee.Should().BeGreaterThan(tx.NetworkFee);
}
else
{
lastTransaction.FeePerByte.Should().BeGreaterThan(tx.FeePerByte);
}
}
lastTransaction = tx;
}
}
[TestMethod]
public void VerifySortOrderAndThatHighetFeeTransactionsAreReverifiedFirst()
{
AddLowPriorityTransactions(50);
AddHighPriorityTransactions(50);
var sortedVerifiedTxs = _unit.GetSortedVerifiedTransactions().ToList();
// verify all 100 transactions are returned in sorted order
sortedVerifiedTxs.Count.ShouldBeEquivalentTo(100);
verifyTransactionsSortedDescending(sortedVerifiedTxs);
// move all to unverified
var block = new Block { Transactions = new Transaction[0] };
_unit.UpdatePoolForBlockPersisted(block, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(50);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(50);
// We can verify the order they are re-verified by reverifying 2 at a time
while (_unit.UnVerifiedCount > 0)
{
_unit.GetVerifiedAndUnverifiedTransactions(out IEnumerable<Transaction> sortedVerifiedTransactions,
out IEnumerable<Transaction> sortedUnverifiedTransactions);
sortedVerifiedTransactions.Count().ShouldBeEquivalentTo(0);
var sortedUnverifiedArray = sortedUnverifiedTransactions.ToArray();
verifyTransactionsSortedDescending(sortedUnverifiedArray);
var maxHighPriorityTransaction = sortedUnverifiedArray.First();
var maxLowPriorityTransaction = sortedUnverifiedArray.First(tx => tx.IsLowPriority);
// reverify 1 high priority and 1 low priority transaction
_unit.ReVerifyTopUnverifiedTransactionsIfNeeded(2, Blockchain.Singleton.GetSnapshot());
var verifiedTxs = _unit.GetSortedVerifiedTransactions().ToArray();
verifiedTxs.Length.ShouldBeEquivalentTo(2);
verifiedTxs[0].ShouldBeEquivalentTo(maxHighPriorityTransaction);
verifiedTxs[1].ShouldBeEquivalentTo(maxLowPriorityTransaction);
var blockWith2Tx = new Block { Transactions = new Transaction[2] { maxHighPriorityTransaction, maxLowPriorityTransaction }};
// verify and remove the 2 transactions from the verified pool
_unit.UpdatePoolForBlockPersisted(blockWith2Tx, Blockchain.Singleton.GetSnapshot());
_unit.SortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.SortedLowPrioTxCount.ShouldBeEquivalentTo(0);
}
_unit.UnverifiedSortedHighPrioTxCount.ShouldBeEquivalentTo(0);
_unit.UnverifiedSortedLowPrioTxCount.ShouldBeEquivalentTo(0);
}
void VerifyCapacityThresholdForAttemptingToAddATransaction()
{
var sortedVerified = _unit.GetSortedVerifiedTransactions().ToArray();
var txBarelyWontFit = CreateMockTransactionWithFee(sortedVerified.Last().NetworkFee.GetData() - 1);
_unit.CanTransactionFitInPool(txBarelyWontFit).ShouldBeEquivalentTo(false);
var txBarelyFits = CreateMockTransactionWithFee(sortedVerified.Last().NetworkFee.GetData() + 1);
_unit.CanTransactionFitInPool(txBarelyFits).ShouldBeEquivalentTo(true);
}
[TestMethod]
public void VerifyCanTransactionFitInPoolWorksAsIntended()
{
AddLowPriorityTransactions(100);
VerifyCapacityThresholdForAttemptingToAddATransaction();
AddHighPriorityTransactions(50);
VerifyCapacityThresholdForAttemptingToAddATransaction();
AddHighPriorityTransactions(50);
VerifyCapacityThresholdForAttemptingToAddATransaction();
}
[TestMethod]
public void CapacityTestWithUnverifiedHighProirtyTransactions()
{
// Verify that unverified high priority transactions will not be pushed out of the queue by incoming
// low priority transactions
// Fill pool with high priority transactions
AddHighPriorityTransactions(99);
// move all to unverified
var block = new Block { Transactions = new Transaction[0] };
_unit.UpdatePoolForBlockPersisted(block, Blockchain.Singleton.GetSnapshot());
_unit.CanTransactionFitInPool(CreateMockLowPriorityTransaction()).ShouldBeEquivalentTo(true);
AddHighPriorityTransactions(1);
_unit.CanTransactionFitInPool(CreateMockLowPriorityTransaction()).ShouldBeEquivalentTo(false);
}
}
}