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
use super::input::Input;
use super::payload::{NoExtra, Payload};
use super::transaction::{
    Transaction, TransactionAuthData, TransactionBindingAuthData, TransactionStruct,
};
use super::transfer::Output;
use super::witness::Witness;
use crate::date::BlockDate;
use chain_addr::Address;
use std::marker::PhantomData;

/// A Transaction builder with an associated state machine
pub struct TxBuilderState<T> {
    data: Vec<u8>,
    tstruct: TransactionStruct,
    phantom: PhantomData<T>,
}

impl<T> Clone for TxBuilderState<T> {
    fn clone(&self) -> Self {
        TxBuilderState {
            data: self.data.clone(),
            tstruct: self.tstruct.clone(),
            phantom: self.phantom,
        }
    }
}

pub enum SetPayload {}
pub struct SetTtl<P>(PhantomData<P>);
pub struct SetIOs<P>(PhantomData<P>);
pub struct SetWitnesses<P>(PhantomData<P>);
pub struct SetAuthData<P: Payload>(PhantomData<P>);

pub type TxBuilder = TxBuilderState<SetPayload>;

// TODO not supported yet
pub const FRAGMENT_OVERHEAD: usize = 0;

impl Default for TxBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TxBuilder {
    /// Create a new Tx builder
    pub fn new() -> Self {
        // push empty hole for fragment overhead space
        let data = vec![0u8; FRAGMENT_OVERHEAD];
        TxBuilderState {
            data,
            tstruct: TransactionStruct {
                sz: 0,
                nb_inputs: 0,
                nb_outputs: 0,
                valid_until: BlockDate::first(),
                inputs: 0,
                outputs: 0,
                witnesses: 0,
                payload_auth: 0,
            },
            phantom: PhantomData,
        }
    }
}

impl<State> TxBuilderState<State> {
    fn current_pos(&self) -> usize {
        self.data.len() - FRAGMENT_OVERHEAD
    }
}

impl TxBuilderState<SetPayload> {
    /// Set the payload of this transaction
    pub fn set_payload<P: Payload>(mut self, payload: &P) -> TxBuilderState<SetTtl<P>> {
        if P::HAS_DATA {
            self.data.extend_from_slice(payload.payload_data().as_ref());
        }

        TxBuilderState {
            data: self.data,
            tstruct: self.tstruct,
            phantom: PhantomData,
        }
    }

    pub fn set_nopayload(self) -> TxBuilderState<SetTtl<NoExtra>> {
        self.set_payload(&NoExtra)
    }
}

impl<P> TxBuilderState<SetTtl<P>> {
    pub fn set_expiry_date(mut self, valid_until: BlockDate) -> TxBuilderState<SetIOs<P>> {
        fn write_date(data: &mut Vec<u8>, date: BlockDate) {
            data.extend_from_slice(&date.epoch.to_be_bytes());
            data.extend_from_slice(&date.slot_id.to_be_bytes());
        }
        write_date(&mut self.data, valid_until);
        self.tstruct.valid_until = valid_until;
        TxBuilderState {
            data: self.data,
            tstruct: self.tstruct,
            phantom: PhantomData,
        }
    }
}

impl<P> TxBuilderState<SetIOs<P>> {
    /// Set the inputs and outputs of this transaction
    ///
    /// This cannot accept more than 255 inputs, 255 outputs, since
    /// the length is encoded as u8, and hence will assert.
    ///
    /// Note that further restriction apply to the ledger,
    /// which only accept up to 254 outputs
    pub fn set_ios(
        mut self,
        inputs: &[Input],
        outputs: &[Output<Address>],
    ) -> TxBuilderState<SetWitnesses<P>> {
        assert!(inputs.len() < 256);
        assert!(outputs.len() < 256);

        let nb_inputs = inputs.len() as u8;
        let nb_outputs = outputs.len() as u8;

        self.data.push(nb_inputs);
        self.data.push(nb_outputs);

        self.tstruct.nb_inputs = nb_inputs;
        self.tstruct.nb_outputs = nb_outputs;

        self.tstruct.inputs = self.current_pos();

        for i in inputs {
            self.data.extend_from_slice(&i.bytes());
        }

        self.tstruct.outputs = self.current_pos();

        for o in outputs {
            self.data.extend_from_slice(&o.address.to_bytes());
            self.data.extend_from_slice(&o.value.bytes());
        }

        TxBuilderState {
            data: self.data,
            tstruct: self.tstruct,
            phantom: PhantomData,
        }
    }
}

