blvm-consensus 0.1.21

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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! SegWit Integration Tests
//! 
//! Tests for Segregated Witness (BIP141/143) integration with transaction validation,
//! block weight calculation, and witness handling.

use bitcoin_hashes::{sha256d, Hash as BitcoinHash};
use blvm_consensus::*;
use blvm_consensus::segwit::*;
use blvm_consensus::script::verify_script_with_context_full;
use blvm_consensus::constants::MAX_BLOCK_WEIGHT;
use super::bip_test_helpers::*;

/// BIP141 witness commitment output: `OP_RETURN` `0x24` `0xaa21a9ed` || `sha256d(witness_root || nonce)`.
fn create_witness_commitment_script(witness_root: &[u8; 32], nonce: &[u8; 32]) -> Vec<u8> {
    let mut preimage = [0u8; 64];
    preimage[..32].copy_from_slice(witness_root);
    preimage[32..].copy_from_slice(nonce);
    let h = sha256d::Hash::hash(&preimage);
    let mut script = vec![0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];
    script.extend_from_slice(&h[..]);
    script
}

#[test]
fn test_segwit_witness_validation() {
    // Test witness data validation in transaction flow
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00], // SegWit marker (empty scriptSig for SegWit)
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(), // OP_1
        }].into(),
        lock_time: 0,
    };
    
    let witness = vec![vec![0x51]]; // Witness stack: OP_1
    
    let mut utxo_set = UtxoSet::default();
    utxo_set.insert(
        OutPoint { hash: [1; 32], index: 0 },
        std::sync::Arc::new(UTXO {
            value: 1000000,
            script_pubkey: vec![0x51].into(), // P2WPKH scriptPubkey
            height: 0,
        }),
    );
    
    // Validate with witness
    let input = &tx.inputs[0];
    let utxo = utxo_set.get(&input.prevout).unwrap();
    let pv = vec![utxo.value];
    let psp: Vec<&crate::types::ByteString> = vec![&utxo.script_pubkey];

    // Convert witness to ByteString for script validation
    let witness_script = witness[0].clone();

    let result = verify_script_with_context_full(
        &input.script_sig,
        &utxo.script_pubkey,
        Some(&witness_script), // Witness data
        0, // Flags
        &tx,
        0, // Input index
        &pv,
        &psp,
        None, // Block height
        None, // Median time past
        crate::types::Network::Mainnet,
        crate::script::SigVersion::WitnessV0,
        None,
        None,
        None,
        None, // precomputed_bip143
        #[cfg(feature = "production")] None,
    );
    
    assert!(result.is_ok());
}

#[test]
fn test_segwit_transaction_weight() {
    // Test transaction weight calculation with witness
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00], // SegWit marker
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    let witness = vec![vec![0x51; 100]]; // 100-byte witness
    
    let weight = calculate_transaction_weight(&tx, Some(&witness), crate::types::Network::Mainnet).unwrap();
    
    // Weight = 4 * base_size + total_size
    // base_size includes transaction without witness
    // total_size = base_size + witness_size
    assert!(weight > 0);
    assert!(weight > 4 * 100); // Weight should account for witness
}

#[test]
fn test_segwit_block_weight() {
    // Test block weight calculation with SegWit transactions
    let block = Block {
        header: create_test_header(1234567890, [0; 32]),
        transactions: vec![
            Transaction {
                version: 1,
                inputs: vec![].into(),
                outputs: vec![TransactionOutput {
                    value: 5000000000,
                    script_pubkey: vec![].into(),
                }].into(),
                lock_time: 0,
            },
            Transaction {
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [1; 32].into(), index: 0 },
                    script_sig: vec![0x00],
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![0x51].into(),
                }].into(),
                lock_time: 0,
            },
        ],
    };
    
    let witnesses = vec![
        vec![], // Coinbase witness (empty)
        vec![vec![0x51]], // First transaction witness
    ];
    
    let block_weight = calculate_block_weight(&block, &witnesses).unwrap();
    
    assert!(block_weight > 0);
    assert!(block_weight <= MAX_BLOCK_WEIGHT); // Should be within limit
}

