blvm-primitives 0.1.2

Bitcoin Commons BLVM: Foundational types, serialization, crypto, and config for consensus and protocol layers
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
//! Bitcoin consensus constants from Orange Paper

/// Maximum money supply: 21,000,000 BTC in satoshis
pub const MAX_MONEY: i64 = 21_000_000 * 100_000_000;

/// Maximum transaction size: 1MB
pub const MAX_TX_SIZE: usize = 1_000_000;

/// Maximum block serialized size in bytes (network rule)
/// This is the maximum size of a block when serialized without witness data
pub const MAX_BLOCK_SERIALIZED_SIZE: usize = 4_000_000;

/// Maximum block weight in weight units (network rule, BIP141)
/// Weight = (stripped_size × 4) + witness_size
/// This is the primary limit for SegWit blocks
pub const MAX_BLOCK_WEIGHT: usize = 4_000_000;

/// Upper bound on the number of transactions in any consensus-valid block.
///
/// Consensus does not fix a tx-count limit; it follows from `MAX_BLOCK_WEIGHT` (BIP141).
/// Mainnet has included blocks with **12k+** transactions (e.g. dense 2015–2016 spam eras);
/// a 10k cap incorrectly rejects valid blocks and panicked in `compute_block_tx_ids`.
///
/// Uses a loose per-tx minimum weight (~60 WU) so `MAX_BLOCK_WEIGHT / 60` safely exceeds
/// any block that could pass weight check (real minimum per tx is higher).
pub const MAX_TRANSACTIONS_PER_BLOCK: usize = MAX_BLOCK_WEIGHT / 60;

/// Maximum block size (deprecated - use MAX_BLOCK_WEIGHT for SegWit blocks)
/// Kept for backward compatibility
#[deprecated(note = "Use MAX_BLOCK_WEIGHT for SegWit blocks")]
pub const MAX_BLOCK_SIZE: usize = MAX_BLOCK_WEIGHT;

/// Maximum number of inputs per transaction
// Note: consensus has no explicit input limit - only bounded by block weight
// Setting to a very high value to match consensus behavior
pub const MAX_INPUTS: usize = 100_000;

/// Maximum number of outputs per transaction
// Note: consensus has no explicit output limit - only bounded by block weight
// Setting to a very high value to match consensus behavior
pub const MAX_OUTPUTS: usize = 100_000;

/// Maximum script length
pub const MAX_SCRIPT_SIZE: usize = 10_000;

/// Maximum stack size during script execution
pub const MAX_STACK_SIZE: usize = 1000;

/// Maximum number of operations in script
pub const MAX_SCRIPT_OPS: usize = 201;

/// Maximum script element size (BIP141: witness elements can be up to 520 bytes)
pub const MAX_SCRIPT_ELEMENT_SIZE: usize = 520;

/// Halving interval: 210,000 blocks
pub const HALVING_INTERVAL: u64 = 210_000;

/// Initial block subsidy: 50 BTC
pub const INITIAL_SUBSIDY: i64 = 50 * 100_000_000;

/// Satoshis per BTC
pub const SATOSHIS_PER_BTC: i64 = 100_000_000;

/// Difficulty adjustment interval: 2016 blocks
pub const DIFFICULTY_ADJUSTMENT_INTERVAL: u64 = 2016;

/// Target time per block: 10 minutes
pub const TARGET_TIME_PER_BLOCK: u64 = 600;

/// Maximum future block time tolerance: 2 hours (7200 seconds)
///
/// Blocks with timestamps more than this far in the future are rejected
/// to prevent time-warp attacks. This allows for reasonable clock skew
/// between network nodes.
pub const MAX_FUTURE_BLOCK_TIME: u64 = 7200;

/// Maximum target (minimum difficulty)
pub const MAX_TARGET: u32 = 0x1d00ffff;

