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
//! Implementations of the `TxBuilder` for Bitcoin transactions. This builder automatically
//! selects between Legacy and Witness transactions based on its inputs. The user may also specify
//! the desired type using `build_legacy` or `build_witness`.
//!
//! This means that the caller doesn't typically need to worry about the implementation details.
//! They can simply use the builder transparently to produce the desired tx type.
//!
//! The builder is best accessed via the preconstructed network objects in `nets.rs`.

use std::marker::PhantomData;

use coins_core::{builder::TxBuilder, enc::AddressEncoder, types::tx::Transaction};

use crate::{
    enc::encoder::{Address, BitcoinEncoderMarker},
    types::{
        legacy::LegacyTx,
        script::{ScriptPubkey, ScriptSig, Witness},
        tx::{BitcoinTransaction, BitcoinTx},
        txin::{BitcoinOutpoint, BitcoinTxIn},
        txout::TxOut,
        witness::{WitnessTransaction, WitnessTx},
    },
};

/// This is a generic builder for Bitcoin transactions. It allows you to easily build legacy and
/// witness transactions.
///
/// Note: due to Bitcoin consensus rules, the order of inputs and outputs may be semantically
/// meaningful. E.g. when signing a transaction with the `SINGLE` sighash mode.
///
/// It is parameterized with an address encoder, so that the same struct and logic can be used on
/// mainnet and testnet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BitcoinTxBuilder<T: AddressEncoder> {
    version: u32,
    vin: Vec<BitcoinTxIn>,
    vout: Vec<TxOut>,
    locktime: u32,
    witnesses: Vec<Witness>,
    produce_witness: bool,
    encoder: PhantomData<fn(T) -> T>,
}

impl<T> BitcoinTxBuilder<T>
where
    T: BitcoinEncoderMarker,
{
    /// Add a set of witnesses to the transaction, and return a witness builder.
    pub fn extend_witnesses<I>(mut self, witnesses: I) -> Self
    where
        I: IntoIterator<Item = Witness>,
    {
        self.witnesses.extend(witnesses);
        self
    }

    /// Insert a witness at a speicified index
    pub fn insert_witness(
        mut self,
        index: usize,
        witness: <<Self as TxBuilder>::Transaction as Transaction>::TxIn,
    ) -> Self {
        let index = std::cmp::min(index, self.vin.len());
        self.vin.insert(index, witness);
        self
    }

    /// Add an op_return output. Using this twice may render the transaction non-standard.
    pub fn op_return(mut self, message: &[u8]) -> Self {
        self.vout.push(TxOut::op_return(message));
        self
    }

    /// Set the script sig at a specific input. Do nothing if the vin is not that long.
    pub fn set_script_sig(mut self, input_idx: usize, script_sig: ScriptSig) -> Self {
        if input_idx >= self.vin.len() {
            self
        } else {
            self.vin[input_idx].script_sig = script_sig;
            self
        }
    }

    /// Consume self, produce a legacy tx. Discard any witness information in the builder
    pub fn build_legacy(self) -> Result<LegacyTx, <LegacyTx as Transaction>::TxError> {
        LegacyTx::new(self.version, self.vin, self.vout, self.locktime)
    }

    /// Consume self, produce a witness tx
    pub fn build_witness(self) -> Result<WitnessTx, <WitnessTx as Transaction>::TxError> {
        <WitnessTx as WitnessTransaction>::new(
            self.version,
            self.vin,
            self.vout,
            self.witnesses,
            self.locktime,
        )
    }

    /// Add an output paying `value` to `script_pubkey`
    pub fn pay_script_pubkey(mut self, value: u64, script_pubkey: ScriptPubkey) -> Self {
        let output = TxOut::new(value, script_pubkey);
        self.vout.push(output);
        self
    }
}

impl<T> TxBuilder for BitcoinTxBuilder<T>
where
    T: BitcoinEncoderMarker,
{
    type Encoder = T;
    type Transaction = BitcoinTx;

    fn new() -> Self {
        Self {
            version: 0,
            vin: vec![],
            vout: vec![],
            locktime: 0,
            witnesses: vec![],
            produce_witness: false,
            encoder: PhantomData,
        }
    }

    fn from_tx(tx: Self::Transaction) -> Self {
        Self {
            version: tx.version(),
            vin: tx.inputs().to_vec(),
            vout: tx.outputs().to_vec(),
            locktime: tx.locktime(),
            witnesses: tx.witnesses().to_vec(),
            produce_witness: tx.is_witness(),
            encoder: PhantomData,
        }
    }

    fn from_tx_ref(tx: &Self::Transaction) -> Self {
        Self {
            version: tx.version(),
            vin: tx.inputs().to_vec(),
            vout: tx.outputs().to_vec(),
            locktime: tx.locktime(),
            witnesses: tx.witnesses().to_vec(),
            produce_witness: tx.is_witness(),
            encoder: PhantomData,
        }
    }

    fn version(mut self, version: u32) -> Self {
        self.version = version;
        self
    }

    fn spend<I>(mut self, prevout: I, sequence: u32) -> Self
    where
        I: Into<BitcoinOutpoint>,
    {
        self.vin.push(BitcoinTxIn::new(
            prevout.into(),
            ScriptSig::default(),
            sequence,
        ));
        self
    }

    fn pay(self, value: u64, address: &Address) -> Self {
        let script_pubkey = T::decode_address(address);
        self.pay_script_pubkey(value, script_pubkey)
    }

    fn insert_input(
        mut self,
        index: usize,
        input: <Self::Transaction as Transaction>::TxIn,
    ) -> Self {
        let index = std::cmp::min(index, self.vin.len());
        self.vin.insert(index, input);
        self
    }

    fn extend_inputs<I>(mut self, inputs: I) -> Self
    where
        I: IntoIterator<Item = BitcoinTxIn>,
    {
        self.vin.extend(inputs);
        self
    }

    fn insert_output(
        mut self,
        index: usize,
        output: <Self::Transaction as Transaction>::TxOut,
    ) -> Self {
        let index = std::cmp::min(index, self.vout.len());
        self.vout.insert(index, output);
        self
    }

    fn extend_outputs<I>(mut self, outputs: I) -> Self
    where
        I: IntoIterator<Item = TxOut>,
    {
        self.vout.extend(outputs);
        self
    }

    fn locktime(mut self, locktime: u32) -> Self {
        self.locktime = locktime;
        self
    }

    fn build(self) -> Result<Self::Transaction, <Self::Transaction as Transaction>::TxError> {
        if self.produce_witness || !self.witnesses.is_empty() {
            Ok(<WitnessTx as WitnessTransaction>::new(
                self.version,
                self.vin,
                self.vout,
                self.witnesses,
                self.locktime,
            )?
            .into())
        } else {
            Ok(LegacyTx::new(self.version, self.vin, self.vout, self.locktime)?.into())
        }
    }
}