#[test]
fn test_segwit_block_weight_boundary() {
    // Test block weight at boundary (exactly at or near 4M weight)
    let mut block = Block {
        header: create_test_header(1234567890, [0; 32]),
            transactions: vec![].into(),
    };
    
    // Create transactions that approach the weight limit
    // This is a simplified test - real boundary testing would need precise weight calculation
    for _ in 0..100 {
        block.transactions.push(Transaction {
            version: 1,
            inputs: vec![TransactionInput {
                prevout: OutPoint { hash: [1; 32].into(), index: 0 },
                script_sig: vec![0x00],
                sequence: 0xffffffff,
            }].into(),
            outputs: vec![TransactionOutput {
                value: 1000,
                script_pubkey: vec![0x51; 100].into(), // Large scriptPubkey
            }].into(),
            lock_time: 0,
        });
    }
    
    let witnesses: Vec<Witness> = (0..block.transactions.len())
        .map(|i| if i == 0 { vec![] } else { vec![vec![0x51; 50]] })
        .collect();
    
    let block_weight = calculate_block_weight(&block, &witnesses).unwrap();
    
    // Block weight should be calculated correctly
    assert!(block_weight > 0);
    // Note: In real testing, we'd verify it's exactly at boundary when appropriate
}

#[test]
fn test_segwit_witness_commitment() {
    // Test witness commitment in coinbase transaction
    let mut coinbase_tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [0; 32].into(), index: 0xffffffff },
            script_sig: vec![0x51],
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 5000000000,
            script_pubkey: vec![].into(),
        }].into(),
        lock_time: 0,
    };
    
    let witness_root = [1u8; 32];
    
    // Add witness commitment to coinbase script
    coinbase_tx.outputs[0].script_pubkey =
        create_witness_commitment_script(&witness_root, &[0u8; 32]);
    
    let is_valid = validate_witness_commitment(&coinbase_tx, &witness_root, &[]).unwrap();
    
    assert!(is_valid);
}

#[test]
fn test_segwit_p2wpkh_validation() {
    // Test P2WPKH (Pay-to-Witness-Public-Key-Hash) validation
    // P2WPKH: scriptPubkey is OP_0 <20-byte-hash>
    let p2wpkh_hash = [0x51; 20]; // 20-byte hash
    let mut script_pubkey = vec![0x00]; // OP_0
    script_pubkey.extend_from_slice(&p2wpkh_hash);
    
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![], // Empty scriptSig for P2WPKH
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    // Witness for P2WPKH: <signature> <pubkey>
    let witness = vec![
        vec![0x51; 72], // Signature (DER-encoded)
        vec![0x51; 33], // Public key (compressed)
    ];
    
    let mut utxo_set = UtxoSet::default();
    utxo_set.insert(
        OutPoint { hash: [1; 32], index: 0 },
        std::sync::Arc::new(UTXO {
            value: 1000000,
            script_pubkey: script_pubkey.clone().into(),
            height: 0,
        }),
    );
    
    // Validate P2WPKH with witness
    let input = &tx.inputs[0];
    let utxo = utxo_set.get(&input.prevout).unwrap();
    let pv = vec![utxo.value];
    let psp: Vec<&crate::types::ByteString> = vec![&utxo.script_pubkey];

    // For P2WPKH, witness replaces scriptSig
    let witness_script = witness.iter().flat_map(|w| w.iter().cloned()).collect::<Vec<u8>>();

    let result = verify_script_with_context_full(
        &input.script_sig,
        &utxo.script_pubkey,
        Some(&witness_script),
        0,
        &tx,
        0,
        &pv,
        &psp,
        None,
        None,
        crate::types::Network::Mainnet,
        crate::script::SigVersion::WitnessV0,
        None,
        None,
        None,
        None, // precomputed_bip143
        #[cfg(feature = "production")] None,
    );
    
    assert!(result.is_ok());
}