/// Minimum target (maximum difficulty) - Bitcoin's genesis target
pub const MIN_TARGET: [u8; 32] = [
    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

/// Lock time threshold: transactions with lock time < this are block height
pub const LOCKTIME_THRESHOLD: u32 = 500_000_000;

/// Sequence number for final transaction
pub const SEQUENCE_FINAL: u32 = 0xffffffff;

/// Sequence number for RBF
pub const SEQUENCE_RBF: u32 = 0xfffffffe;

/// Minimum relay fee for RBF replacement (BIP125)
///
/// A replacement transaction must pay at least this much more in fees
/// than the transaction it replaces. This prevents spam replacements
/// with minimal fee increases.
pub const MIN_RELAY_FEE: i64 = 1000; // 1000 satoshis

/// Coinbase maturity requirement: 100 blocks
///
/// Coinbase outputs cannot be spent until 100 blocks deep.
/// This prevents miners from spending coinbase immediately and helps
/// secure the network against deep reorgs.
pub const COINBASE_MATURITY: u64 = 100;

/// Maximum block sigop cost (network rule)
///
/// Total sigop cost for a block must not exceed this value.
/// Sigop cost = (legacy sigops × 4) + (P2SH sigops × 4) + witness sigops
///
/// Reference: consensus `consensus.h` MAX_BLOCK_SIGOPS_COST = 80000
pub const MAX_BLOCK_SIGOPS_COST: u64 = 80_000;

/// BIP54: Maximum sigop count per transaction (Consensus Cleanup).
/// Transactions with total sigop count > this are invalid after BIP54 activation.
pub const BIP54_MAX_SIGOPS_PER_TX: u64 = 2500;

/// Witness commitment hash length (BIP141)
///
/// The witness commitment in the coinbase transaction contains:
/// - OP_RETURN (0x6a): 1 byte
/// - Push opcode (0x24): 1 byte
/// - Commitment hash: 32 bytes
///   Total: 34 bytes
///
/// Reference: BIP141 - Witness commitment format
pub const WITNESS_COMMITMENT_HASH_LENGTH: usize = 32;

/// Witness commitment script length (BIP141)
///
/// Total length of witness commitment script:
/// - OP_RETURN (0x6a): 1 byte
/// - Push opcode (0x24): 1 byte  
/// - Commitment hash: 32 bytes
///   Total: 34 bytes
pub const WITNESS_COMMITMENT_SCRIPT_LENGTH: usize = 34;

/// Taproot script length (BIP341)
///
/// Taproot P2TR script format: OP_1 <32-byte-program>
/// - OP_1 (0x51): 1 byte
/// - Push opcode (0x20): 1 byte
/// - Program hash: 32 bytes
///   Total: 34 bytes
pub const TAPROOT_SCRIPT_LENGTH: usize = 34;

/// Taproot program hash length (BIP341)
///
/// Taproot witness program (P2TR) is 32 bytes
pub const TAPROOT_PROGRAM_LENGTH: usize = 32;

/// SegWit witness program lengths (BIP141)
///
/// SegWit v0 programs:
/// - P2WPKH: 20 bytes
/// - P2WSH: 32 bytes
pub const SEGWIT_P2WPKH_LENGTH: usize = 20;
pub const SEGWIT_P2WSH_LENGTH: usize = 32;

// ============================================================================
// BIP ACTIVATION HEIGHTS
// ============================================================================
// Consensus-critical activation heights. Any change to these values would cause
// a chain split. These heights are locked via formal proofs to match consensus.

/// BIP30: Duplicate Coinbase Prevention - Mainnet deactivation height
///
/// BIP30 was disabled after this block to allow duplicate coinbases in blocks 91842 and 91880.
/// Reference: consensus disabled BIP30 after block 91722
pub const BIP30_DEACTIVATION_MAINNET: u64 = 91722;

/// BIP30: Duplicate Coinbase Prevention - Testnet deactivation height
///
/// BIP30 was disabled after this block on testnet.
pub const BIP30_DEACTIVATION_TESTNET: u64 = 0; // BIP30 never enforced on testnet

/// BIP30: Duplicate Coinbase Prevention - Regtest deactivation height
///
/// BIP30 is never enforced on regtest.
pub const BIP30_DEACTIVATION_REGTEST: u64 = 0;

/// BIP16: P2SH (Pay-to-Script-Hash) - Mainnet activation height
///
/// Starting at this block, P2SH scripts are valid.
/// Reference: BIP16, activated April 1, 2012 at block 173,805
pub const BIP16_P2SH_ACTIVATION_MAINNET: u64 = 173_805;

/// BIP16: P2SH (Pay-to-Script-Hash) - Testnet activation height
///
/// Reference: BIP16, always active on testnet
pub const BIP16_P2SH_ACTIVATION_TESTNET: u64 = 0;

/// BIP16: P2SH (Pay-to-Script-Hash) - Regtest activation height
///
/// Reference: BIP16, always active on regtest
pub const BIP16_P2SH_ACTIVATION_REGTEST: u64 = 0;

/// BIP34: Block Height in Coinbase - Mainnet activation height
///
/// Starting at this block, coinbase scriptSig must contain the block height.
/// Reference: Bitcoin Core `consensus.BIP34Height` (`CMainParams` in `kernel/chainparams.cpp`).
pub const BIP34_ACTIVATION_MAINNET: u64 = 227_931;

/// BIP34: Block Height in Coinbase - Testnet activation height
///
/// Reference: Bitcoin Core `consensus.BIP34Height` for `CTestNetParams` (`chainparams.cpp`).
pub const BIP34_ACTIVATION_TESTNET: u64 = 21_111;

/// BIP34: Block Height in Coinbase - Regtest activation height
///
/// Always active on regtest (block 0)
pub const BIP34_ACTIVATION_REGTEST: u64 = 0;

/// BIP66: Strict DER Signatures - Mainnet activation height
///
/// Starting at this block, all signatures must use strict DER encoding.
/// Reference: BIP66, consensus activation at block 363,725
/// Note: The code checks `height < activation_height`, so 363,725 is the first
/// block where BIP66 is enforced.
pub const BIP66_ACTIVATION_MAINNET: u64 = 363_725;

/// BIP66: Strict DER Signatures - Testnet activation height
///
/// Reference: BIP66, consensus activation at block 330,776
pub const BIP66_ACTIVATION_TESTNET: u64 = 330_776;

/// BIP66: Strict DER Signatures - Regtest activation height
///
/// Always active on regtest (block 0)
pub const BIP66_ACTIVATION_REGTEST: u64 = 0;

/// BIP65: OP_CHECKLOCKTIMEVERIFY (CLTV) - Mainnet activation height
///
/// Starting at this block, CLTV opcode is enabled.
/// Reference: BIP65, consensus activation at block 388,381
pub const BIP65_ACTIVATION_MAINNET: u64 = 388_381;

/// BIP65: OP_CHECKLOCKTIMEVERIFY (CLTV) - Testnet activation height
///
/// Reference: Bitcoin Core `consensus.BIP65Height` for `CTestNetParams` (`kernel/chainparams.cpp`).
pub const BIP65_ACTIVATION_TESTNET: u64 = 581_885;

/// BIP112/BIP113: CHECKSEQUENCEVERIFY (CSV) - Mainnet activation height
///
/// `SCRIPT_VERIFY_CHECKSEQUENCEVERIFY` (0x400). **Not** the same as BIP147 (NULLDUMMY).
/// Reference: Bitcoin Core `consensus.nCSVEnabled` = 419328 on mainnet.
pub const BIP112_CSV_ACTIVATION_MAINNET: u64 = 419_328;

/// BIP112/BIP113: CSV - Testnet activation height (Bitcoin Core testnet3)
///
/// Reference: Bitcoin Core `consensus.CSVHeight` for `CTestNetParams` (`kernel/chainparams.cpp`).
/// Testnet CSV activates later than mainnet (770112), unlike some other deployments.
pub const BIP112_CSV_ACTIVATION_TESTNET: u64 = 770_112;

/// BIP112/BIP113: CSV - Regtest (active from genesis for typical regtest chains)
pub const BIP112_CSV_ACTIVATION_REGTEST: u64 = 0;

/// BIP147: NULLDUMMY Enforcement - Mainnet activation height
///
/// Starting at this block, dummy stack elements must be empty (OP_0).
/// Reference: BIP147, consensus activation at block 481,824
pub const BIP147_ACTIVATION_MAINNET: u64 = 481_824;

/// BIP147: NULLDUMMY Enforcement - Testnet activation height
///
/// Reference: BIP147, consensus activation at block 834,624
pub const BIP147_ACTIVATION_TESTNET: u64 = 834_624;

/// SegWit (BIP141) - Mainnet activation height
///
/// Starting at this block, Segregated Witness is active.
/// Reference: BIP141, consensus activation at block 481,824
pub const SEGWIT_ACTIVATION_MAINNET: u64 = 481_824;

/// Taproot (BIP341) - Mainnet activation height
///
/// Starting at this block, Taproot is active.
/// Reference: BIP341, consensus activation at block 709,632
pub const TAPROOT_ACTIVATION_MAINNET: u64 = 709_632;

/// SegWit (BIP141) - Testnet activation height (Bitcoin Core testnet3 `consensus.SegwitHeight`)
///
/// Reference: Bitcoin Core `kernel/chainparams.cpp` (`CTestNetParams`).
/// Same height as BIP147 (NULLDUMMY) on testnet3.
pub const SEGWIT_ACTIVATION_TESTNET: u64 = 834_624;

/// Taproot (BIP341) - Testnet activation height (Bitcoin Core testnet3)
///
/// Reference: Taproot buried height implied by `MinBIP9WarningHeight - 2016` in `CTestNetParams`
/// (`kernel/chainparams.cpp`).
pub const TAPROOT_ACTIVATION_TESTNET: u64 = 2_011_968;

/// CTV (BIP119) - Mainnet activation height
///
/// Starting at this block, OP_CHECKTEMPLATEVERIFY is active.
/// Note: CTV is not yet activated on mainnet. Set to 0 to disable.
/// Reference: BIP119 (proposed soft fork, not yet activated)
pub const CTV_ACTIVATION_MAINNET: u64 = 0;

/// CTV (BIP119) - Testnet activation height
///
/// Note: CTV is not yet activated on testnet. Set to 0 to disable.
pub const CTV_ACTIVATION_TESTNET: u64 = 0;

/// CTV (BIP119) - Regtest activation height
///
/// Always active on regtest (block 0) when feature is enabled.
pub const CTV_ACTIVATION_REGTEST: u64 = 0;

/// CSFS (BIP348) - Mainnet activation height
///
/// Starting at this block, OP_CHECKSIGFROMSTACK is active in Tapscript.
/// Note: CSFS is not yet activated on mainnet. Set to 0 to disable.
/// Reference: BIP348 (proposed soft fork, not yet activated)
pub const CSFS_ACTIVATION_MAINNET: u64 = 0;

/// CSFS (BIP348) - Testnet activation height
///
/// Note: CSFS is not yet activated on testnet. Set to 0 to disable.
pub const CSFS_ACTIVATION_TESTNET: u64 = 0;

/// CSFS (BIP348) - Regtest activation height
///
/// Always active on regtest (block 0) when feature is enabled.
pub const CSFS_ACTIVATION_REGTEST: u64 = 0;

/// BIP54: Consensus Cleanup - Mainnet activation height
///
/// BIP54 specifies "for all blocks **after activation**" the new rules apply. We must not
/// enforce before that height or we would reject valid pre-activation blocks (e.g. coinbase
/// with lock_time=0, 64-byte txs). Signalling/miner compatibility is about *when* activation
/// locks in; the activation height is the first block from which rules apply. Set to the
/// network-agreed height once known (or make configurable so operators can set without a new binary).
pub const BIP54_ACTIVATION_MAINNET: u64 = u64::MAX;

/// BIP54: Consensus Cleanup - Testnet activation height
pub const BIP54_ACTIVATION_TESTNET: u64 = u64::MAX;

/// BIP54: Consensus Cleanup - Regtest activation height
///
/// Set to u64::MAX so regtest matches mainnet/testnet (BIP54 off by default).
/// To test BIP54 on regtest, use a lower activation (e.g. 0) via config or override.
pub const BIP54_ACTIVATION_REGTEST: u64 = u64::MAX;

// ============================================================================
// GENESIS BLOCK CONSTANTS
// ============================================================================
// The genesis block is the foundation of Bitcoin. Any change to these values
// would create a different blockchain. These are locked via formal proofs.

/// Genesis block hash (mainnet)
///
/// The hash of the first Bitcoin block. This is the root of the blockchain.
/// Hash: 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
pub const GENESIS_BLOCK_HASH: [u8; 32] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68, 0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93,
    0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1, 0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f,
];

