blvm-node 0.1.2

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
//! Write-Ahead Log (WAL) for batched database writes during IBD
//!
//! This module provides a WAL-based write buffer that dramatically improves
//! IBD performance by batching database operations:
//!
//! - Without WAL: ~2 blocks/sec (individual DB writes per operation)
//! - With WAL: ~50-100 blocks/sec (batch flush every N blocks)
//!
//! ## How it works
//!
//! 1. All write operations are buffered in memory
//! 2. Operations are also written to a WAL file for crash recovery
//! 3. When the buffer reaches a threshold (1000 blocks), it flushes to the database
//! 4. On startup, any uncommitted WAL entries are replayed
//!
//! ## Thread Safety
//!
//! The WAL buffer uses internal locking and is safe for concurrent access.
//! However, for maximum performance during IBD, use a single writer thread.

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use tracing::{debug, info, warn};

use super::database::{Database, Tree};

/// WAL operation types
#[derive(Debug, Clone)]
enum WalOp {
    Put {
        tree: String,
        key: Vec<u8>,
        value: Vec<u8>,
    },
    Delete {
        tree: String,
        key: Vec<u8>,
    },
}

/// Serialization format for WAL entries (simple binary format)
impl WalOp {
    fn serialize(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        match self {
            WalOp::Put { tree, key, value } => {
                buf.push(0x01); // Put marker
                buf.extend_from_slice(&(tree.len() as u32).to_le_bytes());
                buf.extend_from_slice(tree.as_bytes());
                buf.extend_from_slice(&(key.len() as u32).to_le_bytes());
                buf.extend_from_slice(key);
                buf.extend_from_slice(&(value.len() as u32).to_le_bytes());
                buf.extend_from_slice(value);
            }
            WalOp::Delete { tree, key } => {
                buf.push(0x02); // Delete marker
                buf.extend_from_slice(&(tree.len() as u32).to_le_bytes());
                buf.extend_from_slice(tree.as_bytes());
                buf.extend_from_slice(&(key.len() as u32).to_le_bytes());
                buf.extend_from_slice(key);
            }
        }
        buf
    }

    fn deserialize(data: &[u8]) -> Result<(WalOp, usize)> {
        if data.is_empty() {
            anyhow::bail!("Empty WAL entry");
        }

        let mut pos = 0;
        let op_type = data[pos];
        pos += 1;

        // Read tree name
        if pos + 4 > data.len() {
            anyhow::bail!("Truncated WAL entry");
        }
        let tree_len =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
        pos += 4;
        if pos + tree_len > data.len() {
            anyhow::bail!("Truncated WAL entry");
        }
        let tree = String::from_utf8(data[pos..pos + tree_len].to_vec())?;
        pos += tree_len;

        // Read key
        if pos + 4 > data.len() {
            anyhow::bail!("Truncated WAL entry");
        }
        let key_len =
            u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
        pos += 4;
        if pos + key_len > data.len() {
            anyhow::bail!("Truncated WAL entry");
        }
        let key = data[pos..pos + key_len].to_vec();
        pos += key_len;

        match op_type {
            0x01 => {
                // Put - read value
                if pos + 4 > data.len() {
                    anyhow::bail!("Truncated WAL entry");
                }
                let value_len =
                    u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]])
                        as usize;
                pos += 4;
                if pos + value_len > data.len() {
                    anyhow::bail!("Truncated WAL entry");
                }
                let value = data[pos..pos + value_len].to_vec();
                pos += value_len;
                Ok((WalOp::Put { tree, key, value }, pos))
            }
            0x02 => {
                // Delete
                Ok((WalOp::Delete { tree, key }, pos))
            }
            _ => anyhow::bail!("Unknown WAL operation type: {}", op_type),
        }
    }
}

/// Configuration for the WAL buffer
#[derive(Debug, Clone)]
pub struct WalConfig {
    /// Number of blocks to buffer before flushing
    pub flush_interval_blocks: u64,
    /// Maximum operations to buffer before forcing flush
    pub max_buffered_ops: usize,
    /// Whether to sync WAL file after each write (slower but safer)
    pub sync_wal: bool,
}

impl Default for WalConfig {
    fn default() -> Self {
        Self {
            flush_interval_blocks: 1000,
            max_buffered_ops: 100_000,
            sync_wal: false, // Trade some durability for speed during IBD
        }
    }
}

