blvm-protocol 0.1.4

Bitcoin Commons BLVM: Bitcoin protocol abstraction layer for multiple variants and evolution
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
#![cfg(feature = "utxo-commitments")]

//! Unit tests for UTXO commitments (moved from blvm-consensus to avoid a dev-dependency cycle).

mod tests {
    use blvm_consensus::types::{OutPoint, UTXO};
    use blvm_protocol::utxo_commitments::*;

    #[test]
    fn test_utxo_merkle_tree_new() {
        let tree = UtxoMerkleTree::new().unwrap();
        assert_eq!(tree.total_supply(), 0);
        assert_eq!(tree.utxo_count(), 0);
    }

    #[test]
    fn test_insert_utxo() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![0x51].into(), // OP_1
            height: 0,
            is_coinbase: false,
        };

        let root = tree.insert(outpoint.clone(), utxo.clone()).unwrap();
        assert_eq!(tree.utxo_count(), 1);
        assert_eq!(tree.total_supply(), 1000);

        // Root should change after insert
        assert_eq!(tree.root(), root);
    }

    #[test]
    fn test_remove_utxo() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };

        // Insert then remove
        tree.insert(outpoint.clone(), utxo.clone()).unwrap();
        assert_eq!(tree.utxo_count(), 1);

        tree.remove(&outpoint, &utxo).unwrap();
        assert_eq!(tree.utxo_count(), 0);
        assert_eq!(tree.total_supply(), 0);
    }

    #[test]
    fn test_generate_commitment() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![].into(),
            height: 0,
        };

        tree.insert(outpoint, utxo).unwrap();

        let block_hash = [2; 32];
        let commitment = tree.generate_commitment(block_hash, 0);

        assert_eq!(commitment.block_height, 0);
        assert_eq!(commitment.block_hash, block_hash);
        assert_eq!(commitment.total_supply, 1000);
        assert_eq!(commitment.utxo_count, 1);
        assert_eq!(commitment.merkle_root, tree.root());
    }

    #[test]
    fn test_verify_commitment_supply() {
        let mut tree = UtxoMerkleTree::new().unwrap();

        // Add UTXO with value matching genesis block subsidy
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 5000000000, // 50 BTC (genesis subsidy)
            script_pubkey: vec![].into(),
            height: 0,
            is_coinbase: false,
        };

        tree.insert(outpoint, utxo).unwrap();

        let block_hash = [2; 32];
        let commitment = tree.generate_commitment(block_hash, 0);

        // Verify supply matches expected at height 0
        let result = tree.verify_commitment_supply(&commitment);
        assert!(result.is_ok());
    }

    #[test]
    fn test_verify_supply_function() {
        // Test supply verification utility
        let commitment = UtxoCommitment::new(
            [0; 32], 5000000000, // 50 BTC at genesis
            1, 0, [0; 32],
        );

        let result = verify_supply(&commitment);
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_commitment_serialization() {
        let commitment = UtxoCommitment::new([1; 32], 1000, 5, 100, [2; 32]);

        let bytes = commitment.to_bytes();
        assert_eq!(bytes.len(), 84);

        let deserialized = UtxoCommitment::from_bytes(&bytes).unwrap();
        assert_eq!(deserialized.merkle_root, commitment.merkle_root);
        assert_eq!(deserialized.total_supply, commitment.total_supply);
        assert_eq!(deserialized.utxo_count, commitment.utxo_count);
        assert_eq!(deserialized.block_height, commitment.block_height);
        assert_eq!(deserialized.block_hash, commitment.block_hash);
    }

    #[test]
    fn test_generate_proof() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![].into(),
            height: 0,
        };

        tree.insert(outpoint.clone(), utxo).unwrap();

        // Generate proof
        let proof = tree.generate_proof(&outpoint).unwrap();
        // Proof should be generated (verify it's not empty - structure exists)
        // Note: sparse-merkle-tree MerkleProof has internal structure, just verify we got one
        // The proof can be verified against the root separately
        assert!(true); // Proof generated successfully
    }

    #[test]
    fn test_commitment_verify_supply_method() {
        let commitment = UtxoCommitment::new([0; 32], 5000000000, 1, 0, [0; 32]);

        assert!(commitment.verify_supply(5000000000));
        assert!(!commitment.verify_supply(1000));
    }

    #[test]
    fn test_commitment_verify_count() {
        let commitment = UtxoCommitment::new([0; 32], 1000, 5, 0, [0; 32]);

        assert!(commitment.verify_count(5));
        assert!(!commitment.verify_count(10));
    }

    #[test]
    fn test_verifyconsensuscommitment_orange_paper_genesis() {
        use blvm_consensus::constants::{
            GENESIS_BLOCK_HASH, GENESIS_BLOCK_MERKLE_ROOT, GENESIS_BLOCK_NONCE,
            GENESIS_BLOCK_TIMESTAMP,
        };
        use blvm_consensus::types::BlockHeader;
        use blvm_protocol::utxo_commitments::verification::{
            verify_commitment_block_hash, verify_header_chain, verify_supply,
        };

        // Genesis block header (valid PoW)
        let genesis_header = BlockHeader {
            version: 1,
            prev_block_hash: [0; 32],
            merkle_root: GENESIS_BLOCK_MERKLE_ROOT,
            timestamp: GENESIS_BLOCK_TIMESTAMP as u64,
            bits: 0x1d00ffff,
            nonce: GENESIS_BLOCK_NONCE,
        };

        // Valid commitment: genesis hash, correct supply at height 0
        let valid_commitment = UtxoCommitment::new(
            [0; 32],    // merkle_root (not checked in VerifyConsensusCommitment formula)
            5000000000, // 50 BTC = expected supply at height 0
            1,
            0, // block_height
            GENESIS_BLOCK_HASH,
        );

        let result = (verify_supply(&valid_commitment).is_ok()
            && verify_header_chain(&[genesis_header.clone()]).is_ok()
            && verify_commitment_block_hash(&valid_commitment, &genesis_header).is_ok())
            as i64;
        assert_eq!(result, 1, "Valid genesis commitment should return 1");
    }

    #[test]
    fn test_verifyconsensuscommitment_orange_paper_invalid_cases() {
        use blvm_consensus::types::BlockHeader;
        use blvm_protocol::utxo_commitments::verification::{
            verify_commitment_block_hash, verify_header_chain, verify_supply,
        };

        let header = BlockHeader {
            version: 1,
            prev_block_hash: [0; 32],
            merkle_root: [0; 32],
            timestamp: 1231006505,
            bits: 0x1d00ffff,
            nonce: 0,
        };

        // Empty headers -> 0
        let commitment = UtxoCommitment::new([0; 32], 5000000000, 1, 0, [0; 32]);
        assert!(verify_header_chain(&[]).is_err());

        // Wrong supply -> 0
        let bad_supply = UtxoCommitment::new([0; 32], 999, 1, 0, [0; 32]);
        assert!(verify_supply(&bad_supply).is_err());

        // Height out of bounds: commitment says height 5 but we only have 1 header (height 0)
        let height_oob = UtxoCommitment::new([0; 32], 5000000000, 1, 5, [0; 32]);
        assert!(verify_supply(&height_oob).is_ok()); // supply at h=5 is valid
        assert!(verify_commitment_block_hash(&height_oob, &header).is_err()); // block_hash [0;32] != hash(header)
    }

    #[test]
    fn test_verify_utxo_proof_valid() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![0x51], // OP_1
            height: 0,
            is_coinbase: false,
        };

        // Insert UTXO and generate commitment
        tree.insert(outpoint.clone(), utxo.clone()).unwrap();
        let block_hash = [2; 32];
        let commitment = tree.generate_commitment(block_hash, 0);

        // Generate proof
        let proof = tree.generate_proof(&outpoint).unwrap();

        // Verify proof (static function, doesn't need tree instance)
        let is_valid = UtxoMerkleTree::verify_utxo_proof(
            &commitment,
            &outpoint,
            &utxo,
            proof, // Takes ownership
        )
        .unwrap();

        assert!(is_valid, "Valid proof should verify successfully");
    }

    #[test]
    fn test_verify_utxo_proof_wrong_utxo() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo_a = UTXO {
            value: 1000,
            script_pubkey: vec![0x51].into(), // OP_1
            height: 0,
            is_coinbase: false,
        };
        let utxo_b = UTXO {
            value: 2000,                      // Different value
            script_pubkey: vec![0x52].into(), // OP_2
            height: 0,
            is_coinbase: false,
        };

        // Insert UTXO A and generate commitment
        tree.insert(outpoint.clone(), utxo_a.clone()).unwrap();
        let block_hash = [2; 32];
        let commitment = tree.generate_commitment(block_hash, 0);

        // Generate proof for UTXO A
        let proof = tree.generate_proof(&outpoint).unwrap();

        // Try to verify with UTXO B (different UTXO)
        let is_valid = UtxoMerkleTree::verify_utxo_proof(
            &commitment,
            &outpoint,
            &utxo_b, // Wrong UTXO
            proof,
        )
        .unwrap();

        assert!(!is_valid, "Proof with wrong UTXO should fail verification");
    }

    #[test]
    fn test_verify_utxo_proof_wrong_root() {
        let mut tree_a = UtxoMerkleTree::new().unwrap();
        let mut tree_b = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 1000,
            script_pubkey: vec![0x51].into(),
            height: 0,
            is_coinbase: false,
        };

        // Insert into tree A and generate commitment A
        tree_a.insert(outpoint.clone(), utxo.clone()).unwrap();
        let commitment_a = tree_a.generate_commitment([2; 32], 0);

        // Insert different UTXO into tree B and generate commitment B
        let utxo_b = UTXO {
            value: 2000, // Different value
            script_pubkey: vec![0x52].into(),
            height: 0,
            is_coinbase: false,
        };
        tree_b.insert(outpoint.clone(), utxo_b).unwrap();
        let commitment_b = tree_b.generate_commitment([3; 32], 0);

        // Generate proof from tree A
        let proof = tree_a.generate_proof(&outpoint).unwrap();

        // Try to verify against commitment B's root (wrong root)
        let is_valid = UtxoMerkleTree::verify_utxo_proof(
            &commitment_b, // Wrong commitment
            &outpoint,
            &utxo,
            proof,
        )
        .unwrap();

        assert!(!is_valid, "Proof with wrong root should fail verification");
    }

    #[test]
    fn test_verify_utxo_proof_coinbase_utxo() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let utxo = UTXO {
            value: 5000000000, // 50 BTC
            script_pubkey: vec![0x51].into(),
            height: 0,
            is_coinbase: true, // Coinbase UTXO
        };

        tree.insert(outpoint.clone(), utxo.clone()).unwrap();
        let commitment = tree.generate_commitment([2; 32], 0);
        let proof = tree.generate_proof(&outpoint).unwrap();

        let is_valid =
            UtxoMerkleTree::verify_utxo_proof(&commitment, &outpoint, &utxo, proof).unwrap();

        assert!(is_valid, "Coinbase UTXO proof should verify successfully");
    }

    #[test]
    fn test_verify_utxo_proof_multiple_utxos() {
        let mut tree = UtxoMerkleTree::new().unwrap();
        let outpoint1 = OutPoint {
            hash: [1; 32],
            index: 0,
        };
        let outpoint2 = OutPoint {
            hash: [2; 32],
            index: 0,
        };
        let utxo1 = UTXO {
            value: 1000,
            script_pubkey: vec![0x51].into(),
            height: 0,
            is_coinbase: false,
        };
        let utxo2 = UTXO {
            value: 2000,
            script_pubkey: vec![0x52].into(),
            height: 0,
            is_coinbase: false,
        };

        // Insert both UTXOs
        tree.insert(outpoint1.clone(), utxo1.clone()).unwrap();
        tree.insert(outpoint2.clone(), utxo2.clone()).unwrap();
        let commitment = tree.generate_commitment([3; 32], 0);

        // Verify both proofs
        let proof1 = tree.generate_proof(&outpoint1).unwrap();
        let is_valid1 =
            UtxoMerkleTree::verify_utxo_proof(&commitment, &outpoint1, &utxo1, proof1).unwrap();
        assert!(is_valid1, "First UTXO proof should verify");

        let proof2 = tree.generate_proof(&outpoint2).unwrap();
        let is_valid2 =
            UtxoMerkleTree::verify_utxo_proof(&commitment, &outpoint2, &utxo2, proof2).unwrap();
        assert!(is_valid2, "Second UTXO proof should verify");
    }
}