blvm-consensus 0.1.55

Bitcoin Commons BLVM: Direct mathematical implementation of Bitcoin consensus rules from the Orange Paper
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
//! Sequence lock calculation functions (BIP68)
//!
//! Implements consensus's sequence lock calculation for relative locktime.
//! Sequence locks are used to enforce relative locktime constraints using
//! transaction input sequence numbers.
//!
//! Reference: consensus `tx_verify.cpp` CalculateSequenceLocks and EvaluateSequenceLocks

use crate::error::Result;
use crate::locktime::{
    extract_sequence_locktime_value, extract_sequence_type_flag, is_sequence_disabled,
};
use crate::types::*;
use blvm_spec_lock::spec_locked;

/// Sequence locktime granularity (for time-based locks)
/// Time-based locks are measured in 512-second intervals (BIP68).
const SEQUENCE_LOCKTIME_GRANULARITY: u32 = 9; // 2^9 = 512 seconds

/// Locktime verify sequence flag (BIP68)
/// Must be set in script verification flags to enforce sequence locks.
pub const LOCKTIME_VERIFY_SEQUENCE: u32 = 0x01;

/// Calculate sequence locks for a transaction (BIP68)
///
/// Computes the minimum block height and time that must be reached
/// before the transaction can be included in a block.
///
/// Matches consensus's CalculateSequenceLocks() exactly.
///
/// # Arguments
/// * `tx` - Transaction to calculate locks for
/// * `flags` - Script verification flags (must include LOCKTIME_VERIFY_SEQUENCE)
/// * `prev_heights` - Block heights at which each input confirmed
/// * `prev_mtps` - Median time of the block before each input's confirmation.
///   Required for a time-based relative lock. `-1` marks an input that is not time-based.
///   `None` is only valid when no input uses a time lock.
///
/// # Returns
/// Pair (min_height, min_time) that must be satisfied:
/// - min_height: Minimum block height (or -1 if no height constraint)
/// - min_time: Minimum block time (or -1 if no time constraint)
#[spec_locked("5.5", "CalculateSequenceLocks")]
#[blvm_spec_lock::axiom(result_0 >= -1)]
#[blvm_spec_lock::axiom(result_1 >= -1)]
#[blvm_spec_lock::ensures(result_0 >= -1)]
#[blvm_spec_lock::ensures(result_1 >= -1)]
pub fn calculate_sequence_locks(
    tx: &Transaction,
    flags: u32,
    prev_heights: &[u64],
    prev_mtps: Option<&[i64]>,
) -> Result<(i64, i64)> {
    // Ensure prev_heights matches input count
    if prev_heights.len() != tx.inputs.len() {
        return Err(crate::error::ConsensusError::ConsensusRuleViolation(
            format!(
                "prev_heights length {} does not match input count {}",
                prev_heights.len(),
                tx.inputs.len()
            )
            .into(),
        ));
    }

    // Initialize to -1 (no constraint)
    let mut min_height: i64 = -1;
    let mut min_time: i64 = -1;

    // BIP68 is only enforced for version 2+ transactions and when flag is set
    let enforce_bip68 = tx.version >= 2 && (flags & LOCKTIME_VERIFY_SEQUENCE) != 0;

    if !enforce_bip68 {
        return Ok((min_height, min_time));
    }

    // Process each input
    for (i, input) in tx.inputs.iter().enumerate() {
        // Check if sequence is disabled (bit 31 set)
        if is_sequence_disabled(input.sequence as u32) {
            // This input doesn't contribute to sequence locks
            continue;
        }

        // Must not use `as i64`: large u64 values wrap to negative i64 and break invariants.
        let coin_height = i64::try_from(prev_heights[i]).map_err(|_| {
            crate::error::ConsensusError::ConsensusRuleViolation(
                "prev_height does not fit in i64 for sequence lock calculation".into(),
            )
        })?;

        // Check locktime type (bit 22)
        if extract_sequence_type_flag(input.sequence as u32) {
            // Time-based relative locktime starts at the median time of the
            // block before the one that confirmed this coin.
            let coin_time = prev_mtps
                .and_then(|mtps| mtps.get(i).copied())
                .filter(|mtp| *mtp >= 0)
                .ok_or_else(|| {
                    crate::error::ConsensusError::ConsensusRuleViolation(
                        "time-based relative lock requires the median time of the prior block"
                            .into(),
                    )
                })?;

            // Extract locktime value and multiply by granularity (512 seconds)
            let locktime_value = extract_sequence_locktime_value(input.sequence as u32) as i64;

            // Runtime assertion: Locktime value must be non-negative
            debug_assert!(
                locktime_value >= 0,
                "Locktime value ({locktime_value}) must be non-negative"
            );

            let locktime_seconds = locktime_value << SEQUENCE_LOCKTIME_GRANULARITY;

            // Runtime assertion: Shift operation must not overflow
            // locktime_value is u16 (max 65535), so locktime_seconds = 65535 * 512 = 33,553,920
            // This fits in i64, so no overflow possible
            debug_assert!(
                locktime_seconds >= 0,
                "Locktime seconds ({locktime_seconds}) must be non-negative (locktime_value: {locktime_value}, granularity: {SEQUENCE_LOCKTIME_GRANULARITY})"
            );

            // Calculate minimum time: coin_time + locktime_seconds - 1
            // The -1 is to maintain nLockTime semantics (last invalid time)
            let required_time = coin_time
                .checked_add(locktime_seconds)
                .and_then(|sum| sum.checked_sub(1))
                .ok_or_else(|| {
                    crate::error::ConsensusError::ConsensusRuleViolation(
                        "Sequence lock time calculation overflow".into(),
                    )
                })?;

            // Runtime assertion: Required time must be >= coin_time (or close to it after -1)
            debug_assert!(
                required_time >= coin_time.saturating_sub(1),
                "Required time ({required_time}) must be >= coin_time - 1 ({coin_time})"
            );

            min_time = min_time.max(required_time);
        } else {
            // Block-based relative locktime
            // Extract locktime value (number of blocks)
            let locktime_value = extract_sequence_locktime_value(input.sequence as u32) as i64;

            // Runtime assertion: Locktime value must be non-negative
            debug_assert!(
                locktime_value >= 0,
                "Locktime value ({locktime_value}) must be non-negative"
            );

            // Calculate minimum height: coin_height + locktime_value - 1
            // The -1 is to maintain nLockTime semantics (last invalid height)
            let required_height = coin_height
                .checked_add(locktime_value)
                .and_then(|sum| sum.checked_sub(1))
                .ok_or_else(|| {
                    crate::error::ConsensusError::ConsensusRuleViolation(
                        "Sequence lock height calculation overflow".into(),
                    )
                })?;

            // Runtime assertion: Required height must be >= coin_height - 1
            debug_assert!(
                required_height >= coin_height.saturating_sub(1),
                "Required height ({required_height}) must be >= coin_height - 1 ({coin_height})"
            );

            min_height = min_height.max(required_height);
        }
    }

    Ok((min_height, min_time))
}

