blvm-node 0.1.48

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
//! Blockchain RPC methods with seeded chain storage.

use blvm_node::rpc::blockchain::BlockchainRpc;
use blvm_node::storage::Storage;
use blvm_protocol::BitcoinProtocolEngine;
use blvm_protocol::ProtocolVersion;
use std::sync::Arc;
use tempfile::TempDir;

mod common;
use common::{DIFFICULTY_INTERVAL, setup_mining_chain};

/// Block hash as stored in `BlockStore` (80-byte wire header), not bincode.
fn wire_block_hash(header: &blvm_node::BlockHeader) -> blvm_node::Hash {
    let mut header_data = [0u8; 80];
    header_data[0..4].copy_from_slice(&(header.version as i32).to_le_bytes());
    header_data[4..36].copy_from_slice(&header.prev_block_hash);
    header_data[36..68].copy_from_slice(&header.merkle_root);
    header_data[68..72].copy_from_slice(&(header.timestamp as u32).to_le_bytes());
    header_data[72..76].copy_from_slice(&(header.bits as u32).to_le_bytes());
    header_data[76..80].copy_from_slice(&(header.nonce as u32).to_le_bytes());
    blvm_node::storage::hashing::double_sha256(&header_data)
}

fn rpc_with_chain() -> (TempDir, Arc<Storage>, BlockchainRpc) {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path()).unwrap());
    setup_mining_chain(&storage, DIFFICULTY_INTERVAL).unwrap();
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage.clone(), protocol);
    (temp_dir, storage, rpc)
}

#[tokio::test]
async fn test_get_block_count_and_best_hash_with_chain() {
    let (_dir, storage, rpc) = rpc_with_chain();
    let count = rpc.get_block_count().await.unwrap();
    assert_eq!(count.as_u64().unwrap(), DIFFICULTY_INTERVAL - 1);

    let best = rpc
        .get_best_block_hash()
        .await
        .unwrap()
        .as_str()
        .unwrap()
        .to_string();
    let tip = storage.chain().get_tip_hash().unwrap().expect("tip");
    assert_eq!(best, blvm_node::storage::hashing::hash_to_rpc_hex(&tip));
}

#[tokio::test]
async fn test_get_block_hash_by_height() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let hash = rpc.get_block_hash(0).await.unwrap();
    assert!(hash.as_str().unwrap().len() >= 64);
    let hash_tip = rpc.get_block_hash(DIFFICULTY_INTERVAL - 1).await.unwrap();
    assert!(hash_tip.as_str().unwrap().len() >= 64);
}

#[tokio::test]
async fn test_get_difficulty_and_chain_tips() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let diff = rpc.get_difficulty().await.unwrap();
    assert!(diff.as_f64().unwrap_or(0.0) > 0.0);

    let tips = rpc.get_chain_tips().await.unwrap();
    assert!(tips.is_array());
    assert!(!tips.as_array().unwrap().is_empty());
}

#[tokio::test]
async fn test_get_block_header_verbose_and_non_verbose() {
    let (_dir, storage, rpc) = rpc_with_chain();
    let tip_header = storage
        .chain()
        .get_tip_header()
        .unwrap()
        .expect("tip header");
    let tip = wire_block_hash(&tip_header);
    let hex = blvm_node::storage::hashing::hash_to_rpc_hex(&tip);

    let verbose = rpc.get_block_header(&hex, true).await.unwrap();
    assert!(verbose.get("height").is_some());
    assert!(verbose.get("hash").is_some());

    let raw = rpc.get_block_header(&hex, false).await.unwrap();
    assert!(raw.as_str().is_some());
}

#[tokio::test]
async fn test_get_blockchain_info_fields() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let info = rpc.get_blockchain_info().await.unwrap();
    assert_eq!(info.get("chain").unwrap().as_str().unwrap(), "main");
    assert_eq!(
        info.get("blocks").unwrap().as_u64().unwrap(),
        DIFFICULTY_INTERVAL - 1
    );
    assert!(info.get("bestblockhash").is_some());
    assert!(info.get("difficulty").is_some());
}

#[tokio::test]
async fn test_validate_address_regtest() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let params = serde_json::json!(["bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"]);
    let result = rpc.validate_address(&params).await.unwrap();
    assert_eq!(result.get("isvalid").unwrap().as_bool(), Some(true));
}

#[tokio::test]
async fn test_get_block_by_wire_hash() {
    let (_dir, storage, rpc) = rpc_with_chain();
    let tip_header = storage
        .chain()
        .get_tip_header()
        .unwrap()
        .expect("tip header");
    let tip = wire_block_hash(&tip_header);
    let hex = blvm_node::storage::hashing::hash_to_rpc_hex(&tip);
    let block = rpc.get_block(&hex).await.unwrap();
    assert!(block.get("hash").is_some() || block.get("hex").is_some());
}

