blvm-node 0.1.5

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
use blvm_node::storage::blockstore::BlockStore;
use blvm_node::storage::chainstate::ChainState;
use blvm_node::storage::txindex::TxIndex;
use blvm_node::storage::utxostore::UtxoStore;
use blvm_node::Block;
use blvm_node::BlockHeader;
use blvm_node::Hash;
use blvm_node::OutPoint;
use blvm_node::Transaction;
use blvm_node::{ByteString, TransactionInput, TransactionOutput};
use blvm_protocol::ProtocolVersion;
use std::collections::HashMap;
use tempfile::TempDir;

// ============================================================================
// Protocol/consensus fixtures (for mempool, RBF, and other node tests)
// ============================================================================

/// Create a minimal UTXO set (one UTXO) for protocol/mempool tests.
/// Uses blvm_protocol types so it can be shared by mempool_policy_tests, rbf, etc.
pub fn create_protocol_test_utxo_set() -> blvm_protocol::UtxoSet {
    use std::sync::Arc;
    let mut utxo_set = blvm_protocol::UtxoSet::default();
    utxo_set.insert(
        blvm_protocol::OutPoint {
            hash: [1; 32],
            index: 0,
        },
        Arc::new(blvm_protocol::UTXO {
            value: 100_000,
            script_pubkey: vec![0x76, 0xa9, 0x14, 0x00].repeat(20).into(),
            height: 0,
            is_coinbase: false,
        }),
    );
    utxo_set
}

/// Create a test transaction for protocol/mempool tests (configurable value and size).
pub fn create_protocol_test_tx(
    input_value: u64,
    output_value: u64,
    size: usize,
) -> blvm_protocol::Transaction {
    use blvm_protocol::{OutPoint, TransactionInput, TransactionOutput};
    blvm_protocol::Transaction {
        version: 1,
        inputs: blvm_protocol::tx_inputs![TransactionInput {
            prevout: OutPoint {
                hash: [1; 32],
                index: 0,
            },
            script_sig: vec![0; size / 2],
            sequence: 0xffffffff,
        }],
        outputs: blvm_protocol::tx_outputs![TransactionOutput {
            value: output_value as i64,
            script_pubkey: vec![0x76, 0xa9, 0x14].repeat(size / 2).into(),
        }],
        lock_time: 0,
    }
}

pub struct TempDb {
    pub temp_dir: TempDir,
    pub utxo_store: UtxoStore,
    pub tx_index: TxIndex,
    pub block_store: BlockStore,
    pub chain_state: ChainState,
}

impl TempDb {
    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = TempDir::new()?;
        // Use the directory path, not a file path - create_database handles the file creation
        let db_path = temp_dir.path();

        use blvm_node::storage::database::{create_database, default_backend, Database};
        let db_arc: std::sync::Arc<dyn Database> =
            std::sync::Arc::from(create_database(db_path, default_backend(), None)?);
        let utxo_store = UtxoStore::new(db_arc.clone())?;
        let tx_index = TxIndex::new(db_arc.clone())?;
        let block_store = BlockStore::new(db_arc.clone())?;
        let chain_state = ChainState::new(db_arc)?;

        Ok(TempDb {
            temp_dir,
            utxo_store,
            tx_index,
            block_store,
            chain_state,
        })
    }
}

pub struct TestTransactionBuilder {
    version: u64,
    inputs: Vec<TransactionInput>,
    outputs: Vec<TransactionOutput>,
    lock_time: u64,
}

impl Default for TestTransactionBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TestTransactionBuilder {
    pub fn new() -> Self {
        Self {
            version: 1,
            inputs: Vec::new(),
            outputs: Vec::new(),
            lock_time: 0,
        }
    }

    pub fn add_input(mut self, prevout: OutPoint) -> Self {
        self.inputs.push(TransactionInput {
            prevout,
            script_sig: vec![0x51], // OP_1
            sequence: 0xffffffff,
        });
        self
    }

