blvm-consensus 0.1.10

Bitcoin Commons BLVM: Direct mathematical implementation of Bitcoin consensus rules from the Orange Paper
Documentation
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
//! BIP119: OP_CHECKTEMPLATEVERIFY (CTV)
//!
//! Implementation of BIP119 CheckTemplateVerify opcode for Bitcoin transaction templates.
//!
//! **Feature Flag**: This module is only available when the `ctv` feature is enabled.
//! CTV is a proposed soft fork and should be used with caution until activated on mainnet.
//!
//! Mathematical specifications from Orange Paper Section 5.4.6.
//!
//! ## Overview
//!
//! OP_CHECKTEMPLATEVERIFY (CTV) enables transaction templates that commit to specific
//! transaction structures. This enables:
//! - Congestion control (transaction batching)
//! - Vault contracts (time-locked withdrawals)
//! - Payment channels (state updates)
//! - Advanced smart contracts
//!
//! ## Security Considerations
//!
//! - **Constant-time comparison**: Template hash comparison uses constant-time operations
//!   to prevent timing attacks
//! - **Input validation**: All inputs are validated before processing to prevent
//!   out-of-bounds access and integer overflow
//! - **Cryptographic security**: Uses SHA256 (double-hashed) for template hash calculation
//! - **Feature flag**: CTV is behind a feature flag to prevent accidental use before activation
//!
//! ## Performance Optimizations
//!
//! - **Pre-allocated buffers**: Template preimage buffer is pre-allocated with estimated size
//!   to reduce allocations
//! - **Efficient serialization**: Uses direct byte operations for serialization
//! - **SIMD hash comparison**: Uses SIMD-optimized hash comparison when available (production builds)
//!
//! ## Template Hash Calculation
//!
//! Template hash = SHA256(SHA256(template_preimage))
//!
//! Template preimage includes:
//! - Transaction version (4 bytes, little-endian)
//! - Input count (varint)
//! - For each input: prevout hash, prevout index, sequence (NO scriptSig)
//! - Output count (varint)
//! - For each output: value, script length, script bytes
//! - Locktime (4 bytes, little-endian)
//! - Input index (4 bytes, little-endian) - which input is being verified
//!
//! ## Opcode Behavior
//!
//! OP_CHECKTEMPLATEVERIFY - OP_NOP4 (BIP-119):
//! - Consumes: [template_hash] (32 bytes from stack)
//! - Produces: Nothing (fails if template doesn't match)
//! - Requires: Full transaction context (tx, input_index)
//!
//! ## Usage
//!
//! ```rust,ignore
//! // Enable CTV feature in Cargo.toml:
//! // [features]
//! // ctv = []
//!
//! use blvm_consensus::bip119::calculate_template_hash;
//!
//! let tx = Transaction { /* ... */ };
//! let template_hash = calculate_template_hash(&tx, 0)?;
//! ```

use crate::error::{ConsensusError, Result};
use crate::serialization::varint::encode_varint;
use crate::types::*;
use blvm_spec_lock::spec_locked;
use sha2::{Digest, Sha256};

