blvm-sdk 0.1.16

Bitcoin Commons software developer kit, governance infrastructure and composition framework for Bitcoin
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! BIP174: Partially Signed Bitcoin Transaction (PSBT)
//!
//! Specification: https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki
//!
//! PSBT format enables multi-party transaction signing without exposing private keys.
//! Critical for hardware wallet support and transaction coordination.

use crate::governance::error::{GovernanceError, GovernanceResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Raw PSBT map (BIP174 key-value pairs as byte blobs).
type PsbtRawMap = HashMap<Vec<u8>, Vec<u8>>;

/// PSBT magic bytes: 0x70736274 ("psbt")
pub const PSBT_MAGIC: [u8; 4] = [0x70, 0x73, 0x62, 0x74];

/// PSBT separator: 0xff
pub const PSBT_SEPARATOR: u8 = 0xff;

/// PSBT global map key types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PsbtGlobalKey {
    /// Unsigned transaction (required)
    UnsignedTx = 0x00,
    /// Extended public key (BIP32)
    Xpub = 0x01,
    /// Version number
    Version = 0xfb,
    /// Proprietary data
    Proprietary = 0xfc,
}

/// PSBT input map key types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PsbtInputKey {
    /// Non-witness UTXO
    NonWitnessUtxo = 0x00,
    /// Witness UTXO
    WitnessUtxo = 0x01,
    /// Partial signature
    PartialSig = 0x02,
    /// Sighash type
    SighashType = 0x03,
    /// Redeem script
    RedeemScript = 0x04,
    /// Witness script
    WitnessScript = 0x05,
    /// BIP32 derivation path
    Bip32Derivation = 0x06,
    /// Final script sig
    FinalScriptSig = 0x07,
    /// Final script witness
    FinalScriptWitness = 0x08,
    /// Proprietary data
    Proprietary = 0xfc,
}

/// PSBT output map key types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PsbtOutputKey {
    /// Redeem script
    RedeemScript = 0x00,
    /// Witness script
    WitnessScript = 0x01,
    /// BIP32 derivation path
    Bip32Derivation = 0x02,
    /// Proprietary data
    Proprietary = 0xfc,
}

/// BIP32 derivation path entry
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Bip32Derivation {
    /// Public key (33 bytes compressed or 65 bytes uncompressed)
    pub pubkey: Vec<u8>,
    /// Derivation path
    pub path: Vec<u32>,
    /// Master key fingerprint (4 bytes)
    pub master_fingerprint: [u8; 4],
}

/// Partial signature entry
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartialSignature {
    /// Public key
    pub pubkey: Vec<u8>,
    /// Signature
    pub signature: Vec<u8>,
}

/// Sighash type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SighashType {
    /// SIGHASH_ALL
    All = 0x01,
    /// SIGHASH_NONE
    None = 0x02,
    /// SIGHASH_SINGLE
    Single = 0x03,
    /// SIGHASH_ALL | SIGHASH_ANYONECANPAY
    AllAnyoneCanPay = 0x81,
    /// SIGHASH_NONE | SIGHASH_ANYONECANPAY
    NoneAnyoneCanPay = 0x82,
    /// SIGHASH_SINGLE | SIGHASH_ANYONECANPAY
    SingleAnyoneCanPay = 0x83,
}

impl SighashType {
    /// Parse sighash type from byte
    pub fn from_byte(byte: u8) -> Option<Self> {
        match byte {
            0x01 => Some(SighashType::All),
            0x02 => Some(SighashType::None),
            0x03 => Some(SighashType::Single),
            0x81 => Some(SighashType::AllAnyoneCanPay),
            0x82 => Some(SighashType::NoneAnyoneCanPay),
            0x83 => Some(SighashType::SingleAnyoneCanPay),
            _ => None,
        }
    }

    /// Get byte representation
    pub fn to_byte(self) -> u8 {
        self as u8
    }
}

/// Partially Signed Bitcoin Transaction
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartiallySignedTransaction {
    /// Global map (unsigned transaction, xpubs, etc.)
    pub global: HashMap<Vec<u8>, Vec<u8>>,
    /// Input maps (one per input)
    pub inputs: Vec<HashMap<Vec<u8>, Vec<u8>>>,
    /// Output maps (one per output)
    pub outputs: Vec<HashMap<Vec<u8>, Vec<u8>>>,
    /// Version (default: 0)
    pub version: u8,
}