/// Write-buffered database wrapper with WAL support
///
/// Wraps any Database implementation with a write buffer that batches
/// operations and flushes them periodically for better performance.
pub struct WalBufferedDb {
    /// Underlying database
    inner: Arc<dyn Database>,
    /// Path to WAL file
    wal_path: PathBuf,
    /// WAL file handle
    wal_file: Mutex<Option<BufWriter<File>>>,
    /// In-memory write buffer: tree_name -> (key -> value)
    /// None value means delete
    buffer: RwLock<HashMap<String, HashMap<Vec<u8>, Option<Vec<u8>>>>>,
    /// Number of buffered operations
    buffered_ops: Mutex<usize>,
    /// Current block height being processed
    current_height: Mutex<u64>,
    /// Last flushed block height
    last_flush_height: Mutex<u64>,
    /// Configuration
    config: WalConfig,
}

impl WalBufferedDb {
    /// Create a new WAL-buffered database wrapper
    pub fn new(inner: Arc<dyn Database>, wal_dir: &Path, config: WalConfig) -> Result<Self> {
        std::fs::create_dir_all(wal_dir)?;
        let wal_path = wal_dir.join("ibd.wal");

        let db = Self {
            inner,
            wal_path: wal_path.clone(),
            wal_file: Mutex::new(None),
            buffer: RwLock::new(HashMap::new()),
            buffered_ops: Mutex::new(0),
            current_height: Mutex::new(0),
            last_flush_height: Mutex::new(0),
            config,
        };

        // Replay any existing WAL entries (crash recovery)
        if wal_path.exists() {
            info!("Found existing WAL file, replaying...");
            db.replay_wal()?;
        }

        // Open WAL file for writing
        let wal_file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true) // Start fresh after replay
            .open(&wal_path)
            .context("Failed to open WAL file")?;
        *db.wal_file.lock().unwrap() = Some(BufWriter::new(wal_file));

