-
Notifications
You must be signed in to change notification settings - Fork 492
/
TransactionStore.cs
328 lines (279 loc) · 7.28 KB
/
TransactionStore.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
using Microsoft.Data.Sqlite;
using NBitcoin;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Extensions;
using WalletWasabi.Helpers;
using WalletWasabi.Io;
using WalletWasabi.Logging;
using WalletWasabi.Stores;
namespace WalletWasabi.Blockchain.Transactions;
public class TransactionStore : IAsyncDisposable
{
public TransactionStore(string workFolderPath, Network network, bool migrateData = true)
{
workFolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(workFolderPath), workFolderPath, trim: true);
IoHelpers.EnsureDirectoryExists(workFolderPath);
if (workFolderPath == SqliteStorageHelper.InMemoryDatabase)
{
DataSource = SqliteStorageHelper.InMemoryDatabase;
}
else
{
IoHelpers.EnsureDirectoryExists(workFolderPath);
DataSource = Path.Combine(workFolderPath, "Transactions.sqlite");
// TODO: Remove. Useful for testing.
// if (File.Exists(dataSource))
// {
// File.Delete(dataSource);
// }
}
SqliteStorage = TransactionSqliteStorage.FromFile(dataSource: DataSource, network);
if (migrateData)
{
string oldPath = Path.Combine(workFolderPath, "Transactions.dat");
Import(oldPath, network, deleteAfterImport: false);
}
}
private string DataSource { get; }
private object SqliteStorageLock { get; } = new();
/// <remarks>Guarded by <see cref="SqliteStorageLock"/>.</remarks>
private TransactionSqliteStorage SqliteStorage { get; }
/// <remarks>Guarded by <see cref="SqliteStorageLock"/>.</remarks>
private Dictionary<uint256, SmartTransaction> Transactions { get; } = new();
private void Import(string oldPath, Network network, bool deleteAfterImport = false)
{
if (File.Exists(oldPath))
{
SqliteStorage.Clear();
IoManager transactionsFileManager = new(filePath: oldPath);
string[] allLines = File.ReadAllLines(oldPath, Encoding.UTF8);
IEnumerable<SmartTransaction> allTransactions = allLines.Select(x => SmartTransaction.FromLine(x, network));
SqliteStorage.BulkInsert(allTransactions);
if (deleteAfterImport)
{
Logger.LogInfo($"Removing old '{oldPath}' transaction storage.");
File.Delete(oldPath);
}
}
}
public Task InitializeAsync(string operationName, CancellationToken cancellationToken)
{
using (BenchmarkLogger.Measure(operationName: operationName))
{
lock (SqliteStorageLock)
{
InitializeTransactionsNoLock(cancellationToken);
}
}
return Task.CompletedTask;
}
private void InitializeTransactionsNoLock(CancellationToken cancellationToken)
{
try
{
lock (SqliteStorageLock)
{
int i = 0;
foreach (SmartTransaction tx in SqliteStorage.GetAll(cancellationToken).OrderByBlockchain())
{
i++;
if (i % 100 == 0)
{
cancellationToken.ThrowIfCancellationRequested();
}
_ = TryAddOrUpdateNoLockNoSerialization(tx);
}
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// We found a corrupted entry. Stop here.
// Do not try to automatically correct the data, because the internal data structures are throwing events that may confuse the consumers of those events.
Logger.LogError($"'{DataSource}' database got corrupted. Clearing it...");
SqliteStorage.Clear();
throw;
}
}
private bool TryAddOrUpdateNoLockNoSerialization(SmartTransaction tx)
{
uint256 hash = tx.GetHash();
if (Transactions.TryAdd(hash, tx))
{
return true;
}
else
{
if (Transactions[hash].TryUpdate(tx))
{
return true;
}
}
return false;
}
public bool TryAdd(SmartTransaction tx)
{
lock (SqliteStorageLock)
{
if (Transactions.TryAdd(tx.GetHash(), tx))
{
if (SqliteStorage.BulkInsert(tx) == 0)
{
throw new UnreachableException($"Transaction '{tx.GetHash()}' was added in memory but not in database.");
}
return true;
}
return false;
}
}
public bool TryAddOrUpdate(SmartTransaction tx)
{
lock (SqliteStorageLock)
{
bool result = TryAddOrUpdateNoLockNoSerialization(tx);
if (result)
{
if (SqliteStorage.BulkInsert(new SmartTransaction[] { tx }, upsert: true) == 0)
{
throw new UnreachableException($"Transaction '{tx.GetHash()}' was update in memory but not in database.");
}
}
return result;
}
}
public bool TryUpdate(SmartTransaction tx)
{
bool updated = false;
lock (SqliteStorageLock)
{
if (Transactions.TryGetValue(tx.GetHash(), out var foundTx))
{
if (foundTx.TryUpdate(tx))
{
updated = true;
if (SqliteStorage.BulkUpdate(tx) == 0)
{
throw new UnreachableException($"Transaction '{tx.GetHash()}' was update in memory but not in database.");
}
}
}
}
return updated;
}
public bool TryRemove(uint256 hash, [NotNullWhen(true)] out SmartTransaction? tx)
{
bool isRemoved = false;
lock (SqliteStorageLock)
{
if (Transactions.Remove(hash, out tx))
{
isRemoved = true;
if (!SqliteStorage.TryRemove(hash, out _))
{
throw new UnreachableException($"Transaction '{tx.GetHash()}' was removed from memory but not from database.");
}
}
}
return isRemoved;
}
public bool TryGetTransaction(uint256 hash, [NotNullWhen(true)] out SmartTransaction? tx)
{
lock (SqliteStorageLock)
{
return Transactions.TryGetValue(hash, out tx);
}
}
public List<SmartTransaction> GetTransactions()
{
lock (SqliteStorageLock)
{
return Transactions.Values.OrderByBlockchain().ToList();
}
}
public List<uint256> GetTransactionHashes()
{
lock (SqliteStorageLock)
{
return Transactions.Values.OrderByBlockchain().Select(x => x.GetHash()).ToList();
}
}
public bool IsEmpty()
{
lock (SqliteStorageLock)
{
return Transactions.Count == 0;
}
}
public bool Contains(uint256 hash)
{
lock (SqliteStorageLock)
{
return Transactions.ContainsKey(hash);
}
}
private int BulkInsert(params SmartTransaction[] transactions)
=> BulkInsert(transactions as IEnumerable<SmartTransaction>);
private int BulkInsert(IEnumerable<SmartTransaction> transactions)
{
try
{
lock (SqliteStorageLock)
{
return SqliteStorage.BulkInsert(transactions.OrderByBlockchain());
}
}
catch (SqliteException ex)
{
Logger.LogError(ex);
throw;
}
}
private void BulkDelete(params uint256[] transactionIds)
=> BulkDelete(transactionIds as IReadOnlyList<uint256>);
private void BulkDelete(IReadOnlyList<uint256> transactionIds)
{
try
{
lock (SqliteStorageLock)
{
SqliteStorage.BulkRemove(transactionIds);
}
}
catch (SqliteException ex)
{
Logger.LogError(ex);
throw;
}
}
/// <inheritdoc cref="BulkUpdate(IEnumerable{SmartTransaction})"/>
private int BulkUpdate(params SmartTransaction[] transactions)
=> BulkUpdate(transactions as IEnumerable<SmartTransaction>);
/// <returns>Number of modified rows.</returns>
/// <exception cref="SqliteException">If there is an issue with the operation.</exception>
private int BulkUpdate(IEnumerable<SmartTransaction> transactions)
{
try
{
lock (SqliteStorageLock)
{
return SqliteStorage.BulkUpdate(transactions);
}
}
catch (SqliteException ex)
{
Logger.LogError(ex);
throw;
}
}
public ValueTask DisposeAsync()
{
SqliteStorage.Dispose();
return ValueTask.CompletedTask;
}
}