impl PartiallySignedTransaction {
    /// Create a new PSBT from an unsigned transaction
    pub fn new(unsigned_tx: &[u8]) -> GovernanceResult<Self> {
        let input_count = count_tx_inputs(unsigned_tx)?;
        let output_count = count_tx_outputs(unsigned_tx)?;

        let mut global = HashMap::new();
        global.insert(vec![PsbtGlobalKey::UnsignedTx as u8], unsigned_tx.to_vec());
        global.insert(vec![PsbtGlobalKey::Version as u8], vec![0x00]); // Version 0

        Ok(PartiallySignedTransaction {
            global,
            inputs: vec![HashMap::new(); input_count],
            outputs: vec![HashMap::new(); output_count],
            version: 0,
        })
    }

    /// Add input data
    pub fn add_input_data(
        &mut self,
        input_index: usize,
        key: Vec<u8>,
        value: Vec<u8>,
    ) -> GovernanceResult<()> {
        if input_index >= self.inputs.len() {
            // Extend inputs vector if needed
            while self.inputs.len() <= input_index {
                self.inputs.push(HashMap::new());
            }
        }
        self.inputs[input_index].insert(key, value);
        Ok(())
    }

    /// Add output data
    pub fn add_output_data(
        &mut self,
        output_index: usize,
        key: Vec<u8>,
        value: Vec<u8>,
    ) -> GovernanceResult<()> {
        if output_index >= self.outputs.len() {
            // Extend outputs vector if needed
            while self.outputs.len() <= output_index {
                self.outputs.push(HashMap::new());
            }
        }
        self.outputs[output_index].insert(key, value);
        Ok(())
    }

    /// Add partial signature to an input
    pub fn add_partial_signature(
        &mut self,
        input_index: usize,
        pubkey: Vec<u8>,
        signature: Vec<u8>,
    ) -> GovernanceResult<()> {
        // Format: <pubkey_len><pubkey><sig_len><signature>
        let mut key = vec![PsbtInputKey::PartialSig as u8];
        key.extend_from_slice(&pubkey);

        let mut value = Vec::with_capacity(1 + signature.len());
        value.push(signature.len() as u8);
        value.extend_from_slice(&signature);

        self.add_input_data(input_index, key, value)
    }

    /// Add BIP32 derivation path to an input
    pub fn add_bip32_derivation(
        &mut self,
        input_index: usize,
        pubkey: Vec<u8>,
        derivation: Bip32Derivation,
    ) -> GovernanceResult<()> {
        let mut key = vec![PsbtInputKey::Bip32Derivation as u8];
        key.extend_from_slice(&pubkey);

        // Serialize derivation: <master_fp(4)><path_len><path>
        let mut value = Vec::new();
        value.extend_from_slice(&derivation.master_fingerprint);
        value.push(derivation.path.len() as u8);
        for &index in &derivation.path {
            value.extend_from_slice(&index.to_be_bytes());
        }

        self.add_input_data(input_index, key, value)
    }

    /// Set sighash type for an input
    pub fn set_sighash_type(
        &mut self,
        input_index: usize,
        sighash_type: SighashType,
    ) -> GovernanceResult<()> {
        let key = vec![PsbtInputKey::SighashType as u8];
        let value = vec![sighash_type.to_byte()];
        self.add_input_data(input_index, key, value)
    }

    /// Check if PSBT is finalized (all inputs have final script sig/witness)
    pub fn is_finalized(&self) -> bool {
        let unsigned_tx_key = vec![PsbtGlobalKey::UnsignedTx as u8];
        let Some(unsigned_tx) = self.global.get(&unsigned_tx_key) else {
            return false;
        };
        let Ok(input_count) = count_tx_inputs(unsigned_tx) else {
            return false;
        };
        if self.inputs.len() != input_count {
            return false;
        }
        for input_map in &self.inputs {
            let has_final_sig = input_map.contains_key(&vec![PsbtInputKey::FinalScriptSig as u8]);
            let has_final_witness =
                input_map.contains_key(&vec![PsbtInputKey::FinalScriptWitness as u8]);

            if !has_final_sig && !has_final_witness {
                return false;
            }
        }
        true
    }

    /// Extract final transaction (throws error if not finalized)
    pub fn extract_transaction(&self) -> GovernanceResult<Vec<u8>> {
        if !self.is_finalized() {
            return Err(GovernanceError::InvalidInput(
                "PSBT is not finalized".to_string(),
            ));
        }

        let unsigned_tx_key = vec![PsbtGlobalKey::UnsignedTx as u8];
        let unsigned_tx = self.global.get(&unsigned_tx_key).ok_or_else(|| {
            GovernanceError::InvalidInput("Missing unsigned transaction".to_string())
        })?;

        extract_finalized_transaction(unsigned_tx, &self.inputs)
    }