impl<P> TxBuilderState<SetWitnesses<P>> {
    /// Get the authenticated data consisting of the payload and the input/outputs
    pub fn get_auth_data_for_witness(&self) -> TransactionAuthData<'_> {
        TransactionAuthData(&self.data[FRAGMENT_OVERHEAD..])
    }

    /// Set the witnesses of the transaction. There's need to be 1 witness per inputs,
    /// although it is not enforced by this construction
    ///
    /// Note that the same number of witnesses as the number of inputs need to be added here,
    /// otherwise an assert will raise.
    pub fn set_witnesses(self, witnesses: &[Witness]) -> TxBuilderState<SetAuthData<P>>
    where
        P: Payload,
    {
        assert_eq!(witnesses.len(), self.tstruct.nb_inputs as usize);
        self.set_witnesses_unchecked(witnesses)
    }

    /// Set the witnesses of the transaction.
    //It does Not verify if witnesses count is equal to transaction inputs
    pub fn set_witnesses_unchecked(
        mut self,
        witnesses: &[Witness],
    ) -> TxBuilderState<SetAuthData<P>>
    where
        P: Payload,
    {
        self.tstruct.witnesses = self.current_pos();
        for w in witnesses {
            self.data.extend_from_slice(&w.to_bytes())
        }
        TxBuilderState {
            data: self.data,
            tstruct: self.tstruct,
            phantom: PhantomData,
        }
    }
}

impl<P: Payload> TxBuilderState<SetAuthData<P>> {
    /// Get the authenticated data related to possible overall data for transaction and payload binding
    pub fn get_auth_data(&self) -> TransactionBindingAuthData<'_> {
        TransactionBindingAuthData(&self.data[FRAGMENT_OVERHEAD..])
    }

    /// Set the authenticated data
    pub fn set_payload_auth(mut self, auth_data: &P::Auth) -> Transaction<P> {
        self.tstruct.payload_auth = self.current_pos();
        if P::HAS_DATA && P::HAS_AUTH {
            self.data
                .extend_from_slice(<P as Payload>::payload_auth_data(auth_data).as_ref());
        }
        self.tstruct.sz = self.current_pos();
        Transaction {
            data: self.data.into(),
            tstruct: self.tstruct,
            phantom: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        testing::{
            builders::witness_builder::make_witness,
            data::{AddressData, AddressDataValue},
            TestGen,
        },
        value::Value,
    };
    use chain_addr::Discrimination;

    #[test]
    #[should_panic]
    pub fn test_internal_apply_transaction_witnesses_count_are_grater_than_inputs() {
        let faucets = vec![
            AddressDataValue::account(Discrimination::Test, Value(2)),
            AddressDataValue::account(Discrimination::Test, Value(1)),
        ];
        let reciever = AddressDataValue::utxo(Discrimination::Test, Value(2));
        let block0_hash = TestGen::hash();
        let tx_builder = TxBuilder::new()
            .set_payload(&NoExtra)
            .set_expiry_date(BlockDate::first().next_epoch())
            .set_ios(&[faucets[0].make_input(None)], &[reciever.make_output()]);

        let witness1 = make_witness(
            &block0_hash,
            &faucets[0].clone().into(),
            &tx_builder.get_auth_data_for_witness().hash(),
        );
        let witness2 = make_witness(
            &block0_hash,
            &faucets[1].clone().into(),
            &tx_builder.get_auth_data_for_witness().hash(),
        );
        tx_builder.set_witnesses(&[witness1, witness2]);
    }

    #[test]
    #[should_panic]
    pub fn test_internal_apply_transaction_witnesses_count_are_smaller_than_inputs() {
        let faucets = vec![
            AddressDataValue::account(Discrimination::Test, Value(1)),
            AddressDataValue::account(Discrimination::Test, Value(1)),
        ];
        let reciever = AddressData::utxo(Discrimination::Test);
        let block0_hash = TestGen::hash();
        let tx_builder = TxBuilder::new()
            .set_payload(&NoExtra)
            .set_expiry_date(BlockDate::first().next_epoch())
            .set_ios(
                &[faucets[0].make_input(None), faucets[1].make_input(None)],
                &[reciever.make_output(Value(2))],
            );

        let witness = make_witness(
            &block0_hash,
            &faucets[0].clone().into(),
            &tx_builder.get_auth_data_for_witness().hash(),
        );
        tx_builder.set_witnesses(&[witness]);
    }
}