#[test]
fn test_segwit_p2wsh_validation() {
    // Test P2WSH (Pay-to-Witness-Script-Hash) validation
    // P2WSH: scriptPubkey is OP_0 <32-byte-hash>
    let p2wsh_hash = [0x51; 32]; // 32-byte hash
    let mut script_pubkey = vec![0x00]; // OP_0
    script_pubkey.extend_from_slice(&p2wsh_hash);
    
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![], // Empty scriptSig for P2WSH
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    // Witness for P2WSH: <stack elements...> <witness script>
    let witness = vec![
        vec![0x51], // Stack element
        vec![0x51; 100], // Witness script
    ];
    
    let mut utxo_set = UtxoSet::default();
    utxo_set.insert(
        OutPoint { hash: [1; 32], index: 0 },
        std::sync::Arc::new(UTXO {
            value: 1000000,
            script_pubkey: script_pubkey.clone().into(),
            height: 0,
        }),
    );
    
    let input = &tx.inputs[0];
    let utxo = utxo_set.get(&input.prevout).unwrap();
    let pv = vec![utxo.value];
    let psp: Vec<&crate::types::ByteString> = vec![&utxo.script_pubkey];

    let witness_script = witness.iter().flat_map(|w| w.iter().cloned()).collect::<Vec<u8>>();

    let result = verify_script_with_context_full(
        &input.script_sig,
        &utxo.script_pubkey,
        Some(&witness_script),
        0,
        &tx,
        0,
        &pv,
        &psp,
        None,
        None,
        crate::types::Network::Mainnet,
        crate::script::SigVersion::WitnessV0,
        None,
        None,
        None,
        None, // precomputed_bip143
        #[cfg(feature = "production")] None,
    );

    assert!(result.is_ok());
}

#[test]
#[cfg(feature = "production")]
fn test_p2wsh_multisig_fast_path() {
    use blvm_consensus::crypto::OptimizedSha256;
    use blvm_consensus::constants::BIP147_ACTIVATION_MAINNET;

    // 2-of-2 multisig witness script: OP_2 <pk1> <pk2> OP_2 OP_CHECKMULTISIG
    let pk1 = [0x02u8; 33];
    let pk2 = [0x03u8; 33];
    let mut witness_script = vec![0x52]; // OP_2
    witness_script.extend_from_slice(&pk1);
    witness_script.extend_from_slice(&pk2);
    witness_script.push(0x52); // OP_2
    witness_script.push(0xae); // OP_CHECKMULTISIG

    let wsh_hash = OptimizedSha256::new().hash(&witness_script);
    let mut script_pubkey = vec![0x00, 0x20];
    script_pubkey.extend_from_slice(&wsh_hash);

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

    let witness: Witness = vec![
        vec![0x00],
        vec![0x30u8; 72],
        vec![0x30u8; 72],
        witness_script.clone(),
    ];

    let mut utxo_set = UtxoSet::default();
    utxo_set.insert(
        OutPoint { hash: [1; 32], index: 0 },
        std::sync::Arc::new(UTXO {
            value: 1000000,
            script_pubkey: script_pubkey.into(),
            height: 0,
        }),
    );

    let input = &tx.inputs[0];
    let utxo = utxo_set.get(&input.prevout).unwrap();
    let pv = vec![utxo.value];
    let psp: Vec<&crate::types::ByteString> = vec![&utxo.script_pubkey];

    let result = verify_script_with_context_full(
        &input.script_sig,
        &utxo.script_pubkey,
        Some(&witness),
        0x810,
        &tx,
        0,
        &pv,
        &psp,
        Some(BIP147_ACTIVATION_MAINNET + 1),
        None,
        crate::types::Network::Mainnet,
        crate::script::SigVersion::Base,
        None,
        None,
        None,
        None,
        #[cfg(feature = "production")] None,
        #[cfg(feature = "production")] None,
        #[cfg(feature = "production")] None,
        #[cfg(feature = "production")] None,
    );

    assert!(result.is_ok());
    assert!(!result.unwrap());
}

#[test]
fn test_segwit_weight_exceeds_limit() {
    // Test that block weight exceeding 4M is detected
    let mut block = Block {
        header: create_test_header(1234567890, [0; 32]),
            transactions: vec![].into(),
    };
    
    // Create a very large transaction with large witness
    // This would normally be validated to ensure it doesn't exceed MAX_BLOCK_WEIGHT
    let large_witness = vec![vec![0x51; 1000000]]; // 1MB witness
    
    block.transactions.push(Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00],
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    });
    
    let witnesses = vec![vec![], large_witness];
    
    let block_weight = calculate_block_weight(&block, &witnesses).unwrap();
    
    // Block weight calculation should work, but validation should reject
    assert!(block_weight > 0);
    
    // Validate block weight limit
    let is_valid = validate_segwit_block(&block, &witnesses, MAX_BLOCK_WEIGHT).unwrap();
    
    // Should fail if weight exceeds limit
    if block_weight > MAX_BLOCK_WEIGHT {
        assert!(!is_valid);
    }
}