/// Evaluate if sequence locks are satisfied
///
/// Checks if the current block height and time satisfy the sequence lock constraints.
///
/// Matches consensus's EvaluateSequenceLocks() exactly.
///
/// # Arguments
/// * `block_height` - Current block height
/// * `block_time` - Current block's median time-past
/// * `lock_pair` - (min_height, min_time) from calculate_sequence_locks
///
/// # Returns
/// true if locks are satisfied, false otherwise
#[spec_locked("5.5", "EvaluateSequenceLocks")]
pub fn evaluate_sequence_locks(block_height: u64, block_time: u64, lock_pair: (i64, i64)) -> bool {
    let (min_height, min_time) = lock_pair;

    // u64 is always non-negative - no assertion needed

    // Check height constraint
    if min_height >= 0 && block_height <= min_height as u64 {
        // Runtime assertion: Cast must be valid (min_height >= 0)
        debug_assert!(
            min_height >= 0,
            "min_height ({min_height}) must be non-negative for cast to u64"
        );
        return false;
    }

    // Check time constraint
    if min_time >= 0 && block_time <= min_time as u64 {
        // Runtime assertion: Cast must be valid (min_time >= 0)
        debug_assert!(
            min_time >= 0,
            "min_time ({min_time}) must be non-negative for cast to u64"
        );
        return false;
    }

    true
}

/// Check if transaction sequence locks are satisfied
///
/// Convenience function that combines CalculateSequenceLocks and EvaluateSequenceLocks.
///
/// # Arguments
/// * `tx` - Transaction to check
/// * `flags` - Script verification flags
/// * `prev_heights` - Block heights at which each input confirmed
/// * `block_height` - Current block height
/// * `block_time` - Current block's median time-past
/// * `prev_mtps` - Median time of the block before each input's confirmation
///
/// # Returns
/// true if sequence locks are satisfied, false otherwise
pub fn sequence_locks(
    tx: &Transaction,
    flags: u32,
    prev_heights: &[u64],
    block_height: u64,
    block_time: u64,
    prev_mtps: Option<&[i64]>,
) -> Result<bool> {
    let lock_pair = calculate_sequence_locks(tx, flags, prev_heights, prev_mtps)?;
    Ok(evaluate_sequence_locks(block_height, block_time, lock_pair))
}