    /// Serialize PSBT to bytes
    pub fn serialize(&self) -> GovernanceResult<Vec<u8>> {
        let mut result = Vec::new();

        // Magic bytes
        result.extend_from_slice(&PSBT_MAGIC);
        result.push(PSBT_SEPARATOR);

        // Global map
        serialize_map(&mut result, &self.global)?;

        // Separator between global and inputs
        result.push(PSBT_SEPARATOR);

        // Input maps
        for input_map in &self.inputs {
            serialize_map(&mut result, input_map)?;
            result.push(PSBT_SEPARATOR);
        }

        // Output maps
        for output_map in &self.outputs {
            serialize_map(&mut result, output_map)?;
            result.push(PSBT_SEPARATOR);
        }

        Ok(result)
    }

    /// Deserialize PSBT from bytes
    pub fn deserialize(data: &[u8]) -> GovernanceResult<Self> {
        if data.len() < 5 || data[..4] != PSBT_MAGIC || data[4] != PSBT_SEPARATOR {
            return Err(GovernanceError::InvalidInput(
                "Invalid PSBT magic bytes".to_string(),
            ));
        }

        let mut offset = 5;

        // Parse global map
        let (global, new_offset) = deserialize_map(&data[offset..])?;
        offset += new_offset;

        // Skip separator
        if offset >= data.len() || data[offset] != PSBT_SEPARATOR {
            return Err(GovernanceError::InvalidInput(
                "Missing separator after global map".to_string(),
            ));
        }
        offset += 1;

        let unsigned_tx_key = vec![PsbtGlobalKey::UnsignedTx as u8];
        let unsigned_tx = global.get(&unsigned_tx_key).ok_or_else(|| {
            GovernanceError::InvalidInput("Missing unsigned transaction in PSBT".to_string())
        })?;
        let input_count = count_tx_inputs(unsigned_tx)?;
        let output_count = count_tx_outputs(unsigned_tx)?;

        let mut inputs = Vec::with_capacity(input_count);
        for _ in 0..input_count {
            let (input_map, new_offset) = deserialize_map(&data[offset..])?;
            inputs.push(input_map);
            offset += new_offset;
            if offset >= data.len() || data[offset] != PSBT_SEPARATOR {
                return Err(GovernanceError::InvalidInput(
                    "Missing separator after PSBT input map".to_string(),
                ));
            }
            offset += 1;
        }

        let mut outputs = Vec::with_capacity(output_count);
        for _ in 0..output_count {
            let (output_map, new_offset) = deserialize_map(&data[offset..])?;
            outputs.push(output_map);
            offset += new_offset;
            if offset < data.len() && data[offset] == PSBT_SEPARATOR {
                offset += 1;
            }
        }

        // Extract version
        let version_key = vec![PsbtGlobalKey::Version as u8];
        let version = global
            .get(&version_key)
            .and_then(|v| v.first().copied())
            .unwrap_or(0);

        Ok(PartiallySignedTransaction {
            global,
            inputs,
            outputs,
            version,
        })
    }
}

/// Serialize a key-value map (CompactSize encoding)
fn serialize_map(result: &mut Vec<u8>, map: &HashMap<Vec<u8>, Vec<u8>>) -> GovernanceResult<()> {
    for (key, value) in map {
        // Key length (compact size)
        write_compact_size(result, key.len())?;
        result.extend_from_slice(key);

        // Value length (compact size)
        write_compact_size(result, value.len())?;
        result.extend_from_slice(value);
    }

    // End marker: 0x00
    result.push(0x00);

    Ok(())
}

