| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using NBitcoin; |
| | | 6 | | using NetMQ; |
| | | 7 | | using NetMQ.Sockets; |
| | | 8 | | |
| | | 9 | | namespace NLightning.Infrastructure.Bitcoin.Wallet; |
| | | 10 | | |
| | | 11 | | using Domain.Bitcoin.Events; |
| | | 12 | | using Domain.Bitcoin.Transactions.Models; |
| | | 13 | | using Domain.Bitcoin.ValueObjects; |
| | | 14 | | using Domain.Channels.ValueObjects; |
| | | 15 | | using Domain.Crypto.ValueObjects; |
| | | 16 | | using Domain.Node.Options; |
| | | 17 | | using Domain.Persistence.Interfaces; |
| | | 18 | | using Interfaces; |
| | | 19 | | using Options; |
| | | 20 | | |
| | | 21 | | public class BlockchainMonitorService : IBlockchainMonitor |
| | | 22 | | { |
| | | 23 | | private readonly BitcoinOptions _bitcoinOptions; |
| | | 24 | | private readonly IBitcoinWallet _bitcoinWallet; |
| | | 25 | | private readonly ILogger<BlockchainMonitorService> _logger; |
| | | 26 | | private readonly IServiceProvider _serviceProvider; |
| | | 27 | | private readonly Network _network; |
| | 44 | 28 | | private readonly SemaphoreSlim _newBlockSemaphore = new(1, 1); |
| | 44 | 29 | | private readonly SemaphoreSlim _blockBacklogSemaphore = new(1, 1); |
| | 44 | 30 | | private readonly ConcurrentDictionary<uint256, WatchedTransactionModel> _watchedTransactions = new(); |
| | | 31 | | #if NET9_0_OR_GREATER |
| | 44 | 32 | | private readonly OrderedDictionary<uint, Block> _blocksToProcess = new(); |
| | | 33 | | #else |
| | | 34 | | // TODO: Check if ordering is the same in .NET 8 |
| | | 35 | | private readonly SortedDictionary<uint, Block> _blocksToProcess = new(); |
| | | 36 | | #endif |
| | | 37 | | |
| | 44 | 38 | | private BlockchainState _blockchainState = new(0, Hash.Empty, DateTime.UtcNow); |
| | | 39 | | private CancellationTokenSource? _cts; |
| | | 40 | | private Task? _monitoringTask; |
| | | 41 | | private uint _lastProcessedBlockHeight; |
| | | 42 | | private SubscriberSocket? _blockSocket; |
| | | 43 | | // private SubscriberSocket? _transactionSocket; |
| | | 44 | | |
| | | 45 | | public event EventHandler<NewBlockEventArgs>? OnNewBlockDetected; |
| | | 46 | | public event EventHandler<TransactionConfirmedEventArgs>? OnTransactionConfirmed; |
| | | 47 | | |
| | 44 | 48 | | public BlockchainMonitorService(IOptions<BitcoinOptions> bitcoinOptions, IBitcoinWallet bitcoinWallet, |
| | 44 | 49 | | ILogger<BlockchainMonitorService> logger, IOptions<NodeOptions> nodeOptions, |
| | 44 | 50 | | IServiceProvider serviceProvider) |
| | | 51 | | { |
| | 44 | 52 | | _bitcoinOptions = bitcoinOptions.Value; |
| | 44 | 53 | | _bitcoinWallet = bitcoinWallet; |
| | 44 | 54 | | _logger = logger; |
| | 44 | 55 | | _serviceProvider = serviceProvider; |
| | 44 | 56 | | _network = Network.GetNetwork(nodeOptions.Value.BitcoinNetwork) ?? Network.Main; |
| | 44 | 57 | | } |
| | | 58 | | |
| | | 59 | | public async Task StartAsync(uint heightOfBirth, CancellationToken cancellationToken) |
| | | 60 | | { |
| | 32 | 61 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 62 | | |
| | 32 | 63 | | using var scope = _serviceProvider.CreateScope(); |
| | 32 | 64 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | | 65 | | |
| | | 66 | | // Load pending transactions |
| | 32 | 67 | | await LoadPendingWatchedTransactionsAsync(uow); |
| | | 68 | | |
| | | 69 | | // Get the current state or create a new one if it doesn't exist |
| | 32 | 70 | | var currentBlockchainState = await uow.BlockchainStateDbRepository.GetStateAsync(); |
| | 32 | 71 | | if (currentBlockchainState is null) |
| | | 72 | | { |
| | 20 | 73 | | _logger.LogInformation("No blockchain state found, starting from height {Height}", heightOfBirth); |
| | | 74 | | |
| | 20 | 75 | | _lastProcessedBlockHeight = heightOfBirth; |
| | 20 | 76 | | _blockchainState = new BlockchainState(_lastProcessedBlockHeight, Hash.Empty, DateTime.UtcNow); |
| | 20 | 77 | | uow.BlockchainStateDbRepository.Add(_blockchainState); |
| | | 78 | | } |
| | | 79 | | else |
| | | 80 | | { |
| | 12 | 81 | | _blockchainState = currentBlockchainState; |
| | 12 | 82 | | _lastProcessedBlockHeight = _blockchainState.LastProcessedHeight; |
| | 12 | 83 | | _logger.LogInformation("Starting blockchain monitoring at height {Height}, last block hash {LastBlockHash}", |
| | 12 | 84 | | _lastProcessedBlockHeight, _blockchainState.LastProcessedBlockHash); |
| | | 85 | | } |
| | | 86 | | |
| | | 87 | | // Get the current block height from the wallet |
| | 32 | 88 | | var currentBlockHeight = await _bitcoinWallet.GetCurrentBlockHeightAsync(); |
| | | 89 | | |
| | | 90 | | // Add the current block to the processing queue |
| | 32 | 91 | | var currentBlock = await _bitcoinWallet.GetBlockAsync(_lastProcessedBlockHeight); |
| | 32 | 92 | | if (currentBlock is not null) |
| | 28 | 93 | | _blocksToProcess[_lastProcessedBlockHeight] = currentBlock; |
| | | 94 | | |
| | | 95 | | // Add missing blocks to the processing queue and process any pending blocks |
| | 32 | 96 | | await AddMissingBlocksToProcessAsync(currentBlockHeight); |
| | 32 | 97 | | await ProcessPendingBlocksAsync(uow); |
| | | 98 | | |
| | 32 | 99 | | await uow.SaveChangesAsync(); |
| | | 100 | | |
| | | 101 | | // Initialize ZMQ sockets |
| | 32 | 102 | | InitializeZmqSockets(); |
| | | 103 | | |
| | | 104 | | // Start monitoring task |
| | 32 | 105 | | _monitoringTask = MonitorBlockchainAsync(_cts.Token); |
| | | 106 | | |
| | 32 | 107 | | _logger.LogInformation("Blockchain monitor service started successfully"); |
| | 32 | 108 | | } |
| | | 109 | | |
| | | 110 | | public async Task StopAsync() |
| | | 111 | | { |
| | 8 | 112 | | if (_cts is null) |
| | | 113 | | { |
| | 0 | 114 | | throw new InvalidOperationException("Service is not running"); |
| | | 115 | | } |
| | | 116 | | |
| | 8 | 117 | | await _cts.CancelAsync(); |
| | | 118 | | |
| | 8 | 119 | | if (_monitoringTask is not null) |
| | | 120 | | { |
| | | 121 | | try |
| | | 122 | | { |
| | 8 | 123 | | await _monitoringTask; |
| | 8 | 124 | | } |
| | 0 | 125 | | catch (OperationCanceledException) |
| | | 126 | | { |
| | | 127 | | // Expected during cancellation |
| | 0 | 128 | | } |
| | | 129 | | } |
| | | 130 | | |
| | 8 | 131 | | CleanupZmqSockets(); |
| | 8 | 132 | | } |
| | | 133 | | |
| | | 134 | | public async Task WatchTransactionAsync(ChannelId channelId, TxId txId, uint requiredDepth) |
| | | 135 | | { |
| | 4 | 136 | | _logger.LogInformation("Watching transaction {TxId} for {RequiredDepth} confirmations for channel {channelId}", |
| | 4 | 137 | | txId, requiredDepth, channelId); |
| | | 138 | | |
| | 4 | 139 | | using var scope = _serviceProvider.CreateScope(); |
| | 4 | 140 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | | 141 | | |
| | 4 | 142 | | var nBitcoinTxId = new uint256(txId); |
| | 4 | 143 | | var watchedTx = new WatchedTransactionModel(channelId, txId, requiredDepth); |
| | | 144 | | |
| | 4 | 145 | | uow.WatchedTransactionDbRepository.Add(watchedTx); |
| | | 146 | | |
| | 4 | 147 | | _watchedTransactions[nBitcoinTxId] = watchedTx; |
| | | 148 | | |
| | 4 | 149 | | await uow.SaveChangesAsync(); |
| | 4 | 150 | | } |
| | | 151 | | |
| | | 152 | | // public Task WatchForRevocationAsync(TxId commitmentTxId, SignedTransaction penaltyTx) |
| | | 153 | | // { |
| | | 154 | | // _logger.LogInformation("Watching for revocation of commitment transaction {CommitmentTxId}", commitmentTxId); |
| | | 155 | | // |
| | | 156 | | // var nBitcoinTxId = new uint256(commitmentTxId); |
| | | 157 | | // var revocationWatch = new RevocationWatch(nBitcoinTxId, Transaction.Load(penaltyTx.RawTxBytes, _network)); |
| | | 158 | | // |
| | | 159 | | // _revocationWatches.TryAdd(nBitcoinTxId, revocationWatch); |
| | | 160 | | // return Task.CompletedTask; |
| | | 161 | | // } |
| | | 162 | | |
| | | 163 | | private async Task MonitorBlockchainAsync(CancellationToken cancellationToken) |
| | | 164 | | { |
| | 32 | 165 | | _logger.LogInformation("Starting blockchain monitoring loop"); |
| | | 166 | | |
| | | 167 | | try |
| | | 168 | | { |
| | 170 | 169 | | while (!cancellationToken.IsCancellationRequested) |
| | | 170 | | { |
| | | 171 | | try |
| | | 172 | | { |
| | | 173 | | // Check for new blocks |
| | 170 | 174 | | if (_blockSocket != null && |
| | 170 | 175 | | _blockSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out var topic)) |
| | | 176 | | { |
| | 0 | 177 | | if (topic == "rawblock" && _blockSocket.TryReceiveFrameBytes(out var blockHashBytes)) |
| | | 178 | | { |
| | | 179 | | try |
| | | 180 | | { |
| | | 181 | | // One at a time |
| | 0 | 182 | | await _newBlockSemaphore.WaitAsync(cancellationToken); |
| | 0 | 183 | | var block = Block.Load(blockHashBytes, _network); |
| | 0 | 184 | | var coinbaseHeight = block.GetCoinbaseHeight(); |
| | 0 | 185 | | if (!coinbaseHeight.HasValue) |
| | | 186 | | { |
| | | 187 | | // Get the current height from the wallet |
| | 0 | 188 | | var currentHeight = await _bitcoinWallet.GetCurrentBlockHeightAsync(); |
| | | 189 | | |
| | | 190 | | // Get the block from the wallet |
| | 0 | 191 | | var blockAtHeight = await _bitcoinWallet.GetBlockAsync(currentHeight); |
| | 0 | 192 | | if (blockAtHeight is null) |
| | | 193 | | { |
| | 0 | 194 | | _logger.LogError("Failed to retrieve block at height {Height}", currentHeight); |
| | 0 | 195 | | return; |
| | | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | coinbaseHeight = (int)currentHeight; |
| | | 199 | | } |
| | | 200 | | |
| | 0 | 201 | | await ProcessNewBlock(block, (uint)coinbaseHeight); |
| | 0 | 202 | | } |
| | | 203 | | finally |
| | | 204 | | { |
| | 0 | 205 | | _newBlockSemaphore.Release(); |
| | | 206 | | } |
| | | 207 | | } |
| | 0 | 208 | | } |
| | | 209 | | |
| | | 210 | | // TODO: Check for new transactions |
| | | 211 | | // if (_transactionSocket != null && |
| | | 212 | | // _transactionSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out var txTopic)) |
| | | 213 | | // { |
| | | 214 | | // if (txTopic == "rawtx" && _transactionSocket.TryReceiveFrameBytes(out var rawTxBytes)) |
| | | 215 | | // { |
| | | 216 | | // await ProcessNewTransaction(rawTxBytes); |
| | | 217 | | // } |
| | | 218 | | // } |
| | | 219 | | |
| | | 220 | | // Small delay to prevent CPU spinning |
| | 154 | 221 | | await Task.Delay(50, cancellationToken); |
| | 138 | 222 | | } |
| | 8 | 223 | | catch (Exception ex) when (!cancellationToken.IsCancellationRequested) |
| | | 224 | | { |
| | 0 | 225 | | _logger.LogError(ex, "Error in blockchain monitoring loop"); |
| | 0 | 226 | | await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); |
| | | 227 | | } |
| | | 228 | | } |
| | 0 | 229 | | } |
| | 8 | 230 | | catch (OperationCanceledException) |
| | | 231 | | { |
| | 8 | 232 | | _logger.LogInformation("Blockchain monitoring loop cancelled"); |
| | 8 | 233 | | } |
| | 0 | 234 | | catch (Exception ex) |
| | | 235 | | { |
| | 0 | 236 | | _logger.LogError(ex, "Fatal error in blockchain monitoring loop"); |
| | 0 | 237 | | } |
| | 8 | 238 | | } |
| | | 239 | | |
| | | 240 | | private void InitializeZmqSockets() |
| | | 241 | | { |
| | | 242 | | try |
| | | 243 | | { |
| | | 244 | | // Subscribe to new blocks |
| | 32 | 245 | | _blockSocket = new SubscriberSocket(); |
| | 32 | 246 | | _blockSocket.Connect($"tcp://{_bitcoinOptions.ZmqHost}:{_bitcoinOptions.ZmqBlockPort}"); |
| | 32 | 247 | | _blockSocket.Subscribe("rawblock"); |
| | | 248 | | |
| | | 249 | | // // Subscribe to new transactions (for mempool monitoring) |
| | | 250 | | // _transactionSocket = new SubscriberSocket(); |
| | | 251 | | // _transactionSocket.Connect($"tcp://{_bitcoinOptions.ZmqHost}:{_bitcoinOptions.ZmqTxPort}"); |
| | | 252 | | // _transactionSocket.Subscribe("rawtx"); |
| | | 253 | | |
| | 32 | 254 | | _logger.LogInformation("ZMQ sockets initialized - Block: {BlockPort}, Tx: {TxPort}", |
| | 32 | 255 | | _bitcoinOptions.ZmqBlockPort, _bitcoinOptions.ZmqTxPort); |
| | 32 | 256 | | } |
| | 0 | 257 | | catch (Exception ex) |
| | | 258 | | { |
| | 0 | 259 | | _logger.LogError(ex, "Failed to initialize ZMQ sockets"); |
| | 0 | 260 | | CleanupZmqSockets(); |
| | 0 | 261 | | throw; |
| | | 262 | | } |
| | 32 | 263 | | } |
| | | 264 | | |
| | | 265 | | private void CleanupZmqSockets() |
| | | 266 | | { |
| | | 267 | | try |
| | | 268 | | { |
| | 8 | 269 | | _blockSocket?.Dispose(); |
| | 8 | 270 | | _blockSocket = null; |
| | | 271 | | |
| | | 272 | | // _transactionSocket?.Dispose(); |
| | | 273 | | // _transactionSocket = null; |
| | | 274 | | |
| | 8 | 275 | | _logger.LogDebug("ZMQ sockets cleaned up"); |
| | 8 | 276 | | } |
| | 0 | 277 | | catch (Exception ex) |
| | | 278 | | { |
| | 0 | 279 | | _logger.LogError(ex, "Error cleaning up ZMQ sockets"); |
| | 0 | 280 | | } |
| | 8 | 281 | | } |
| | | 282 | | |
| | | 283 | | private async Task ProcessPendingBlocksAsync(IUnitOfWork uow) |
| | | 284 | | { |
| | | 285 | | try |
| | | 286 | | { |
| | 36 | 287 | | await _blockBacklogSemaphore.WaitAsync(); |
| | | 288 | | |
| | 800 | 289 | | while (_blocksToProcess.Count > 0) |
| | | 290 | | { |
| | 764 | 291 | | var blockKvp = _blocksToProcess.First(); |
| | 764 | 292 | | if (blockKvp.Key <= _lastProcessedBlockHeight) |
| | 28 | 293 | | _logger.LogWarning("Possible reorg detected: Block {Height} is already processed.", blockKvp.Key); |
| | | 294 | | |
| | 764 | 295 | | ProcessBlock(blockKvp.Value, blockKvp.Key, uow); |
| | | 296 | | } |
| | 36 | 297 | | } |
| | | 298 | | finally |
| | | 299 | | { |
| | 36 | 300 | | _blockBacklogSemaphore.Release(); |
| | | 301 | | } |
| | 36 | 302 | | } |
| | | 303 | | |
| | | 304 | | private async Task AddMissingBlocksToProcessAsync(uint currentHeight) |
| | | 305 | | { |
| | 36 | 306 | | var lastProcessedHeight = _lastProcessedBlockHeight + 1; |
| | 36 | 307 | | if (currentHeight > lastProcessedHeight) |
| | | 308 | | { |
| | 28 | 309 | | _logger.LogWarning("Processing missed blocks from height {LastProcessedHeight} to {CurrentHeight}", |
| | 28 | 310 | | lastProcessedHeight, currentHeight); |
| | | 311 | | |
| | 1520 | 312 | | for (var height = lastProcessedHeight; height < currentHeight; height++) |
| | | 313 | | { |
| | 732 | 314 | | if (_blocksToProcess.ContainsKey(height)) |
| | | 315 | | continue; |
| | | 316 | | |
| | | 317 | | // Add missing block to process queue |
| | 732 | 318 | | var blockAtHeight = await _bitcoinWallet.GetBlockAsync(height); |
| | 732 | 319 | | if (blockAtHeight is not null) |
| | | 320 | | { |
| | 732 | 321 | | _blocksToProcess[height] = blockAtHeight; |
| | | 322 | | } |
| | | 323 | | else |
| | | 324 | | { |
| | 0 | 325 | | _logger.LogError("Missing block at height {Height}", height); |
| | | 326 | | } |
| | | 327 | | } |
| | | 328 | | } |
| | 36 | 329 | | } |
| | | 330 | | |
| | | 331 | | private async Task ProcessNewBlock(Block block, uint currentHeight) |
| | | 332 | | { |
| | 4 | 333 | | using var scope = _serviceProvider.CreateScope(); |
| | 4 | 334 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | | 335 | | |
| | 4 | 336 | | var blockHash = block.GetHash(); |
| | | 337 | | |
| | | 338 | | try |
| | | 339 | | { |
| | 4 | 340 | | _logger.LogDebug("Processing block at height {blockHeight}: {BlockHash}", currentHeight, blockHash); |
| | | 341 | | |
| | | 342 | | // Check for missed blocks first |
| | 4 | 343 | | await AddMissingBlocksToProcessAsync(currentHeight); |
| | | 344 | | |
| | | 345 | | // Store the current block for processing |
| | 4 | 346 | | _blocksToProcess[currentHeight] = block; |
| | | 347 | | |
| | | 348 | | // Process missing blocks |
| | 4 | 349 | | await ProcessPendingBlocksAsync(uow); |
| | 4 | 350 | | } |
| | 0 | 351 | | catch (Exception ex) |
| | | 352 | | { |
| | 0 | 353 | | _logger.LogError(ex, "Error processing new block {BlockHash}", blockHash); |
| | 0 | 354 | | } |
| | | 355 | | |
| | 4 | 356 | | await uow.SaveChangesAsync(); |
| | 4 | 357 | | } |
| | | 358 | | |
| | | 359 | | // TODO: Check for revocation transactions in mempool |
| | | 360 | | // private async Task ProcessNewTransaction(byte[] rawTxBytes) |
| | | 361 | | // { |
| | | 362 | | // try |
| | | 363 | | // { |
| | | 364 | | // var transaction = Transaction.Load(rawTxBytes, Network.Main); |
| | | 365 | | // } |
| | | 366 | | // catch (Exception ex) |
| | | 367 | | // { |
| | | 368 | | // _logger.LogError(ex, "Error processing new transaction from mempool"); |
| | | 369 | | // } |
| | | 370 | | // } |
| | | 371 | | |
| | | 372 | | private void ProcessBlock(Block block, uint height, IUnitOfWork uow) |
| | | 373 | | { |
| | | 374 | | try |
| | | 375 | | { |
| | 764 | 376 | | var blockHash = block.GetHash(); |
| | | 377 | | |
| | 764 | 378 | | _logger.LogDebug("Processing block {Height} with {TxCount} transactions", height, block.Transactions.Count); |
| | | 379 | | |
| | | 380 | | // Notify listeners of the new block |
| | 764 | 381 | | OnNewBlockDetected?.Invoke(this, new NewBlockEventArgs(height, blockHash.ToBytes())); |
| | | 382 | | |
| | | 383 | | // Check if watched transactions are included in this block |
| | 764 | 384 | | CheckWatchedTransactionsForBlock(block.Transactions, height, uow); |
| | | 385 | | |
| | | 386 | | // Update blockchain state |
| | 764 | 387 | | _blockchainState.UpdateState(blockHash.ToBytes(), height); |
| | 764 | 388 | | uow.BlockchainStateDbRepository.Update(_blockchainState); |
| | | 389 | | |
| | 764 | 390 | | _blocksToProcess.Remove(height); |
| | | 391 | | |
| | | 392 | | // Update our internal state |
| | 764 | 393 | | _lastProcessedBlockHeight = height; |
| | | 394 | | |
| | | 395 | | // Check watched for all transactions' depth |
| | 764 | 396 | | CheckWatchedTransactionsDepth(uow); |
| | 764 | 397 | | } |
| | 0 | 398 | | catch (Exception ex) |
| | | 399 | | { |
| | 0 | 400 | | _logger.LogError(ex, "Error processing block at height {Height}", height); |
| | 0 | 401 | | } |
| | 764 | 402 | | } |
| | | 403 | | |
| | | 404 | | private void ConfirmTransaction(uint blockHeight, IUnitOfWork uow, WatchedTransactionModel watchedTransaction) |
| | | 405 | | { |
| | 4 | 406 | | _logger.LogInformation( |
| | 4 | 407 | | "Transaction {TxId} reached required depth of {depth} confirmations at block {blockHeight}", |
| | 4 | 408 | | watchedTransaction.TransactionId, watchedTransaction.RequiredDepth, blockHeight); |
| | | 409 | | |
| | 4 | 410 | | watchedTransaction.MarkAsCompleted(); |
| | 4 | 411 | | uow.WatchedTransactionDbRepository.Update(watchedTransaction); |
| | 4 | 412 | | OnTransactionConfirmed?.Invoke( |
| | 4 | 413 | | this, new TransactionConfirmedEventArgs(watchedTransaction, blockHeight)); |
| | | 414 | | |
| | 4 | 415 | | _watchedTransactions.TryRemove(new uint256(watchedTransaction.TransactionId), out _); |
| | 4 | 416 | | } |
| | | 417 | | |
| | | 418 | | private void CheckWatchedTransactionsForBlock(List<Transaction> blockTransactions, uint blockHeight, |
| | | 419 | | IUnitOfWork uow) |
| | | 420 | | { |
| | 768 | 421 | | _logger.LogDebug( |
| | 768 | 422 | | "Checking {watchedTransactionCount} watched transactions for block {height} with {TxCount} transactions", |
| | 768 | 423 | | _watchedTransactions.Count, blockHeight, blockTransactions.Count); |
| | | 424 | | |
| | 768 | 425 | | ushort index = 0; |
| | 1544 | 426 | | foreach (var transaction in blockTransactions) |
| | | 427 | | { |
| | 4 | 428 | | var txId = transaction.GetHash(); |
| | | 429 | | |
| | 4 | 430 | | if (!_watchedTransactions.TryGetValue(txId, out var watchedTransaction)) |
| | | 431 | | continue; |
| | | 432 | | |
| | 4 | 433 | | _logger.LogInformation("Transaction {TxId} found in block at height {Height}", txId, blockHeight); |
| | | 434 | | |
| | | 435 | | try |
| | | 436 | | { |
| | | 437 | | // Update first seen height |
| | 4 | 438 | | watchedTransaction.SetHeightAndIndex(blockHeight, index); |
| | 4 | 439 | | uow.WatchedTransactionDbRepository.Update(watchedTransaction); |
| | | 440 | | |
| | 4 | 441 | | if (watchedTransaction.RequiredDepth == 0) |
| | 0 | 442 | | ConfirmTransaction(blockHeight, uow, watchedTransaction); |
| | 4 | 443 | | } |
| | 0 | 444 | | catch (Exception ex) |
| | | 445 | | { |
| | 0 | 446 | | _logger.LogError(ex, "Error checking confirmations for transaction {TxId}", txId); |
| | 0 | 447 | | } |
| | | 448 | | finally |
| | | 449 | | { |
| | 4 | 450 | | index++; |
| | 4 | 451 | | } |
| | | 452 | | } |
| | 768 | 453 | | } |
| | | 454 | | |
| | | 455 | | private void CheckWatchedTransactionsDepth(IUnitOfWork uow) |
| | | 456 | | { |
| | 1624 | 457 | | foreach (var (txId, watchedTransaction) in _watchedTransactions) |
| | | 458 | | { |
| | | 459 | | try |
| | | 460 | | { |
| | 44 | 461 | | var confirmations = _lastProcessedBlockHeight - watchedTransaction.FirstSeenAtHeight; |
| | 44 | 462 | | if (confirmations >= watchedTransaction.RequiredDepth) |
| | 4 | 463 | | ConfirmTransaction(_lastProcessedBlockHeight, uow, watchedTransaction); |
| | 44 | 464 | | } |
| | 0 | 465 | | catch (Exception ex) |
| | | 466 | | { |
| | 0 | 467 | | _logger.LogError(ex, "Error checking confirmations for transaction {TxId}", txId); |
| | 0 | 468 | | } |
| | | 469 | | } |
| | 768 | 470 | | } |
| | | 471 | | |
| | | 472 | | private async Task LoadPendingWatchedTransactionsAsync(IUnitOfWork uow) |
| | | 473 | | { |
| | 32 | 474 | | _logger.LogInformation("Loading watched transactions from database"); |
| | | 475 | | |
| | 32 | 476 | | var watchedTransactions = await uow.WatchedTransactionDbRepository.GetAllPendingAsync(); |
| | 72 | 477 | | foreach (var watchedTransaction in watchedTransactions) |
| | | 478 | | { |
| | 4 | 479 | | _watchedTransactions[new uint256(watchedTransaction.TransactionId)] = watchedTransaction; |
| | | 480 | | } |
| | 32 | 481 | | } |
| | | 482 | | } |