#[tokio::test]
async fn test_get_chain_tx_stats_with_chain() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let stats = rpc
        .get_chain_tx_stats(&serde_json::json!([10]))
        .await
        .unwrap();
    assert!(stats.get("window_block_count").is_some());
    assert!(stats.get("txcount").is_some());
}

#[tokio::test]
async fn test_verify_chain_reports_missing_witnesses() {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path()).unwrap());
    let block = blvm_node::Block {
        header: blvm_protocol::BlockHeader {
            version: 1,
            prev_block_hash: [0u8; 32],
            merkle_root: [0u8; 32],
            timestamp: 1_231_006_505,
            bits: 0x0f00ffff,
            nonce: 1,
        },
        transactions: vec![].into_boxed_slice(),
    };
    let hash = storage.blocks().get_block_hash(&block);
    storage.blocks().store_block(&block).unwrap();
    storage.blocks().store_height(0, &hash).unwrap();
    storage.chain().initialize(&block.header).unwrap();

    let block1 = blvm_node::Block {
        header: blvm_protocol::BlockHeader {
            version: 1,
            prev_block_hash: hash,
            merkle_root: [1u8; 32],
            timestamp: 1_231_006_605,
            bits: 0x0f00ffff,
            nonce: 2,
        },
        transactions: vec![].into_boxed_slice(),
    };
    let hash1 = storage.blocks().get_block_hash(&block1);
    storage.blocks().store_block(&block1).unwrap();
    storage.blocks().store_height(1, &hash1).unwrap();
    storage
        .chain()
        .update_tip(&hash1, &block1.header, 1)
        .unwrap();

    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);
    let result = rpc.verify_chain(Some(1), Some(1)).await.unwrap();
    assert_eq!(result.get("valid").and_then(|v| v.as_bool()), Some(false));
    let errors = result.get("errors").unwrap().as_array().unwrap();
    assert!(
        errors
            .iter()
            .any(|e| { e.as_str().is_some_and(|s| s.contains("witness load error")) }),
        "expected witness load error, got {errors:?}"
    );
}

#[tokio::test]
async fn test_verify_chain_smoke() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let ok = rpc.verify_chain(Some(1), Some(32)).await.unwrap();
    assert!(ok.is_boolean() || ok.get("valid").is_some());
}

#[tokio::test]
async fn test_get_prune_info_smoke() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let info = rpc.get_prune_info(&serde_json::json!([])).await.unwrap();
    assert!(info.get("pruning_enabled").is_some());
}

#[tokio::test]
async fn test_get_txoutset_info_with_chain() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let info = rpc.get_txoutset_info().await.unwrap();
    assert!(info.get("height").is_some());
    assert!(info.get("txouts").is_some());
}

#[tokio::test]
async fn test_get_blockchain_state_with_chain() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let state = rpc.get_blockchain_state().await.unwrap();
    assert!(state.get("bestblockhash").is_some());
    assert!(state.get("difficulty").is_some());
    assert_eq!(state.get("chain").unwrap().as_str().unwrap(), "regtest");
}

#[tokio::test]
async fn test_get_index_info_with_chain() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let info = rpc.get_index_info(&serde_json::json!([])).await.unwrap();
    assert!(info.get("txindex").is_some());
}

fn seed_wire_block(storage: &Storage) -> blvm_node::Hash {
    let block = blvm_node::Block {
        header: blvm_protocol::BlockHeader {
            version: 1,
            prev_block_hash: [0u8; 32],
            merkle_root: [0u8; 32],
            timestamp: 1_231_006_505,
            bits: 0x0f00ffff,
            nonce: 1,
        },
        transactions: vec![].into_boxed_slice(),
    };
    let hash = storage.blocks().get_block_hash(&block);
    storage.blocks().store_block(&block).unwrap();
    storage.blocks().store_height(0, &hash).unwrap();
    hash
}

#[tokio::test]
async fn test_get_block_stats_by_height() {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path()).unwrap());
    seed_wire_block(&storage);
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);
    let stats = rpc.get_block_stats(&serde_json::json!([0])).await.unwrap();
    assert!(stats.get("height").is_some());
    assert!(stats.get("txs").is_some());
}