        Ok(db)
    }

    /// Replay WAL file to recover from crash
    fn replay_wal(&self) -> Result<()> {
        let file = File::open(&self.wal_path)?;
        let mut reader = BufReader::new(file);
        let mut data = Vec::new();
        reader.read_to_end(&mut data)?;

        if data.is_empty() {
            return Ok(());
        }

        let mut pos = 0;
        let mut ops_count = 0;

        // Group operations by tree for efficient batch replay
        let mut tree_ops: HashMap<String, Vec<WalOp>> = HashMap::new();

        while pos < data.len() {
            match WalOp::deserialize(&data[pos..]) {
                Ok((op, consumed)) => {
                    let tree_name = match &op {
                        WalOp::Put { tree, .. } => tree.clone(),
                        WalOp::Delete { tree, .. } => tree.clone(),
                    };
                    tree_ops.entry(tree_name).or_default().push(op);
                    pos += consumed;
                    ops_count += 1;
                }
                Err(e) => {
                    warn!("WAL replay stopped at position {} due to: {}", pos, e);
                    break;
                }
            }
        }

        info!(
            "Replaying {} WAL operations across {} trees",
            ops_count,
            tree_ops.len()
        );

        // Apply operations using batch writes for efficiency
        for (tree_name, ops) in tree_ops {
            let tree = self.inner.open_tree(&tree_name)?;
            let mut batch = tree.batch()?;

            for op in ops {
                match op {
                    WalOp::Put { key, value, .. } => batch.put(&key, &value),
                    WalOp::Delete { key, .. } => batch.delete(&key),
                }
            }

            batch.commit()?;
        }

        info!("WAL replay complete");
        Ok(())
    }

    /// Buffer a put operation
    pub fn buffered_put(&self, tree_name: &str, key: &[u8], value: &[u8]) -> Result<()> {
        // Write to WAL first
        let op = WalOp::Put {
            tree: tree_name.to_string(),
            key: key.to_vec(),
            value: value.to_vec(),
        };
        self.write_wal(&op)?;

        // Add to in-memory buffer
        let mut buffer = self.buffer.write().unwrap();
        buffer
            .entry(tree_name.to_string())
            .or_default()
            .insert(key.to_vec(), Some(value.to_vec()));

        *self.buffered_ops.lock().unwrap() += 1;

        // Check if we should flush
        self.maybe_flush()?;

        Ok(())
    }

    /// Buffer a delete operation
    pub fn buffered_delete(&self, tree_name: &str, key: &[u8]) -> Result<()> {
        // Write to WAL first
        let op = WalOp::Delete {
            tree: tree_name.to_string(),
            key: key.to_vec(),
        };
        self.write_wal(&op)?;

        // Add to in-memory buffer (None = delete)
        let mut buffer = self.buffer.write().unwrap();
        buffer
            .entry(tree_name.to_string())
            .or_default()
            .insert(key.to_vec(), None);

        *self.buffered_ops.lock().unwrap() += 1;

        // Check if we should flush
        self.maybe_flush()?;

        Ok(())
    }

    /// Get a value, checking buffer first then underlying DB
    pub fn buffered_get(&self, tree_name: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
        // Check buffer first
        let buffer = self.buffer.read().unwrap();
        if let Some(tree_buffer) = buffer.get(tree_name) {
            if let Some(value_opt) = tree_buffer.get(key) {
                // Found in buffer: Some(value) = exists, None = deleted
                return Ok(value_opt.clone());
            }
        }
        drop(buffer);

        // Not in buffer, check underlying DB
        let tree = self.inner.open_tree(tree_name)?;
        tree.get(key)
    }

    /// Write operation to WAL file
    fn write_wal(&self, op: &WalOp) -> Result<()> {
        let mut wal_file_guard = self.wal_file.lock().unwrap();
        if let Some(ref mut wal_file) = *wal_file_guard {
            let data = op.serialize();
            wal_file.write_all(&data)?;
            if self.config.sync_wal {
                wal_file.flush()?;
            }
        }
        Ok(())
    }

    /// Mark that we've processed a block
    pub fn block_processed(&self, height: u64) -> Result<()> {
        *self.current_height.lock().unwrap() = height;
        self.maybe_flush()
    }

    /// Check if we should flush and do so if needed
    fn maybe_flush(&self) -> Result<()> {
        let current = *self.current_height.lock().unwrap();
        let last_flush = *self.last_flush_height.lock().unwrap();
        let ops = *self.buffered_ops.lock().unwrap();

        let should_flush = (current - last_flush >= self.config.flush_interval_blocks)
            || (ops >= self.config.max_buffered_ops);

        if should_flush {
            self.flush()?;
        }

        Ok(())
    }

    /// Flush all buffered operations to the database
    pub fn flush(&self) -> Result<()> {
        let mut buffer = self.buffer.write().unwrap();
        let ops_count = *self.buffered_ops.lock().unwrap();

        if ops_count == 0 {
            return Ok(());
        }

        let start = std::time::Instant::now();
        debug!("Flushing {} buffered operations to database", ops_count);

        // Flush each tree's operations using batch writes
        for (tree_name, tree_buffer) in buffer.drain() {
            if tree_buffer.is_empty() {
                continue;
            }

            let tree = self.inner.open_tree(&tree_name)?;
            let mut batch = tree.batch()?;

            for (key, value_opt) in tree_buffer {
                match value_opt {
                    Some(value) => batch.put(&key, &value),
                    None => batch.delete(&key),
                }
            }

            batch.commit()?;
        }

        // Flush underlying database
        self.inner.flush()?;

        // Truncate WAL file (all operations now committed)
        {
            let mut wal_file_guard = self.wal_file.lock().unwrap();
            if let Some(ref mut wal_file) = *wal_file_guard {
                wal_file.flush()?;
            }
            // Reopen WAL file truncated
            let new_file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&self.wal_path)?;
            *wal_file_guard = Some(BufWriter::new(new_file));
        }

        // Update state
        *self.buffered_ops.lock().unwrap() = 0;
        *self.last_flush_height.lock().unwrap() = *self.current_height.lock().unwrap();

        let elapsed = start.elapsed();
        info!(
            "Flushed {} operations in {:?} ({:.0} ops/sec)",
            ops_count,
            elapsed,
            ops_count as f64 / elapsed.as_secs_f64()
        );

        Ok(())
    }

    /// Get the underlying database (bypasses buffer - use carefully)
    pub fn inner(&self) -> &Arc<dyn Database> {
        &self.inner
    }

    /// Get current buffer statistics
    pub fn stats(&self) -> (usize, u64, u64) {
        let ops = *self.buffered_ops.lock().unwrap();
        let current = *self.current_height.lock().unwrap();
        let last_flush = *self.last_flush_height.lock().unwrap();
        (ops, current, last_flush)
    }
}