#[test]
fn test_segwit_mixed_block() {
    // Test block with both SegWit and non-SegWit transactions
    let block = Block {
        header: create_test_header(1234567890, [0; 32]),
        transactions: vec![
            Transaction {
                version: 1,
                inputs: vec![].into(),
                outputs: vec![TransactionOutput {
                    value: 5000000000,
                    script_pubkey: vec![].into(),
                }].into(),
                lock_time: 0,
            },
            Transaction {
                // SegWit transaction
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [1; 32].into(), index: 0 },
                    script_sig: vec![0x00], // SegWit marker
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![0x51].into(),
                }].into(),
                lock_time: 0,
            },
            Transaction {
                // Non-SegWit transaction
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [2; 32].into(), index: 0 },
                    script_sig: vec![0x51], // Non-empty scriptSig
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![0x51].into(),
                }].into(),
                lock_time: 0,
            },
        ],
    };
    
    let witnesses = vec![
        vec![], // Coinbase
        vec![vec![0x51]], // SegWit transaction witness
        vec![], // Non-SegWit (no witness)
    ];
    
    let block_weight = calculate_block_weight(&block, &witnesses).unwrap();
    
    assert!(block_weight > 0);
}

#[test]
fn test_segwit_witness_merkle_root() {
    // Test witness merkle root calculation
    let block = Block {
        header: create_test_header(1234567890, [0; 32]),
        transactions: vec![
            Transaction {
                version: 1,
                inputs: vec![].into(),
                outputs: vec![TransactionOutput {
                    value: 5000000000,
                    script_pubkey: vec![].into(),
                }].into(),
                lock_time: 0,
            },
            Transaction {
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [1; 32].into(), index: 0 },
                    script_sig: vec![0x00],
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![0x51].into(),
                }].into(),
                lock_time: 0,
            },
        ],
    };
    
    let witnesses = vec![
        vec![], // Coinbase witness (empty)
        vec![vec![0x51]], // First transaction witness
    ];
    
    let witness_root = compute_witness_merkle_root(&block, &witnesses).unwrap();
    
    assert_eq!(witness_root.len(), 32);
}

#[test]
fn test_segwit_witness_merkle_root_empty_block() {
    // Test witness merkle root with empty block (should fail)
    let block = Block {
        header: create_test_header(1234567890, [0; 32]),
            transactions: vec![].into(),
    };
    
    let witnesses = vec![];
    
    let result = compute_witness_merkle_root(&block, &witnesses);
    
    assert!(result.is_err());
}

#[test]
fn test_segwit_no_witness_weight() {
    // Test transaction weight without witness (should equal legacy weight)
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x51],
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    let weight_no_witness = calculate_transaction_weight(&tx, None).unwrap();
    let weight_with_empty_witness = calculate_transaction_weight(&tx, Some(&vec![]), crate::types::Network::Mainnet).unwrap();
    
    // Weight should be same with no witness or empty witness
    assert_eq!(weight_no_witness, weight_with_empty_witness);
}

#[test]
fn test_segwit_witness_commitment_validation() {
    // Test witness commitment validation in coinbase
    let mut coinbase_tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [0; 32].into(), index: 0xffffffff },
            script_sig: vec![0x51],
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 5000000000,
            script_pubkey: vec![].into(),
        }].into(),
        lock_time: 0,
    };
    
    let witness_root = [0x42u8; 32];
    
    // Add witness commitment
    coinbase_tx.outputs[0].script_pubkey =
        create_witness_commitment_script(&witness_root, &[0u8; 32]);
    
    let is_valid = validate_witness_commitment(&coinbase_tx, &witness_root, &[]).unwrap();
    assert!(is_valid);
    
    // Test with wrong witness root (should fail)
    let wrong_root = [0x99u8; 32];
    let is_invalid = validate_witness_commitment(&coinbase_tx, &wrong_root, &[]).unwrap();
    assert!(!is_invalid);
}