/// Deserialize a key-value map
fn deserialize_map(data: &[u8]) -> GovernanceResult<(PsbtRawMap, usize)> {
    let mut map = HashMap::new();
    let mut offset = 0;

    while offset < data.len() {
        // Check for end marker
        if data[offset] == 0x00 {
            offset += 1;
            break;
        }

        // Read key (S-013: BIP174-style limits to prevent OOM)
        const MAX_PSBT_KEY_LEN: usize = 520;
        const MAX_PSBT_VALUE_LEN: usize = 520_000;
        let (key_len, len_offset) = read_compact_size(&data[offset..])?;
        offset += len_offset;
        if key_len > MAX_PSBT_KEY_LEN {
            return Err(GovernanceError::InvalidInput(format!(
                "PSBT key too long: {key_len} bytes (max: {MAX_PSBT_KEY_LEN})"
            )));
        }

        if offset + key_len > data.len() {
            return Err(GovernanceError::InvalidInput(
                "Invalid key length".to_string(),
            ));
        }
        let key = data[offset..offset + key_len].to_vec();
        offset += key_len;

        // Read value
        let (value_len, len_offset) = read_compact_size(&data[offset..])?;
        offset += len_offset;
        if value_len > MAX_PSBT_VALUE_LEN {
            return Err(GovernanceError::InvalidInput(format!(
                "PSBT value too long: {value_len} bytes (max: {MAX_PSBT_VALUE_LEN})"
            )));
        }

        if offset + value_len > data.len() {
            return Err(GovernanceError::InvalidInput(
                "Invalid value length".to_string(),
            ));
        }
        let value = data[offset..offset + value_len].to_vec();
        offset += value_len;

        map.insert(key, value);
    }

    Ok((map, offset))
}

/// Write compact size (VarInt encoding)
fn write_compact_size(result: &mut Vec<u8>, size: usize) -> GovernanceResult<()> {
    if size < 0xfd {
        result.push(size as u8);
    } else if size <= 0xffff {
        result.push(0xfd);
        result.extend_from_slice(&(size as u16).to_le_bytes());
    } else if size <= 0xffffffff {
        result.push(0xfe);
        result.extend_from_slice(&(size as u32).to_le_bytes());
    } else {
        result.push(0xff);
        result.extend_from_slice(&(size as u64).to_le_bytes());
    }
    Ok(())
}

/// Read compact size (VarInt decoding)
fn read_compact_size(data: &[u8]) -> GovernanceResult<(usize, usize)> {
    if data.is_empty() {
        return Err(GovernanceError::InvalidInput(
            "Unexpected end of data".to_string(),
        ));
    }

    match data[0] {
        n if n < 0xfd => Ok((n as usize, 1)),
        0xfd => {
            if data.len() < 3 {
                return Err(GovernanceError::InvalidInput(
                    "Invalid compact size".to_string(),
                ));
            }
            let value = u16::from_le_bytes([data[1], data[2]]) as usize;
            Ok((value, 3))
        }
        0xfe => {
            if data.len() < 5 {
                return Err(GovernanceError::InvalidInput(
                    "Invalid compact size".to_string(),
                ));
            }
            let value = u32::from_le_bytes([data[1], data[2], data[3], data[4]]) as usize;
            Ok((value, 5))
        }
        0xff => {
            if data.len() < 9 {
                return Err(GovernanceError::InvalidInput(
                    "Invalid compact size".to_string(),
                ));
            }
            let value = u64::from_le_bytes([
                data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
            ]) as usize;
            Ok((value, 9))
        }
        _ => Err(GovernanceError::InvalidInput(
            "Invalid compact size marker".to_string(),
        )),
    }
}

struct ParsedUnsignedTx {
    version: [u8; 4],
    inputs: Vec<[u8; 36]>,
    input_sequences: Vec<[u8; 4]>,
    outputs: Vec<([u8; 8], Vec<u8>)>,
    locktime: [u8; 4],
}

fn count_tx_inputs(unsigned: &[u8]) -> GovernanceResult<usize> {
    if unsigned.len() < 5 {
        return Err(GovernanceError::InvalidInput(
            "Unsigned transaction too short".to_string(),
        ));
    }
    let (count, _) = read_compact_size(&unsigned[4..])?;
    Ok(count)
}

fn count_tx_outputs(unsigned: &[u8]) -> GovernanceResult<usize> {
    if unsigned.len() < 5 {
        return Err(GovernanceError::InvalidInput(
            "Unsigned transaction too short".to_string(),
        ));
    }
    let mut offset = 4;
    let (input_count, len) = read_compact_size(&unsigned[offset..])?;
    offset += len;
    for _ in 0..input_count {
        if offset + 36 > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction input while counting outputs".to_string(),
            ));
        }
        offset += 36;
        let (script_len, len) = read_compact_size(&unsigned[offset..])?;
        offset += len;
        if offset + script_len + 4 > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction input script while counting outputs".to_string(),
            ));
        }
        offset += script_len + 4;
    }
    let (output_count, _) = read_compact_size(&unsigned[offset..])?;
    Ok(output_count)
}