/// Height-based relative locks only. Time-based inputs are left to the caller.
pub(crate) fn height_relative_lock_unsatisfied(
    tx: &Transaction,
    prev_heights: &[u64],
    block_height: u64,
) -> Result<bool> {
    if prev_heights.len() != tx.inputs.len() {
        return Err(crate::error::ConsensusError::ConsensusRuleViolation(
            format!(
                "prev_heights length {} does not match input count {}",
                prev_heights.len(),
                tx.inputs.len()
            )
            .into(),
        ));
    }
    if tx.version < 2 {
        return Ok(false);
    }
    let mut min_height: i64 = -1;
    for (i, input) in tx.inputs.iter().enumerate() {
        let seq = input.sequence as u32;
        if is_sequence_disabled(seq) || extract_sequence_type_flag(seq) {
            continue;
        }
        let coin_height = i64::try_from(prev_heights[i]).map_err(|_| {
            crate::error::ConsensusError::ConsensusRuleViolation(
                "prev_height does not fit in i64 for sequence lock calculation".into(),
            )
        })?;
        let locktime_value = extract_sequence_locktime_value(seq) as i64;
        let required_height = coin_height
            .checked_add(locktime_value)
            .and_then(|sum| sum.checked_sub(1))
            .ok_or_else(|| {
                crate::error::ConsensusError::ConsensusRuleViolation(
                    "Sequence lock height calculation overflow".into(),
                )
            })?;
        min_height = min_height.max(required_height);
    }
    Ok(!evaluate_sequence_locks(block_height, 0, (min_height, -1)))
}

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

    #[test]
    fn test_calculate_sequence_locks_disabled() {
        let tx = Transaction {
            version: 2,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32],
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0x8000_0000u64, // BIP68 disable flag
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };

        let prev_heights = vec![100];
        let result =
            calculate_sequence_locks(&tx, LOCKTIME_VERIFY_SEQUENCE, &prev_heights, None).unwrap();

        // Disabled sequence should not create locks
        assert_eq!(result, (-1, -1));
    }

    #[test]
    fn test_calculate_sequence_locks_block_based() {
        let tx = Transaction {
            version: 2,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32],
                    index: 0,
                },
                script_sig: vec![],
                sequence: 100, // 100 blocks relative locktime
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };

        let prev_heights = vec![1000]; // Input confirmed at height 1000
        let result =
            calculate_sequence_locks(&tx, LOCKTIME_VERIFY_SEQUENCE, &prev_heights, None).unwrap();

        // Should require height 1000 + 100 - 1 = 1099
        assert_eq!(result.0, 1099);
        assert_eq!(result.1, -1); // No time constraint
    }

    #[test]
    fn high_bit_version_enforces_sequence_locks() {
        fn locks(version: u64) -> (i64, i64) {
            let tx = Transaction {
                version,
                inputs: vec![TransactionInput {
                    prevout: OutPoint {
                        hash: [0; 32],
                        index: 0,
                    },
                    script_sig: vec![],
                    sequence: 100,
                }]
                .into(),
                outputs: vec![].into(),
                lock_time: 0,
            };
            calculate_sequence_locks(&tx, LOCKTIME_VERIFY_SEQUENCE, &[1000], None).unwrap()
        }

        // Wire versions are unsigned. 0xffffffff and 0x80000000 are both >= 2.
        assert_eq!(locks(0xffff_ffff), (1099, -1));
        assert_eq!(locks(0x8000_0000), (1099, -1));
        assert_eq!(locks(2), (1099, -1));
        assert_eq!(locks(1), (-1, -1));
        assert_eq!(locks(0), (-1, -1));
    }

    #[test]
    fn test_prev_height_overflowing_i64_returns_err() {
        let tx = Transaction {
            version: 2,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: [0; 32],
                    index: 0,
                },
                script_sig: vec![],
                sequence: 10,
            }]
            .into(),
            outputs: vec![].into(),
            lock_time: 0,
        };
        let prev_heights = vec![(i64::MAX as u64).saturating_add(1)];
        let err = calculate_sequence_locks(&tx, LOCKTIME_VERIFY_SEQUENCE, &prev_heights, None)
            .unwrap_err();
        assert!(matches!(
            err,
            crate::error::ConsensusError::ConsensusRuleViolation(_)
        ));
    }

    #[test]
    fn test_evaluate_sequence_locks() {
        // Lock requires height 1099
        let lock_pair = (1099, -1);

        // Block height 1100 satisfies the lock
        assert!(evaluate_sequence_locks(1100, 0, lock_pair));

        // Block height 1099 does not satisfy (must be > 1099)
        assert!(!evaluate_sequence_locks(1099, 0, lock_pair));

        // Block height 1098 does not satisfy
        assert!(!evaluate_sequence_locks(1098, 0, lock_pair));
    }
}