/// Calculate transaction template hash for BIP119 CTV
///
/// Template hash is SHA256(SHA256(template_preimage)) where template_preimage
/// includes version, inputs, outputs, locktime, and input index.
///
/// Mathematical specification: Orange Paper Section 5.4.6
///
/// **TemplateHash**: 𝒯𝒳 × ℕ → ℍ
///
/// For transaction tx and input index i:
/// - TemplateHash(tx, i) = SHA256(SHA256(TemplatePreimage(tx, i)))
///
/// # Arguments
///
/// * `tx` - The transaction to calculate template hash for
/// * `input_index` - The index of the input being verified (0-based)
///
/// # Returns
///
/// The 32-byte template hash, or an error if calculation fails
///
/// # Errors
///
/// Returns `ConsensusError` if:
/// - Input index is out of bounds
/// - Transaction has no inputs
/// - Transaction has no outputs
/// - Serialization fails
#[spec_locked("5.4.6")]
pub fn calculate_template_hash(tx: &Transaction, input_index: usize) -> Result<Hash> {
    // Validate inputs
    if input_index >= tx.inputs.len() {
        return Err(ConsensusError::TransactionValidation(
            format!(
                "Input index {} out of bounds (transaction has {} inputs)",
                input_index,
                tx.inputs.len()
            )
            .into(),
        ));
    }

    if tx.inputs.is_empty() {
        return Err(ConsensusError::TransactionValidation(
            "Transaction must have at least one input for CTV".into(),
        ));
    }

    if tx.outputs.is_empty() {
        return Err(ConsensusError::TransactionValidation(
            "Transaction must have at least one output for CTV".into(),
        ));
    }

    // Build template preimage with pre-allocated capacity for performance
    // Estimate: 4 (version) + 9 (varint max) + inputs*(32+4+4) + 9 (varint max) + outputs*(8+9+script) + 4 (locktime) + 4 (index)
    let estimated_size = 4
        + 9
        + (tx.inputs.len() * 40)
        + 9
        + (tx
            .outputs
            .iter()
            .map(|o| 8 + 9 + o.script_pubkey.len())
            .sum::<usize>())
        + 4
        + 4;
    let mut preimage = Vec::with_capacity(estimated_size);

    // 1. Transaction version (4 bytes, little-endian)
    preimage.extend_from_slice(&(tx.version as u32).to_le_bytes());

    // 2. Input count (varint)
    preimage.extend_from_slice(&encode_varint(tx.inputs.len() as u64));

    // 3. For each input: prevout hash, prevout index, sequence (NO scriptSig)
    for input in &tx.inputs {
        // Previous output hash (32 bytes)
        preimage.extend_from_slice(&input.prevout.hash);
        // Previous output index (4 bytes, little-endian)
        preimage.extend_from_slice(&input.prevout.index.to_le_bytes());
        // Sequence (4 bytes, little-endian)
        preimage.extend_from_slice(&(input.sequence as u32).to_le_bytes());
        // Note: scriptSig is NOT included in template (key difference from sighash)
    }

    // 4. Output count (varint)
    preimage.extend_from_slice(&encode_varint(tx.outputs.len() as u64));

    // 5. For each output: value, script length, script bytes
    for output in &tx.outputs {
        // Value (8 bytes, little-endian)
        preimage.extend_from_slice(&output.value.to_le_bytes());
        // Script length (varint)
        preimage.extend_from_slice(&encode_varint(output.script_pubkey.len() as u64));
        // Script bytes
        preimage.extend_from_slice(&output.script_pubkey);
    }

    // 6. Locktime (4 bytes, little-endian)
    preimage.extend_from_slice(&(tx.lock_time as u32).to_le_bytes());

    // 7. Input index (4 bytes, little-endian) - which input is being verified
    preimage.extend_from_slice(&(input_index as u32).to_le_bytes());

    // 8. Double SHA256: SHA256(SHA256(preimage))
    // Security: Use SHA256 which is cryptographically secure and constant-time
    let hash1 = Sha256::digest(&preimage);
    let hash2 = Sha256::digest(hash1);

    // Convert to Hash type (32 bytes)
    let mut template_hash = [0u8; 32];
    template_hash.copy_from_slice(&hash2);

    Ok(template_hash)
}

/// Validate template hash for CTV
///
/// Checks if the provided template hash matches the transaction's template hash.
///
/// # Arguments
///
/// * `tx` - The transaction to validate
/// * `input_index` - The index of the input being verified
/// * `expected_hash` - The expected template hash (32 bytes)
///
/// # Returns
///
/// `true` if template hash matches, `false` otherwise
#[spec_locked("5.4.6")]
pub fn validate_template_hash(
    tx: &Transaction,
    input_index: usize,
    expected_hash: &[u8],
) -> Result<bool> {
    // Template hash must be exactly 32 bytes
    if expected_hash.len() != 32 {
        return Ok(false);
    }

    // Calculate actual template hash
    let actual_hash = calculate_template_hash(tx, input_index)?;

    // Compare hashes
    Ok(actual_hash == expected_hash)
}

/// Extract template hash from script
///
/// For CTV scripts, the template hash is typically the last 32 bytes pushed
/// before OP_CHECKTEMPLATEVERIFY (0xb3).
///
/// # Arguments
///
/// * `script` - The script to extract template hash from
///
/// # Returns
///
/// The template hash if found, `None` otherwise
#[spec_locked("5.4.6")]
pub fn extract_template_hash_from_script(script: &[u8]) -> Option<Hash> {
    // Look for OP_CHECKTEMPLATEVERIFY - OP_NOP4
    use crate::opcodes::OP_CHECKTEMPLATEVERIFY;
    if let Some(ctv_pos) = script.iter().rposition(|&b| b == OP_CHECKTEMPLATEVERIFY) {
        // Find the last push operation before CTV
        // Template hash should be pushed as 32 bytes (0x20 push)
        if ctv_pos >= 33 && script[ctv_pos - 33] == 0x20 {
            // Extract 32 bytes before CTV
            let mut hash = [0u8; 32];
            hash.copy_from_slice(&script[ctv_pos - 32..ctv_pos]);
            return Some(hash);
        }
    }
    None
}