fn parse_unsigned_tx(unsigned: &[u8]) -> GovernanceResult<ParsedUnsignedTx> {
    if unsigned.len() < 8 {
        return Err(GovernanceError::InvalidInput(
            "Unsigned transaction too short".to_string(),
        ));
    }
    let version: [u8; 4] = unsigned[0..4]
        .try_into()
        .map_err(|_| GovernanceError::InvalidInput("Invalid version".to_string()))?;
    let mut offset = 4;
    let (input_count, len) = read_compact_size(&unsigned[offset..])?;
    offset += len;

    let mut inputs = Vec::with_capacity(input_count);
    let mut input_sequences = Vec::with_capacity(input_count);
    for _ in 0..input_count {
        if offset + 36 > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction input prevout".to_string(),
            ));
        }
        let mut prevout = [0u8; 36];
        prevout.copy_from_slice(&unsigned[offset..offset + 36]);
        offset += 36;

        let (script_len, len) = read_compact_size(&unsigned[offset..])?;
        offset += len;
        if offset + script_len + 4 > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction input script".to_string(),
            ));
        }
        offset += script_len;

        let mut sequence = [0u8; 4];
        sequence.copy_from_slice(&unsigned[offset..offset + 4]);
        offset += 4;
        inputs.push(prevout);
        input_sequences.push(sequence);
    }

    let (output_count, len) = read_compact_size(&unsigned[offset..])?;
    offset += len;
    let mut outputs = Vec::with_capacity(output_count);
    for _ in 0..output_count {
        if offset + 8 > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction output value".to_string(),
            ));
        }
        let mut value = [0u8; 8];
        value.copy_from_slice(&unsigned[offset..offset + 8]);
        offset += 8;

        let (script_len, len) = read_compact_size(&unsigned[offset..])?;
        offset += len;
        if offset + script_len > unsigned.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated transaction output script".to_string(),
            ));
        }
        let script = unsigned[offset..offset + script_len].to_vec();
        offset += script_len;
        outputs.push((value, script));
    }

    if offset + 4 > unsigned.len() {
        return Err(GovernanceError::InvalidInput(
            "Truncated transaction locktime".to_string(),
        ));
    }
    let locktime: [u8; 4] = unsigned[offset..offset + 4]
        .try_into()
        .map_err(|_| GovernanceError::InvalidInput("Invalid locktime".to_string()))?;

    Ok(ParsedUnsignedTx {
        version,
        inputs,
        input_sequences,
        outputs,
        locktime,
    })
}

fn decode_final_witness_stack(data: &[u8]) -> GovernanceResult<Vec<Vec<u8>>> {
    let (count, len) = read_compact_size(data)?;
    let mut offset = len;
    let mut stack = Vec::with_capacity(count);
    for _ in 0..count {
        let (item_len, len2) = read_compact_size(&data[offset..])?;
        offset += len2;
        if offset + item_len > data.len() {
            return Err(GovernanceError::InvalidInput(
                "Truncated final script witness stack".to_string(),
            ));
        }
        stack.push(data[offset..offset + item_len].to_vec());
        offset += item_len;
    }
    Ok(stack)
}

fn serialize_legacy_tx(
    parsed: &ParsedUnsignedTx,
    script_sigs: &[Vec<u8>],
) -> GovernanceResult<Vec<u8>> {
    if script_sigs.len() != parsed.inputs.len() {
        return Err(GovernanceError::InvalidInput(
            "Final scriptSig count mismatch".to_string(),
        ));
    }
    let mut out = Vec::new();
    out.extend_from_slice(&parsed.version);
    write_compact_size(&mut out, parsed.inputs.len())?;
    for (i, prevout) in parsed.inputs.iter().enumerate() {
        out.extend_from_slice(prevout);
        write_compact_size(&mut out, script_sigs[i].len())?;
        out.extend_from_slice(&script_sigs[i]);
        out.extend_from_slice(&parsed.input_sequences[i]);
    }
    write_compact_size(&mut out, parsed.outputs.len())?;
    for (value, script) in &parsed.outputs {
        out.extend_from_slice(value);
        write_compact_size(&mut out, script.len())?;
        out.extend_from_slice(script);
    }
    out.extend_from_slice(&parsed.locktime);
    Ok(out)
}