#[test]
fn test_segwit_is_segwit_transaction() {
    // Test detection of SegWit transactions
    let mut tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00], // SegWit marker
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    assert!(is_segwit_transaction(&tx));
    
    // Non-SegWit transaction
    tx.inputs[0].script_sig = vec![0x51];
    assert!(!is_segwit_transaction(&tx));
}

#[test]
fn test_segwit_weight_base_size() {
    // Test that base size calculation is correct (without witness)
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x51; 50], // 50-byte scriptSig
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51; 25].into(), // 25-byte scriptPubkey
        }].into(),
        lock_time: 0,
    };
    
    let weight_no_witness = calculate_transaction_weight(&tx, None).unwrap();
    let weight_with_witness = calculate_transaction_weight(&tx, Some(&vec![vec![0x51; 100]]), crate::types::Network::Mainnet).unwrap();
    
    // Weight with witness should be larger
    assert!(weight_with_witness > weight_no_witness);
}

#[test]
fn test_segwit_weight_precise_calculation() {
    // Test precise weight calculation: Weight = 4 * base_size + total_size
    let tx = Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00], // SegWit marker
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    };
    
    let witness = vec![vec![0x51; 100]]; // 100-byte witness
    
    let weight = calculate_transaction_weight(&tx, Some(&witness), crate::types::Network::Mainnet).unwrap();
    
    // Base size (without witness) * 4 + total size (with witness)
    // This verifies the weight formula is applied correctly
    assert!(weight > 0);
}

#[test]
fn test_segwit_block_weight_sum() {
    // Test that block weight is sum of transaction weights
    let block = Block {
        header: create_test_header(1234567890, [0; 32]),
        transactions: vec![
            Transaction {
                version: 1,
                inputs: vec![].into(),
                outputs: vec![TransactionOutput {
                    value: 5000000000,
                    script_pubkey: vec![].into(),
                }].into(),
                lock_time: 0,
            },
            Transaction {
                version: 1,
                inputs: vec![TransactionInput {
                    prevout: OutPoint { hash: [1; 32].into(), index: 0 },
                    script_sig: vec![0x00],
                    sequence: 0xffffffff,
                }].into(),
                outputs: vec![TransactionOutput {
                    value: 1000,
                    script_pubkey: vec![0x51].into(),
                }].into(),
                lock_time: 0,
            },
        ],
    };
    
    let witnesses = vec![
        vec![],
        vec![vec![0x51]],
    ];
    
    let block_weight = calculate_block_weight(&block, &witnesses).unwrap();
    
    // Calculate individual transaction weights
    let tx0_weight = calculate_transaction_weight(&block.transactions[0], Some(&witnesses[0]), crate::types::Network::Mainnet).unwrap();
    let tx1_weight = calculate_transaction_weight(&block.transactions[1], Some(&witnesses[1]), crate::types::Network::Mainnet).unwrap();
    
    // Block weight should equal sum of transaction weights
    assert_eq!(block_weight, tx0_weight + tx1_weight);
}

#[test]
fn test_segwit_validate_block_weight_limit() {
    // Test that validate_segwit_block enforces weight limit
    let mut block = Block {
        header: create_test_header(1234567890, [0; 32]),
            transactions: vec![].into(),
    };
    
    // Create a small block (should pass)
    block.transactions.push(Transaction {
        version: 1,
        inputs: vec![TransactionInput {
            prevout: OutPoint { hash: [1; 32].into(), index: 0 },
            script_sig: vec![0x00],
            sequence: 0xffffffff,
        }].into(),
        outputs: vec![TransactionOutput {
            value: 1000,
            script_pubkey: vec![0x51].into(),
        }].into(),
        lock_time: 0,
    });
    
    let witnesses = vec![vec![vec![0x51]]];
    
    let is_valid = validate_segwit_block(&block, &witnesses, MAX_BLOCK_WEIGHT).unwrap();
    
    // Small block should pass validation
    assert!(is_valid);
}