fn rpc_with_address_index() -> (TempDir, BlockchainRpc, String) {
    use blvm_node::config::IndexingConfig;
    use blvm_node::storage::database::default_backend;

    let temp_dir = TempDir::new().unwrap();
    let mut indexing = IndexingConfig::default();
    indexing.enable_address_index = true;
    let storage = Arc::new(
        Storage::with_backend_pruning_and_indexing(
            temp_dir.path(),
            default_backend(),
            None,
            Some(indexing),
            None,
            None,
            None,
        )
        .unwrap(),
    );
    let tx = common::valid_transaction();
    let script_hex = hex::encode(&tx.outputs[0].script_pubkey);
    use blvm_protocol::block::calculate_tx_id;
    let tx_hash = calculate_tx_id(&tx);
    storage
        .transactions()
        .index_transaction(&tx, &[0xde; 32], 1, 0)
        .unwrap();
    storage
        .utxos()
        .add_utxo(
            &blvm_node::OutPoint {
                hash: tx_hash,
                index: 0,
            },
            &blvm_node::UTXO {
                value: tx.outputs[0].value,
                script_pubkey: tx.outputs[0].script_pubkey.clone().into(),
                height: 1,
                is_coinbase: false,
            },
        )
        .unwrap();
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);
    (temp_dir, rpc, script_hex)
}

#[tokio::test]
async fn test_getaddresstxids_with_indexed_script() {
    let (_dir, rpc, script_hex) = rpc_with_address_index();
    let ids = rpc
        .getaddresstxids(&serde_json::json!([script_hex]))
        .await
        .unwrap();
    let arr = ids.as_array().unwrap();
    assert_eq!(arr.len(), 1);
}

#[tokio::test]
async fn test_getaddressbalance_with_indexed_script() {
    let (_dir, rpc, script_hex) = rpc_with_address_index();
    let balance = rpc
        .getaddressbalance(&serde_json::json!([script_hex]))
        .await
        .unwrap();
    assert!(balance.get("balance").unwrap().as_i64().unwrap() > 0);
}

#[tokio::test]
async fn test_getaddresstxids_with_bech32_address() {
    use blvm_protocol::address::BitcoinAddress;
    use blvm_protocol::{TransactionInput, TransactionOutput};

    let address = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080";
    let decoded = BitcoinAddress::decode(address).expect("regtest bech32 test vector");
    let mut script = vec![0x00];
    script.extend_from_slice(&decoded.witness_program);

    use blvm_node::config::IndexingConfig;
    use blvm_node::storage::database::default_backend;

    let temp_dir = TempDir::new().unwrap();
    let mut indexing = IndexingConfig::default();
    indexing.enable_address_index = true;
    let storage = Arc::new(
        Storage::with_backend_pruning_and_indexing(
            temp_dir.path(),
            default_backend(),
            None,
            Some(indexing),
            None,
            None,
            None,
        )
        .unwrap(),
    );
    let tx = blvm_protocol::Transaction {
        version: 1,
        inputs: blvm_protocol::tx_inputs![TransactionInput {
            prevout: blvm_node::OutPoint {
                hash: [0x11; 32],
                index: 0,
            },
            script_sig: vec![0x51],
            sequence: 0xffffffff,
        }],
        outputs: blvm_protocol::tx_outputs![TransactionOutput {
            value: 50_000,
            script_pubkey: script.clone().into(),
        }],
        lock_time: 0,
    };
    storage
        .transactions()
        .index_transaction(&tx, &[0xee; 32], 1, 0)
        .unwrap();
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);

    let ids = rpc
        .getaddresstxids(&serde_json::json!([address]))
        .await
        .unwrap();
    assert_eq!(ids.as_array().unwrap().len(), 1);
}

#[tokio::test]
async fn test_get_block_filter_for_wire_block() {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path()).unwrap());
    let hash = seed_wire_block(&storage);
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);
    let hash_hex = blvm_node::storage::hashing::hash_to_rpc_hex(&hash);
    let filter = rpc
        .get_block_filter(&serde_json::json!([hash_hex, 0]))
        .await
        .unwrap();
    assert!(filter.get("filter").is_some());
}

#[tokio::test]
async fn test_invalidate_and_reconsider_block_wire_hash() {
    let temp_dir = TempDir::new().unwrap();
    let storage = Arc::new(Storage::new(temp_dir.path()).unwrap());
    let hash = seed_wire_block(&storage);
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage, protocol);
    let hash_hex = blvm_node::storage::hashing::hash_to_rpc_hex(&hash);
    rpc.invalidate_block(&serde_json::json!([hash_hex.clone()]))
        .await
        .unwrap();
    rpc.reconsider_block(&serde_json::json!([hash_hex]))
        .await
        .unwrap();
}

#[tokio::test]
async fn test_get_address_info_with_hex_script() {
    let (_dir, rpc, script_hex) = rpc_with_address_index();
    let info = rpc
        .get_address_info(&serde_json::json!([script_hex]))
        .await
        .unwrap();
    assert_eq!(info.get("tx_count").unwrap().as_u64(), Some(1));
}