    pub fn add_output(mut self, value: u64, script_pubkey: ByteString) -> Self {
        self.outputs.push(TransactionOutput {
            value: value as i64,
            script_pubkey,
        });
        self
    }

    pub fn with_version(mut self, version: i32) -> Self {
        self.version = version as u64;
        self
    }

    pub fn with_lock_time(mut self, lock_time: u32) -> Self {
        self.lock_time = lock_time as u64;
        self
    }

    pub fn build(self) -> Transaction {
        Transaction {
            version: self.version,
            inputs: self.inputs.into(),
            outputs: self.outputs.into(),
            lock_time: self.lock_time,
        }
    }
}

pub struct TestBlockBuilder {
    header: BlockHeader,
    transactions: Vec<Transaction>,
}

impl Default for TestBlockBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TestBlockBuilder {
    pub fn new() -> Self {
        Self {
            header: BlockHeader {
                version: 1,
                prev_block_hash: Hash::default(),
                merkle_root: Hash::default(),
                timestamp: 0,
                bits: 0x1d00ffff,
                nonce: 0,
            },
            transactions: Vec::new(),
        }
    }

    pub fn set_prev_hash(mut self, hash: Hash) -> Self {
        self.header.prev_block_hash = hash;
        self
    }

    pub fn set_timestamp(mut self, timestamp: u32) -> Self {
        self.header.timestamp = timestamp as u64;
        self
    }

    pub fn with_version(mut self, version: i32) -> Self {
        self.header.version = version as i64;
        self
    }

    pub fn with_bits(mut self, bits: u32) -> Self {
        self.header.bits = bits as u64;
        self
    }

    pub fn with_nonce(mut self, nonce: u32) -> Self {
        self.header.nonce = nonce as u64;
        self
    }

    pub fn add_transaction(mut self, tx: Transaction) -> Self {
        self.transactions.push(tx);
        self
    }

    pub fn add_coinbase_transaction(mut self, script_pubkey: ByteString) -> Self {
        let coinbase_tx = Transaction {
            version: 1,
            inputs: blvm_protocol::tx_inputs![TransactionInput {
                prevout: OutPoint {
                    hash: [0u8; 32],
                    index: 0xffffffff,
                },
                script_sig: vec![0x51], // OP_1
                sequence: 0xffffffff,
            }],
            outputs: blvm_protocol::tx_outputs![TransactionOutput {
                value: 5000000000, // 50 BTC in satoshis
                script_pubkey,
            }],
            lock_time: 0,
        };
        self.transactions.push(coinbase_tx);
        self
    }

    pub fn build(self) -> Block {
        Block {
            header: self.header,
            transactions: self.transactions.into_boxed_slice(),
        }
    }

    pub fn build_header(self) -> BlockHeader {
        self.header
    }
}

pub struct TestUtxoSetBuilder {
    utxos: HashMap<OutPoint, TransactionOutput>,
}

impl Default for TestUtxoSetBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TestUtxoSetBuilder {
    pub fn new() -> Self {
        Self {
            utxos: HashMap::new(),
        }
    }

    pub fn add_utxo(
        mut self,
        hash: Hash,
        index: u32,
        value: u64,
        script_pubkey: ByteString,
    ) -> Self {
        self.utxos.insert(
            OutPoint { hash, index },
            TransactionOutput {
                value: value as i64,
                script_pubkey,
            },
        );
        self
    }

    pub fn build(self) -> HashMap<OutPoint, TransactionOutput> {
        self.utxos
    }
}

pub fn random_hash() -> Hash {
    let mut hash = [0u8; 32];
    for i in 0..32 {
        hash[i] = rand::random::<u8>();
    }
    Hash::from(hash)
}

pub fn random_hash20() -> [u8; 20] {
    let mut hash = [0u8; 20];
    for i in 0..20 {
        hash[i] = rand::random::<u8>();
    }
    hash
}

