-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathblock_processor.rs
More file actions
623 lines (556 loc) Β· 23.7 KB
/
block_processor.rs
File metadata and controls
623 lines (556 loc) Β· 23.7 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Block processing functionality for the Dash SPV client.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot, Mutex, RwLock};
use crate::error::{Result, SpvError};
use crate::storage::StorageManager;
use crate::types::{AddressBalance, SpvEvent, SpvStats};
use key_wallet_manager::wallet_interface::WalletInterface;
/// Task for the block processing worker.
#[derive(Debug)]
pub enum BlockProcessingTask {
ProcessBlock {
block: dashcore::Block,
response_tx: oneshot::Sender<Result<()>>,
},
ProcessTransaction {
tx: dashcore::Transaction,
response_tx: oneshot::Sender<Result<()>>,
},
ProcessCompactFilter {
filter: dashcore::bip158::BlockFilter,
block_hash: dashcore::BlockHash,
response_tx: oneshot::Sender<Result<bool>>,
},
}
/// Block processing worker that handles blocks in a separate task.
pub struct BlockProcessor<W: WalletInterface, S: StorageManager> {
receiver: mpsc::UnboundedReceiver<BlockProcessingTask>,
wallet: Arc<RwLock<W>>,
storage: Arc<Mutex<S>>,
stats: Arc<RwLock<SpvStats>>,
event_tx: mpsc::UnboundedSender<SpvEvent>,
processed_blocks: HashSet<dashcore::BlockHash>,
failed: bool,
network: dashcore::Network,
}
impl<W: WalletInterface + Send + Sync + 'static, S: StorageManager + Send + Sync + 'static>
BlockProcessor<W, S>
{
/// Create a new block processor.
pub fn new(
receiver: mpsc::UnboundedReceiver<BlockProcessingTask>,
wallet: Arc<RwLock<W>>,
storage: Arc<Mutex<S>>,
stats: Arc<RwLock<SpvStats>>,
event_tx: mpsc::UnboundedSender<SpvEvent>,
network: dashcore::Network,
) -> Self {
Self {
receiver,
wallet,
storage,
stats,
event_tx,
processed_blocks: HashSet::new(),
failed: false,
network,
}
}
/// Run the block processor worker loop.
pub async fn run(mut self) {
tracing::info!("π Block processor worker started");
while let Some(task) = self.receiver.recv().await {
// If we're in failed state, reject all new tasks
if self.failed {
match task {
BlockProcessingTask::ProcessBlock {
response_tx,
block,
} => {
let block_hash = block.block_hash();
tracing::error!(
"β Block processor in failed state, rejecting block {}",
block_hash
);
let _ = response_tx
.send(Err(SpvError::Config("Block processor has failed".to_string())));
}
BlockProcessingTask::ProcessTransaction {
response_tx,
tx,
} => {
let txid = tx.txid();
tracing::error!(
"β Block processor in failed state, rejecting transaction {}",
txid
);
let _ = response_tx
.send(Err(SpvError::Config("Block processor has failed".to_string())));
}
BlockProcessingTask::ProcessCompactFilter {
response_tx,
block_hash,
..
} => {
tracing::error!(
"β Block processor in failed state, rejecting compact filter for block {}",
block_hash
);
let _ = response_tx
.send(Err(SpvError::Config("Block processor has failed".to_string())));
}
}
continue;
}
match task {
BlockProcessingTask::ProcessBlock {
block,
response_tx,
} => {
let block_hash = block.block_hash();
// Check for duplicate blocks
if self.processed_blocks.contains(&block_hash) {
tracing::warn!("β‘ Block {} already processed, skipping", block_hash);
let _ = response_tx.send(Ok(()));
continue;
}
// Process block and handle errors
let result = self.process_block_internal(block).await;
match &result {
Ok(()) => {
// Mark block as successfully processed
self.processed_blocks.insert(block_hash);
// Update blocks processed statistics
{
let mut stats = self.stats.write().await;
stats.blocks_processed += 1;
}
tracing::info!("β
Block {} processed successfully", block_hash);
}
Err(e) => {
// Log error with block hash and enter failed state
tracing::error!(
"β BLOCK PROCESSING FAILED for block {}: {}",
block_hash,
e
);
tracing::error!("β Block processor entering failed state - no more blocks will be processed");
self.failed = true;
}
}
let _ = response_tx.send(result);
}
BlockProcessingTask::ProcessTransaction {
tx,
response_tx,
} => {
let txid = tx.txid();
let result = self.process_transaction_internal(tx).await;
if let Err(e) = &result {
tracing::error!("β TRANSACTION PROCESSING FAILED for tx {}: {}", txid, e);
tracing::error!("β Block processor entering failed state");
self.failed = true;
}
let _ = response_tx.send(result);
}
BlockProcessingTask::ProcessCompactFilter {
filter,
block_hash,
response_tx,
} => {
// Check compact filter with wallet
let mut wallet = self.wallet.write().await;
let matches =
wallet.check_compact_filter(&filter, &block_hash, self.network).await;
drop(wallet);
if matches {
tracing::info!("π― Compact filter matched for block {}", block_hash);
// Emit event if filter matched
let _ = self.event_tx.send(SpvEvent::CompactFilterMatched {
hash: block_hash.to_string(),
});
} else {
tracing::debug!("Compact filter did not match for block {}", block_hash);
}
let _ = response_tx.send(Ok(matches));
}
}
}
tracing::info!("π Block processor worker stopped");
}
/// Process a block internally.
async fn process_block_internal(&mut self, block: dashcore::Block) -> Result<()> {
let block_hash = block.block_hash();
tracing::info!("π¦ Processing downloaded block: {}", block_hash);
// Get block height from storage
let height = {
let storage = self.storage.lock().await;
match storage.get_header_height_by_hash(&block_hash).await {
Ok(Some(h)) => h,
_ => {
tracing::warn!("β οΈ Could not find height for block {}, using 0", block_hash);
0u32
}
}
};
tracing::debug!("Block {} is at height {}", block_hash, height);
// Process block with wallet
let mut wallet = self.wallet.write().await;
let txids = wallet.process_block(&block, height, self.network).await;
if !txids.is_empty() {
tracing::info!(
"π― Wallet found {} relevant transactions in block {} at height {}",
txids.len(),
block_hash,
height
);
}
drop(wallet); // Release lock
// Emit BlockProcessed event with actual relevant transaction count
let _ = self.event_tx.send(SpvEvent::BlockProcessed {
height,
hash: block_hash.to_string(),
transactions_count: block.txdata.len(),
relevant_transactions: txids.len(),
});
// Update chain state if needed
self.update_chain_state_with_block(&block).await?;
Ok(())
}
/// Process a transaction internally.
async fn process_transaction_internal(&mut self, tx: dashcore::Transaction) -> Result<()> {
let txid = tx.txid();
tracing::debug!("Processing mempool transaction: {}", txid);
// Let the wallet process the mempool transaction
let mut wallet = self.wallet.write().await;
wallet.process_mempool_transaction(&tx, self.network).await;
drop(wallet);
// TODO: Check if transaction affects watched addresses/scripts
// TODO: Emit appropriate events if transaction is relevant
Ok(())
}
/* TODO: Re-implement with wallet integration
/// Process transactions in a block to check for matches with watch items.
async fn process_block_transactions(
&mut self,
block: &dashcore::Block,
) -> Result<()> {
let block_hash = block.block_hash();
let mut relevant_transactions = 0;
let mut new_outpoints_to_watch = Vec::new();
let mut balance_changes: HashMap<dashcore::Address, i64> = HashMap::new();
// Get block height from storage
let block_height = {
let storage = self.storage.lock().await;
match storage.get_header_height_by_hash(&block_hash).await {
Ok(Some(h)) => h,
_ => {
tracing::warn!(
"β οΈ Could not find height for block {} in transaction processing, using 0",
block_hash
);
0u32
}
}
};
for (tx_index, transaction) in block.txdata.iter().enumerate() {
let txid = transaction.txid();
let is_coinbase = tx_index == 0;
// Wrap transaction processing in error handling to log failing txid
match self
.process_single_transaction_in_block(
transaction,
tx_index,
watch_items,
&mut balance_changes,
&mut new_outpoints_to_watch,
block_height,
is_coinbase,
)
.await
{
Ok(is_relevant) => {
if is_relevant {
relevant_transactions += 1;
tracing::debug!(
"π Transaction {}: {} (index {}) is relevant",
txid,
if is_coinbase {
"coinbase"
} else {
"regular"
},
tx_index
);
}
}
Err(e) => {
// Log error with both block hash and failing transaction ID
tracing::error!(
"β TRANSACTION PROCESSING FAILED in block {} for tx {} (index {}): {}",
block_hash,
txid,
tx_index,
e
);
return Err(e);
}
}
}
if relevant_transactions > 0 {
tracing::info!(
"π― Block {} contains {} relevant transactions affecting watched items",
block_hash,
relevant_transactions
);
// Update statistics since we found a block with relevant transactions
{
let mut stats = self.stats.write().await;
stats.blocks_with_relevant_transactions += 1;
}
tracing::info!("π¨ BLOCK MATCH DETECTED! Block {} at height {} contains {} transactions affecting watched addresses/scripts",
block_hash, block_height, relevant_transactions);
// Report balance changes
if !balance_changes.is_empty() {
self.report_balance_changes(&balance_changes, block_height).await?;
}
}
// Always emit block processed event (even if no relevant transactions)
let _ = self.event_tx.send(SpvEvent::BlockProcessed {
height: block_height,
hash: block_hash.to_string(),
transactions_count: block.txdata.len(),
relevant_transactions,
});
Ok(())
}
/// Process a single transaction within a block for watch item matches.
/// Returns whether the transaction is relevant to any watch items.
async fn process_single_transaction_in_block(
&mut self,
transaction: &dashcore::Transaction,
_tx_index: usize,
watch_items: &[WatchItem],
balance_changes: &mut HashMap<dashcore::Address, i64>,
new_outpoints_to_watch: &mut Vec<dashcore::OutPoint>,
block_height: u32,
is_coinbase: bool,
) -> Result<bool> {
let txid = transaction.txid();
let mut transaction_relevant = false;
let mut tx_balance_changes: HashMap<dashcore::Address, i64> = HashMap::new();
// Process inputs first (spending UTXOs)
if !is_coinbase {
for (vin, input) in transaction.input.iter().enumerate() {
// Check if this input spends a UTXO from our watched addresses
// Note: WalletInterface doesn't expose UTXO tracking directly
// The wallet will handle this internally in process_block
// Also check against explicitly watched outpoints
for watch_item in watch_items {
if let WatchItem::Outpoint(watched_outpoint) = watch_item {
if &input.previous_output == watched_outpoint {
transaction_relevant = true;
tracing::info!(
"πΈ TX {} input {}:{} spending explicitly watched outpoint {:?}",
txid,
txid,
vin,
watched_outpoint
);
}
}
}
}
}
// Process outputs (creating new UTXOs)
for (vout, output) in transaction.output.iter().enumerate() {
for watch_item in watch_items {
let (matches, matched_address) = match watch_item {
WatchItem::Address {
address,
..
} => (address.script_pubkey() == output.script_pubkey, Some(address.clone())),
WatchItem::Script(script) => (script == &output.script_pubkey, None),
WatchItem::Outpoint(_) => (false, None), // Outpoints don't match outputs
};
if matches {
transaction_relevant = true;
let outpoint = dashcore::OutPoint {
txid,
vout: vout as u32,
};
let amount = dashcore::Amount::from_sat(output.value);
// Create and store UTXO if we have an address
if let Some(address) = matched_address {
let balance_impact = amount.to_sat() as i64;
tracing::info!("π° TX {} output {}:{} to {:?} (value: {}) - Address {} balance impact: +{}",
txid, txid, vout, watch_item, amount, address, balance_impact);
// WalletInterface doesn't have add_utxo method - this will be handled by process_block
// Just track the balance changes
tracing::debug!("π Found UTXO {}:{} for address {}", txid, vout, address);
// Update balance change for this address (add)
*balance_changes.entry(address.clone()).or_insert(0) += balance_impact;
*tx_balance_changes.entry(address.clone()).or_insert(0) += balance_impact;
} else {
tracing::info!("π° TX {} output {}:{} to {:?} (value: {}) - No address to track balance",
txid, txid, vout, watch_item, amount);
}
// Track this outpoint so we can detect when it's spent
new_outpoints_to_watch.push(outpoint);
tracing::debug!(
"π Now watching outpoint {}:{} for future spending",
txid,
vout
);
}
}
}
// Report per-transaction balance changes if this transaction was relevant
if transaction_relevant && !tx_balance_changes.is_empty() {
tracing::info!("π§Ύ Transaction {} balance summary:", txid);
for (address, change_sat) in &tx_balance_changes {
if *change_sat != 0 {
let change_amount = dashcore::Amount::from_sat(change_sat.abs() as u64);
let sign = if *change_sat > 0 {
"+"
} else {
"-"
};
tracing::info!(
" π Address {}: {}{} (net change for this tx)",
address,
sign,
change_amount
);
}
}
}
// Emit transaction event if relevant
if transaction_relevant {
let net_amount: i64 = tx_balance_changes.values().sum();
let affected_addresses: Vec<String> =
tx_balance_changes.keys().map(|addr| addr.to_string()).collect();
let _ = self.event_tx.send(SpvEvent::TransactionDetected {
txid: txid.to_string(),
confirmed: true, // Block transactions are confirmed
block_height: Some(block_height),
amount: net_amount,
addresses: affected_addresses,
});
}
Ok(transaction_relevant)
}
/// Report balance changes for watched addresses.
async fn report_balance_changes(
&self,
balance_changes: &HashMap<dashcore::Address, i64>,
block_height: u32,
) -> Result<()> {
tracing::info!("π° Balance changes detected in block at height {}:", block_height);
for (address, change_sat) in balance_changes {
if *change_sat != 0 {
let change_amount = dashcore::Amount::from_sat(change_sat.abs() as u64);
let sign = if *change_sat > 0 {
"+"
} else {
"-"
};
tracing::info!(
" π Address {}: {}{} (net change for this block)",
address,
sign,
change_amount
);
// Additional context about the change
if *change_sat > 0 {
tracing::info!(
" β¬οΈ Net increase indicates received more than spent in this block"
);
} else {
tracing::info!(
" β¬οΈ Net decrease indicates spent more than received in this block"
);
}
}
}
// Calculate and report current balances for all watched addresses
let watch_items: Vec<_> = self.watch_items.read().await.iter().cloned().collect();
for watch_item in watch_items.iter() {
if let WatchItem::Address {
address,
..
} = watch_item
{
match self.get_address_balance(address).await {
Ok(balance) => {
tracing::info!(
" πΌ Address {} balance: {} (confirmed: {}, unconfirmed: {})",
address,
balance.total(),
balance.confirmed,
balance.unconfirmed
);
}
Err(e) => {
tracing::error!("Failed to get balance for address {}: {}", address, e);
tracing::warn!(
"Continuing balance reporting despite failure for address {}",
address
);
// Continue with other addresses even if this one fails
}
}
}
}
// Emit balance update event
if !balance_changes.is_empty() {
// WalletInterface doesn't expose total balance - skip balance event for now
tracing::debug!("Balance changes detected but WalletInterface doesn't expose balance");
}
Ok(())
}
*/
/// Get the balance for a specific address.
async fn get_address_balance(&self, _address: &dashcore::Address) -> Result<AddressBalance> {
// WalletInterface doesn't expose per-address balance
// Return empty balance for now
Ok(AddressBalance {
confirmed: dashcore::Amount::from_sat(0),
unconfirmed: dashcore::Amount::from_sat(0),
pending: dashcore::Amount::from_sat(0),
pending_instant: dashcore::Amount::from_sat(0),
})
}
/// Update chain state with information from the processed block.
async fn update_chain_state_with_block(&mut self, block: &dashcore::Block) -> Result<()> {
let block_hash = block.block_hash();
// Get the block height from storage
let height = {
let storage = self.storage.lock().await;
match storage.get_header_height_by_hash(&block_hash).await {
Ok(Some(h)) => h,
_ => {
tracing::warn!(
"β οΈ Could not find height for block {} in chain state update, using 0",
block_hash
);
0u32
}
}
};
if height > 0 {
tracing::debug!(
"π Updating chain state with block {} at height {}",
block_hash,
height
);
// Update stats
{
let mut stats = self.stats.write().await;
stats.blocks_requested += 1;
}
}
Ok(())
}
}