fn serialize_segwit_tx(
    parsed: &ParsedUnsignedTx,
    script_sigs: &[Vec<u8>],
    witnesses: &[Vec<Vec<u8>>],
) -> GovernanceResult<Vec<u8>> {
    if script_sigs.len() != parsed.inputs.len() || witnesses.len() != parsed.inputs.len() {
        return Err(GovernanceError::InvalidInput(
            "Final script/witness count mismatch".to_string(),
        ));
    }
    let mut out = Vec::new();
    out.extend_from_slice(&parsed.version);
    out.push(0x00);
    out.push(0x01);
    write_compact_size(&mut out, parsed.inputs.len())?;
    for (i, prevout) in parsed.inputs.iter().enumerate() {
        out.extend_from_slice(prevout);
        write_compact_size(&mut out, script_sigs[i].len())?;
        out.extend_from_slice(&script_sigs[i]);
        out.extend_from_slice(&parsed.input_sequences[i]);
    }
    write_compact_size(&mut out, parsed.outputs.len())?;
    for (value, script) in &parsed.outputs {
        out.extend_from_slice(value);
        write_compact_size(&mut out, script.len())?;
        out.extend_from_slice(script);
    }
    for stack in witnesses {
        write_compact_size(&mut out, stack.len())?;
        for item in stack {
            write_compact_size(&mut out, item.len())?;
            out.extend_from_slice(item);
        }
    }
    out.extend_from_slice(&parsed.locktime);
    Ok(out)
}

fn extract_finalized_transaction(
    unsigned: &[u8],
    input_maps: &[PsbtRawMap],
) -> GovernanceResult<Vec<u8>> {
    let parsed = parse_unsigned_tx(unsigned)?;
    if input_maps.len() != parsed.inputs.len() {
        return Err(GovernanceError::InvalidInput(
            "PSBT input map count does not match unsigned transaction".to_string(),
        ));
    }

    let final_sig_key = vec![PsbtInputKey::FinalScriptSig as u8];
    let final_wit_key = vec![PsbtInputKey::FinalScriptWitness as u8];
    let mut script_sigs = Vec::with_capacity(input_maps.len());
    let mut witnesses = Vec::with_capacity(input_maps.len());
    let mut has_witness = false;

    for input_map in input_maps {
        script_sigs.push(input_map.get(&final_sig_key).cloned().unwrap_or_default());
        let stack = if let Some(raw) = input_map.get(&final_wit_key) {
            has_witness = true;
            decode_final_witness_stack(raw)?
        } else {
            Vec::new()
        };
        witnesses.push(stack);
    }

    if has_witness {
        serialize_segwit_tx(&parsed, &script_sigs, &witnesses)
    } else {
        serialize_legacy_tx(&parsed, &script_sigs)
    }
}

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

    fn mock_unsigned_tx() -> Vec<u8> {
        let mut tx = vec![
            0x01, 0x00, 0x00, 0x00, // version
            0x01, // input count
        ];
        tx.extend_from_slice(&[0u8; 32]); // prevout hash
        tx.extend_from_slice(&[0xff, 0xff, 0xff, 0xff]); // prevout index
        tx.push(0x00); // scriptSig length
        tx.extend_from_slice(&[0xff, 0xff, 0xff, 0xff]); // sequence
        tx.push(0x01); // output count
        tx.extend_from_slice(&[0u8; 8]); // value
        tx.push(0x00); // scriptPubKey length
        tx.extend_from_slice(&[0u8; 4]); // locktime
        tx
    }

    #[test]
    fn test_psbt_creation() {
        let unsigned_tx = mock_unsigned_tx();
        let psbt = PartiallySignedTransaction::new(&unsigned_tx).unwrap();

        assert_eq!(psbt.version, 0);
        assert_eq!(psbt.inputs.len(), 1);
        assert_eq!(psbt.outputs.len(), 1);
        assert!(
            psbt.global
                .contains_key(&vec![PsbtGlobalKey::UnsignedTx as u8])
        );
    }

    #[test]
    fn test_serialize_deserialize() {
        let unsigned_tx = mock_unsigned_tx();
        let mut psbt = PartiallySignedTransaction::new(&unsigned_tx).unwrap();

        // Add some data
        psbt.add_partial_signature(0, vec![0x02; 33], vec![0x30; 72])
            .unwrap();

        let serialized = psbt.serialize().unwrap();
        let deserialized = PartiallySignedTransaction::deserialize(&serialized).unwrap();

        assert_eq!(psbt.global, deserialized.global);
    }

    #[test]
    fn test_compact_size_encoding() {
        let mut result = Vec::new();
        write_compact_size(&mut result, 253).unwrap();
        assert_eq!(result[0], 0xfd);

        let (value, offset) = read_compact_size(&result).unwrap();
        assert_eq!(value, 253);
        assert_eq!(offset, 3);
    }
}