pub fn p2pkh_script(pubkey_hash: [u8; 20]) -> ByteString {
    let mut script = Vec::new();
    script.push(0x76); // OP_DUP
    script.push(0xa9); // OP_HASH160
    script.push(0x14); // 20 bytes
    script.extend_from_slice(&pubkey_hash);
    script.push(0x88); // OP_EQUALVERIFY
    script.push(0xac); // OP_CHECKSIG
    script
}

pub fn valid_transaction() -> Transaction {
    TestTransactionBuilder::new()
        .add_input(OutPoint {
            hash: random_hash(),
            index: 0,
        })
        .add_output(1000, p2pkh_script(random_hash20()))
        .build()
}

pub fn unique_transaction() -> Transaction {
    TestTransactionBuilder::new()
        .add_input(OutPoint {
            hash: random_hash(),
            index: 0,
        })
        .add_output(1000, p2pkh_script(random_hash20()))
        .build()
}

pub fn valid_block_header() -> BlockHeader {
    BlockHeader {
        version: 1,
        prev_block_hash: random_hash(),
        merkle_root: random_hash(),
        timestamp: 1234567890,
        bits: 0x1d00ffff,
        nonce: 0,
    }
}

pub fn valid_block() -> Block {
    TestBlockBuilder::new()
        .add_transaction(valid_transaction())
        .build()
}

pub fn large_block(transaction_count: usize) -> Block {
    let mut builder = TestBlockBuilder::new();

    // Add coinbase transaction
    builder = builder.add_coinbase_transaction(p2pkh_script(random_hash20()));

    // Add many regular transactions
    for _ in 0..transaction_count {
        let tx = TestTransactionBuilder::new()
            .add_input(OutPoint {
                hash: random_hash(),
                index: 0,
            })
            .add_output(1000, p2pkh_script(random_hash20()))
            .build();
        builder = builder.add_transaction(tx);
    }

    builder.build()
}

pub fn default_protocol_version() -> ProtocolVersion {
    ProtocolVersion::Regtest
}

// ---------------------------------------------------------------------------
// ECDSA helpers for integration tests (blvm-secp256k1 — no rust-secp256k1 crate).
// ---------------------------------------------------------------------------

/// Valid curve scalar **1**, big-endian 32-byte encoding.
#[inline]
pub fn test_secp256k1_scalar_one() -> [u8; 32] {
    let mut k = [0u8; 32];
    k[31] = 1;
    k
}

/// Small distinct test scalar (`n` in 1..=127, stored in the least significant byte).
#[inline]
pub fn test_secp256k1_scalar_small(n: u8) -> [u8; 32] {
    debug_assert!(n >= 1, "use non-zero scalar");
    let mut k = [0u8; 32];
    k[31] = n;
    k
}

/// RFC6979 ECDSA compact signature + compressed pubkey, both hex-encoded.
pub fn ecdsa_compact_sig_hex_and_pubkey_hex(
    seckey32: &[u8; 32],
    msg32: &[u8; 32],
) -> (String, String) {
    use blvm_secp256k1::ecdsa::{ecdsa_sign_compact_rfc6979, ge_to_compressed, pubkey_from_secret};
    use blvm_secp256k1::scalar::Scalar;
    let sig = ecdsa_sign_compact_rfc6979(msg32, seckey32).expect("ECDSA sign (test key)");
    let mut sec = Scalar::zero();
    assert!(
        !sec.set_b32(seckey32) && !sec.is_zero(),
        "invalid test seckey"
    );
    let pk = ge_to_compressed(&pubkey_from_secret(&sec));
    (hex::encode(sig), hex::encode(pk))
}

/// 33-byte compressed pubkey from raw seckey.
pub fn compressed_pubkey33_from_seckey(seckey32: &[u8; 32]) -> [u8; 33] {
    use blvm_secp256k1::ecdsa::{ge_to_compressed, pubkey_from_secret};
    use blvm_secp256k1::scalar::Scalar;
    let mut sec = Scalar::zero();
    assert!(!sec.set_b32(seckey32) && !sec.is_zero());
    ge_to_compressed(&pubkey_from_secret(&sec))
}