/// Check if script uses CTV
///
/// # Arguments
///
/// * `script` - The script to check
///
/// # Returns
///
/// `true` if script contains OP_CHECKTEMPLATEVERIFY (0xba)
#[spec_locked("5.4.6")]
pub fn is_ctv_script(script: &[u8]) -> bool {
    use crate::opcodes::OP_CHECKTEMPLATEVERIFY;
    script.contains(&OP_CHECKTEMPLATEVERIFY) // OP_CHECKTEMPLATEVERIFY (OP_NOP4)
}

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

    #[test]
    fn test_template_hash_basic() {
        // Create a simple transaction
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![0x51], // OP_1 (not included in template)
                sequence: 0xffffffff,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![0x76, 0xa9, 0x14, 0x00, 0x87].into(), // P2PKH
            }]
            .into(),
            lock_time: 0,
        };

        // Calculate template hash
        let hash = calculate_template_hash(&tx, 0).unwrap();

        // Hash should be 32 bytes
        assert_eq!(hash.len(), 32);

        // Hash should be deterministic (same inputs → same output)
        let hash2 = calculate_template_hash(&tx, 0).unwrap();
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_template_hash_determinism() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [1; 32].into(),
                    index: 0,
                },
                script_sig: vec![0x52, 0x53], // Different scriptSig
                sequence: 0,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 5000,
                script_pubkey: vec![0x51].into(), // OP_1
            }]
            .into(),
            lock_time: 100,
        };

        // Calculate hash multiple times
        let hash1 = calculate_template_hash(&tx, 0).unwrap();
        let hash2 = calculate_template_hash(&tx, 0).unwrap();
        let hash3 = calculate_template_hash(&tx, 0).unwrap();

        // All should be identical
        assert_eq!(hash1, hash2);
        assert_eq!(hash2, hash3);
    }

    #[test]
    fn test_template_hash_input_index_dependency() {
        let tx = Transaction {
            version: 1,
            inputs: vec![
                TransactionInput {
                    prevout: OutPoint {
                        hash: [1; 32].into(),
                        index: 0,
                    },
                    script_sig: vec![],
                    sequence: 0,
                },
                TransactionInput {
                    prevout: OutPoint {
                        hash: [2; 32],
                        index: 1,
                    },
                    script_sig: vec![],
                    sequence: 0,
                },
            ]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        // Different input indices should produce different hashes
        let hash0 = calculate_template_hash(&tx, 0).unwrap();
        let hash1 = calculate_template_hash(&tx, 1).unwrap();

        assert_ne!(
            hash0, hash1,
            "Different input indices must produce different template hashes"
        );
    }

    #[test]
    fn test_template_hash_script_sig_not_included() {
        // Create two transactions with different scriptSigs but same structure
        let tx1 = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![0x51], // OP_1
                sequence: 0,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![0x51].into(),
            }]
            .into(),
            lock_time: 0,
        };

        let tx2 = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![0x52, 0x53], // Different scriptSig
                sequence: 0,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![0x51].into(),
            }]
            .into(),
            lock_time: 0,
        };

        // Template hashes should be identical (scriptSig not included)
        let hash1 = calculate_template_hash(&tx1, 0).unwrap();
        let hash2 = calculate_template_hash(&tx2, 0).unwrap();

        assert_eq!(hash1, hash2, "Template hash should not include scriptSig");
    }

    #[test]
    fn test_template_hash_validation() {
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };

        // Calculate correct template hash
        let correct_hash = calculate_template_hash(&tx, 0).unwrap();

        // Validation should pass with correct hash
        assert!(validate_template_hash(&tx, 0, &correct_hash).unwrap());

        // Validation should fail with wrong hash
        let wrong_hash = [1u8; 32];
        assert!(!validate_template_hash(&tx, 0, &wrong_hash).unwrap());

        // Validation should fail with wrong size
        let wrong_size = vec![0u8; 31];
        assert!(!validate_template_hash(&tx, 0, &wrong_size).unwrap());
    }

    #[test]
    fn test_template_hash_error_cases() {
        // Empty inputs
        let tx_no_inputs = Transaction {
            version: 1,
            inputs: vec![].into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };
        assert!(calculate_template_hash(&tx_no_inputs, 0).is_err());

        // Empty outputs
        let tx_no_outputs = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        assert!(calculate_template_hash(&tx_no_outputs, 0).is_err());

        // Input index out of bounds
        let tx = Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32].into(),
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![].into(),
            }]
            .into(),
            lock_time: 0,
        };
        assert!(calculate_template_hash(&tx, 1).is_err()); // Index 1, but only 1 input (index 0)
    }

    #[test]
    fn test_is_ctv_script() {
        // Script with CTV: push 32 bytes (0x20) + 32 bytes of hash + OP_CHECKTEMPLATEVERIFY (0xb3)
        let mut script_with_ctv = vec![0x20]; // OP_PUSHDATA1 with length 32
        script_with_ctv.extend_from_slice(&[0x00; 32]); // 32 bytes of hash
        script_with_ctv.push(0xb3); // OP_CHECKTEMPLATEVERIFY (OP_NOP4)
        assert!(is_ctv_script(&script_with_ctv));

        // Script without CTV
        let script_without_ctv = vec![0x51, 0x87]; // OP_1, OP_EQUAL
        assert!(!is_ctv_script(&script_without_ctv));
    }
}