const fn reverse_hash32(h: [u8; 32]) -> [u8; 32] {
    let mut out = [0u8; 32];
    let mut i = 0usize;
    while i < 32 {
        out[i] = h[31 - i];
        i += 1;
    }
    out
}

/// Genesis block hash in **internal / wire** byte order.
///
/// Bitcoin displays block hashes with the leading zero bytes first ([`GENESIS_BLOCK_HASH`]).
/// P2P messages (`GetHeaders` locators), block header `prev_block_hash`, and typical
/// `double_sha256(header)` output use this reversed layout.
pub const GENESIS_BLOCK_HASH_INTERNAL: [u8; 32] = reverse_hash32(GENESIS_BLOCK_HASH);

/// Genesis block timestamp (Unix timestamp)
///
/// The timestamp of the genesis block: January 3, 2009, 18:15:05 UTC
/// This is the birth of Bitcoin.
pub const GENESIS_BLOCK_TIMESTAMP: u32 = 1231006505;

/// Genesis block merkle root
///
/// The merkle root of the genesis block's coinbase transaction.
/// This is the root of the first transaction tree.
pub const GENESIS_BLOCK_MERKLE_ROOT: [u8; 32] = [
    0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f, 0x61,
    0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a,
];

/// Genesis block nonce
///
/// The nonce used in the genesis block's proof of work.
pub const GENESIS_BLOCK_NONCE: u32 = 2083236893;