impl Drop for WalBufferedDb {
    fn drop(&mut self) {
        // Ensure all buffered data is flushed on shutdown
        if let Err(e) = self.flush() {
            warn!("Failed to flush WAL buffer on shutdown: {}", e);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    // Mock database for testing
    struct MockDb {
        data: Mutex<HashMap<String, HashMap<Vec<u8>, Vec<u8>>>>,
    }

    impl MockDb {
        fn new() -> Self {
            Self {
                data: Mutex::new(HashMap::new()),
            }
        }
    }

    impl Database for MockDb {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn open_tree(&self, name: &str) -> Result<Box<dyn Tree>> {
            Ok(Box::new(MockTree {
                name: name.to_string(),
                db: Arc::new(Mutex::new(HashMap::new())),
            }))
        }

        fn flush(&self) -> Result<()> {
            Ok(())
        }
    }

    struct MockTree {
        name: String,
        db: Arc<Mutex<HashMap<Vec<u8>, Vec<u8>>>>,
    }

    impl Tree for MockTree {
        fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
            self.db.lock().unwrap().insert(key.to_vec(), value.to_vec());
            Ok(())
        }

        fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
            Ok(self.db.lock().unwrap().get(key).cloned())
        }

        fn remove(&self, key: &[u8]) -> Result<()> {
            self.db.lock().unwrap().remove(key);
            Ok(())
        }

        fn contains_key(&self, key: &[u8]) -> Result<bool> {
            Ok(self.db.lock().unwrap().contains_key(key))
        }

        fn clear(&self) -> Result<()> {
            self.db.lock().unwrap().clear();
            Ok(())
        }

        fn len(&self) -> Result<usize> {
            Ok(self.db.lock().unwrap().len())
        }

        fn iter(&self) -> Box<dyn Iterator<Item = Result<(Vec<u8>, Vec<u8>)>> + '_> {
            Box::new(std::iter::empty())
        }

        fn batch(&self) -> Result<Box<dyn super::super::database::BatchWriter + '_>> {
            Ok(Box::new(MockBatch {
                ops: Vec::new(),
                db: self.db.clone(),
            }))
        }
    }

    struct MockBatch {
        ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
        db: Arc<Mutex<HashMap<Vec<u8>, Vec<u8>>>>,
    }

    impl super::super::database::BatchWriter for MockBatch {
        fn put(&mut self, key: &[u8], value: &[u8]) {
            self.ops.push((key.to_vec(), Some(value.to_vec())));
        }

        fn delete(&mut self, key: &[u8]) {
            self.ops.push((key.to_vec(), None));
        }

        fn commit(self: Box<Self>) -> Result<()> {
            let mut db = self.db.lock().unwrap();
            for (key, value) in self.ops {
                match value {
                    Some(v) => db.insert(key, v),
                    None => db.remove(&key),
                };
            }
            Ok(())
        }

        fn len(&self) -> usize {
            self.ops.len()
        }
    }

    #[test]
    fn test_wal_basic_operations() {
        let dir = tempdir().unwrap();
        let mock_db = Arc::new(MockDb::new());
        let config = WalConfig {
            flush_interval_blocks: 10,
            max_buffered_ops: 100,
            sync_wal: false,
        };

        let wal_db = WalBufferedDb::new(mock_db, dir.path(), config).unwrap();

        // Buffer some operations
        wal_db.buffered_put("test", b"key1", b"value1").unwrap();
        wal_db.buffered_put("test", b"key2", b"value2").unwrap();

        // Should be able to read from buffer
        assert_eq!(
            wal_db.buffered_get("test", b"key1").unwrap(),
            Some(b"value1".to_vec())
        );

        // Flush and verify stats reset
        wal_db.flush().unwrap();
        let (ops, _, _) = wal_db.stats();
        assert_eq!(ops, 0);
    }

    #[test]
    fn test_wal_serialization() {
        let op = WalOp::Put {
            tree: "test".to_string(),
            key: vec![1, 2, 3],
            value: vec![4, 5, 6],
        };

        let serialized = op.serialize();
        let (deserialized, _) = WalOp::deserialize(&serialized).unwrap();

        match deserialized {
            WalOp::Put { tree, key, value } => {
                assert_eq!(tree, "test");
                assert_eq!(key, vec![1, 2, 3]);
                assert_eq!(value, vec![4, 5, 6]);
            }
            _ => panic!("Wrong operation type"),
        }
    }
}