fn rpc_with_pruning_chain() -> (TempDir, Arc<Storage>, BlockchainRpc) {
    use blvm_node::config::PruningConfig;
    use blvm_node::storage::database::default_backend;

    let temp_dir = TempDir::new().unwrap();
    let pruning = Some(PruningConfig {
        mode: blvm_node::config::PruningMode::Normal {
            keep_from_height: 0,
            min_recent_blocks: 50,
        },
        auto_prune: true,
        auto_prune_interval: 100,
        min_blocks_to_keep: 50,
        prune_on_startup: false,
        incremental_prune_during_ibd: false,
        prune_window_size: 50,
        min_blocks_for_incremental_prune: 288,
        #[cfg(feature = "utxo-commitments")]
        utxo_commitments: None,
        bip158_filters: None,
    });
    let storage = Arc::new(
        Storage::with_backend_pruning_and_indexing(
            temp_dir.path(),
            default_backend(),
            pruning,
            None,
            None,
            None,
            None,
        )
        .unwrap(),
    );
    setup_mining_chain(&storage, 120).unwrap();
    let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
    let rpc = BlockchainRpc::with_dependencies_and_protocol(storage.clone(), protocol);
    (temp_dir, storage, rpc)
}

#[tokio::test]
async fn test_prune_blockchain_when_enabled() {
    let (_dir, _storage, rpc) = rpc_with_pruning_chain();
    let result = rpc
        .prune_blockchain(&serde_json::json!([20]))
        .await
        .unwrap();
    assert_eq!(result.get("pruned_height").unwrap().as_u64(), Some(20));
}

#[tokio::test]
async fn test_prune_blockchain_without_pruning_errors() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    assert!(
        rpc.prune_blockchain(&serde_json::json!([10]))
            .await
            .is_err()
    );
}

#[tokio::test]
async fn test_load_txoutset_missing_path_errors() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    assert!(rpc.load_txout_set(&serde_json::json!([])).await.is_err());
}

#[tokio::test]
async fn test_verify_chain_default_params() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let ok = rpc.verify_chain(None, None).await.unwrap();
    assert!(ok.is_boolean() || ok.get("valid").is_some());
}

#[tokio::test]
async fn test_get_block_header_at_genesis_height() {
    let (_dir, storage, rpc) = rpc_with_chain();
    let genesis_hash = storage
        .blocks()
        .get_hash_by_height(0)
        .unwrap()
        .expect("genesis");
    let hex = blvm_node::storage::hashing::hash_to_rpc_hex(&genesis_hash);
    let header = rpc.get_block_header(&hex, true).await.unwrap();
    assert_eq!(header.get("height").unwrap().as_u64(), Some(0));
}

#[tokio::test]
async fn test_get_block_stats_bip141_weight() {
    let (_dir, storage, rpc) = rpc_with_chain();
    let genesis_hash = storage
        .blocks()
        .get_hash_by_height(0)
        .unwrap()
        .expect("genesis");
    let block = storage
        .blocks()
        .get_block(&genesis_hash)
        .unwrap()
        .expect("genesis block");
    use blvm_protocol::serialization::transaction::serialize_transaction;
    let stripped_size: usize = block
        .transactions
        .iter()
        .map(|tx| serialize_transaction(tx).len())
        .sum::<usize>()
        + 80;

    let stats = rpc.get_block_stats(&serde_json::json!([0])).await.unwrap();
    let block_size = stats.get("total_size").unwrap().as_u64().unwrap();
    let block_weight = stats.get("total_weight").unwrap().as_u64().unwrap();
    assert_eq!(block_size, stripped_size as u64);
    assert_eq!(block_weight, (3 * stripped_size + stripped_size) as u64);
}

#[tokio::test]
async fn test_getblockstats_totalfee_coinbase_minus_subsidy() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let stats = rpc.get_block_stats(&serde_json::json!([0])).await.unwrap();
    assert_eq!(stats.get("totalfee").unwrap().as_f64(), Some(0.0));
}

#[tokio::test]
async fn test_getchaintxstats_cumulative_txcount() {
    let (_dir, _storage, rpc) = rpc_with_chain();
    let stats = rpc
        .get_chain_tx_stats(&serde_json::json!([5]))
        .await
        .unwrap();
    assert_eq!(stats.get("window_tx_count").unwrap().as_u64(), Some(5));
    assert_eq!(
        stats.get("txcount").unwrap().as_u64(),
        Some(DIFFICULTY_INTERVAL)
    );
}