// ============================================================================
// Orange Paper Section 4 symbols (C, M_MAX, H, etc.)
// ============================================================================
// Auto-generated from blvm-spec/THE_ORANGE_PAPER.md via cargo spec-lock extract-constants

/// satoshis per BTC (Orange Paper C)
pub const C: u64 = 100_000_000;

/// maximum money supply (Orange Paper M_MAX)
pub const M_MAX: i64 = (21_000_000 * C) as i64;

/// halving interval (Orange Paper H)
pub const H: u64 = 210_000;

/// maximum block weight (Orange Paper W_MAX)
pub const W_MAX: u64 = 4_000_000;

/// maximum sigops per block (Orange Paper S_MAX)
pub const S_MAX: u64 = 80_000;

/// coinbase maturity (Orange Paper R)
pub const R: u64 = 100;

/// maximum script length (Orange Paper L_SCRIPT)
pub const L_SCRIPT: u64 = 10_000;

/// maximum stack size (Orange Paper L_STACK)
pub const L_STACK: u64 = 1_000;

/// maximum operations per script (Orange Paper L_OPS)
pub const L_OPS: u64 = 201;

/// maximum element size (Orange Paper L_ELEMENT)
pub const L_ELEMENT: u64 = 520;

// ============================================================================
// FORMAL VERIFICATION: Orange Paper Constant Locking
// ============================================================================
// These proofs directly verify that constant values match the Orange Paper
// Section 4 (Consensus Constants) specification. This creates a cryptographic
// lock between the Orange Paper (IR) and blvm-consensus implementation.

#[cfg(test)]
mod genesis_hash_byte_order_tests {
    use super::{GENESIS_BLOCK_HASH, GENESIS_BLOCK_HASH_INTERNAL};

    #[test]
    fn genesis_internal_is_reversed_display_form() {
        let mut rev = GENESIS_BLOCK_HASH;
        rev.reverse();
        assert_eq!(rev, GENESIS_BLOCK_HASH_INTERNAL);
    }
}

#[cfg(test)]
mod max_tx_per_block_tests {
    use super::MAX_TRANSACTIONS_PER_BLOCK;

    /// Regression: mainnet includes blocks with 12k+ txs (e.g. 2015–2016 spam waves).
    /// A 10k cap panicked in parallel `compute_block_tx_ids` during IBD.
    #[test]
    fn max_transactions_per_block_covers_observed_mainnet_dense_blocks() {
        assert!(
            MAX_TRANSACTIONS_PER_BLOCK >= 13_000,
            "bound {} too low for known mainnet blocks",
            MAX_TRANSACTIONS_PER_BLOCK
        );
    }
}