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
//! Transaction that changes the ledger state.
use crate::amount::Stroops;
use crate::crypto::{hash, KeyPair, MuxedAccount};
use crate::error::{Error, Result};
use crate::memo::Memo;
use crate::network::Network;
use crate::operations::Operation;
use crate::signature::DecoratedSignature;
use crate::time_bounds::TimeBounds;
use crate::xdr;
use crate::xdr::{XDRDeserialize, XDRSerialize};
use xdr_rs_serialize::de::XDRIn;
use xdr_rs_serialize::ser::XDROut;

/// Minimum base fee.
pub const MIN_BASE_FEE: Stroops = Stroops(100);

/// Stellar transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transaction {
    source_account: MuxedAccount,
    fee: Stroops,
    sequence: i64,
    time_bounds: Option<TimeBounds>,
    memo: Memo,
    operations: Vec<Operation>,
    signatures: Vec<DecoratedSignature>,
}

/// Fee bump transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeeBumpTransaction {
    fee_source: MuxedAccount,
    fee: Stroops,
    inner_tx: Transaction,
    signatures: Vec<DecoratedSignature>,
}

/// Transaction envelope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransactionEnvelope {
    /// Transaction
    Transaction(Transaction),
    /// Fee bump transaction.
    FeeBumpTransaction(FeeBumpTransaction),
}

/// A builder to construct the properties of a `Transaction`.
pub struct TransactionBuilder {
    base_fee: Stroops,
    tx: Result<Transaction>,
}

impl Transaction {
    /// Creates a `TransactionBuilder` to configure a `Transaction`.
    ///
    /// This is the same as `TransactionBuilder::new`.
    pub fn builder<S: Into<MuxedAccount>>(
        source_account: S,
        sequence: i64,
        fee: Stroops,
    ) -> TransactionBuilder {
        TransactionBuilder::new(source_account, sequence, fee)
    }

    /// Retrieves the transaction source account.
    pub fn source_account(&self) -> &MuxedAccount {
        &self.source_account
    }

    /// Retrieves a mutable reference to the transaction source account.
    pub fn source_account_mut(&mut self) -> &mut MuxedAccount {
        &mut self.source_account
    }

    /// Retrieves the transaction fee.
    pub fn fee(&self) -> &Stroops {
        &self.fee
    }

    /// Retrieves a mutable reference to the transaction fee.
    pub fn fee_mut(&mut self) -> &mut Stroops {
        &mut self.fee
    }

    /// Retrieves the transaction sequence number.
    pub fn sequence(&self) -> &i64 {
        &self.sequence
    }

    /// Retrieves a mutable reference to the transaction sequence number.
    pub fn sequence_mut(&mut self) -> &mut i64 {
        &mut self.sequence
    }

    /// Retrieves the transaction time bounds.
    pub fn time_bounds(&self) -> &Option<TimeBounds> {
        &self.time_bounds
    }

    /// Retrieves a mutable reference to the transaction time bounds.
    pub fn time_bounds_mut(&mut self) -> &mut Option<TimeBounds> {
        &mut self.time_bounds
    }

    /// Retrieves the transaction memo.
    pub fn memo(&self) -> &Memo {
        &self.memo
    }

    /// Retrieves a mutable reference to the transaction memo.
    pub fn memo_mut(&mut self) -> &mut Memo {
        &mut self.memo
    }

    /// Retrieves the transaction operations.
    pub fn operations(&self) -> &Vec<Operation> {
        &self.operations
    }

    /// Retrieves a mutable reference to the transaction operations.
    pub fn operations_mut(&mut self) -> &mut Vec<Operation> {
        &mut self.operations
    }

    /// Retrieves the transaction signatures.
    pub fn signatures(&self) -> &Vec<DecoratedSignature> {
        &self.signatures
    }

    /// Retrieves a mutable reference to the transaction signatures.
    pub fn signatures_mut(&mut self) -> &mut Vec<DecoratedSignature> {
        &mut self.signatures
    }

    /// Creates a `TransactionEnvelope` from the transaction.
    pub fn to_envelope(&self) -> TransactionEnvelope {
        self.clone().into_envelope()
    }

    /// Creates a `TransactionEnvelope` from the transaction.
    ///
    /// This consumes the transaction and takes ownership of it.
    pub fn into_envelope(self) -> TransactionEnvelope {
        TransactionEnvelope::Transaction(self)
    }

    /// Sign transaction with `preimage`, and add signature.
    ///
    /// This signs the transaction with the preimage `x` of `hash(x)`.
    pub fn sign_hashx(&mut self, preimage: &[u8]) -> Result<()> {
        let signature = self.decorated_signature_from_preimage(&preimage)?;
        self.signatures.push(signature);
        Ok(())
    }

    /// Sign transaction with `key` for `network`, and add signature.
    pub fn sign(&mut self, key: &KeyPair, network: &Network) -> Result<()> {
        let signature = self.decorated_signature(&key, &network)?;
        self.signatures.push(signature);
        Ok(())
    }

    /// Returns the decorated signature of the transaction create with `image`.
    pub fn decorated_signature_from_preimage(&self, preimage: &[u8]) -> Result<DecoratedSignature> {
        DecoratedSignature::new_from_preimage(&preimage)
    }

    /// Returns the decorated signature of the transaction create with `key` for `network`.
    pub fn decorated_signature(
        &self,
        key: &KeyPair,
        network: &Network,
    ) -> Result<DecoratedSignature> {
        let tx_hash = self.hash(&network)?;
        Ok(key.sign_decorated(&tx_hash))
    }

    /// Returns the transaction hash for the transaction on `network`.
    pub fn hash(&self, network: &Network) -> Result<Vec<u8>> {
        let signature_data = self.signature_data(network)?;
        Ok(hash(&signature_data))
    }

    /// Returns the transaction signature data as bytes.
    pub fn signature_data(&self, network: &Network) -> Result<Vec<u8>> {
        let mut base = Vec::new();
        let tx_signature_payload = self.to_xdr_transaction_signature_payload(&network)?;
        tx_signature_payload
            .write_xdr(&mut base)
            .map_err(Error::XdrError)?;
        Ok(base)
    }

    /// Returns the xdr object.
    pub fn to_xdr(&self) -> Result<xdr::Transaction> {
        let source_account = self.source_account.to_xdr()?;
        let fee = self.fee.to_xdr_uint32()?;
        let seq_num = xdr::SequenceNumber::new(xdr::Int64::new(self.sequence));
        let time_bounds = match &self.time_bounds {
            None => None,
            Some(tb) => Some(tb.to_xdr()?),
        };
        let memo = self.memo.to_xdr()?;
        let mut operations = Vec::new();
        for operation in self.operations() {
            let xdr_operation = operation.to_xdr()?;
            operations.push(xdr_operation);
        }
        let ext = xdr::TransactionExt::V0(());
        Ok(xdr::Transaction {
            source_account,
            fee,
            seq_num,
            time_bounds,
            memo,
            operations,
            ext,
        })
    }

    /// Returns the transaction envelope v1 xdr object.
    pub fn to_xdr_envelope(&self) -> Result<xdr::TransactionV1Envelope> {
        let tx = self.to_xdr()?;
        let signatures = signatures_to_xdr(self.signatures())?;
        Ok(xdr::TransactionV1Envelope { tx, signatures })
    }

    /// Returns the xdr transaction signature payload object.
    pub fn to_xdr_transaction_signature_payload(
        &self,
        network: &Network,
    ) -> Result<xdr::TransactionSignaturePayload> {
        let network_id = xdr::Hash::new(network.network_id());
        let inner = self.to_xdr()?;
        let tagged_transaction =
            xdr::TransactionSignaturePayloadTaggedTransaction::EnvelopeTypeTx(inner);
        Ok(xdr::TransactionSignaturePayload {
            network_id,
            tagged_transaction,
        })
    }

    /// Creates from xdr object.
    pub fn from_xdr(x: &xdr::Transaction) -> Result<Transaction> {
        let source_account = MuxedAccount::from_xdr(&x.source_account)?;
        let fee = Stroops::from_xdr_uint32(&x.fee)?;
        let sequence = x.seq_num.value.value;
        let time_bounds = match &x.time_bounds {
            None => None,
            Some(tb) => Some(TimeBounds::from_xdr(tb)?),
        };
        let memo = Memo::from_xdr(&x.memo)?;
        let mut operations = Vec::new();
        for operation in &x.operations {
            let xdr_operation = Operation::from_xdr(&operation)?;
            operations.push(xdr_operation);
        }
        Ok(Transaction {
            source_account,
            fee,
            sequence,
            time_bounds,
            memo,
            operations,
            signatures: Vec::new(),
        })
    }

    /// Creates from xdr envelope object.
    pub fn from_xdr_envelope(x: &xdr::TransactionV1Envelope) -> Result<Transaction> {
        let mut tx = Self::from_xdr(&x.tx)?;
        let signatures = signatures_from_xdr(&x.signatures)?;
        tx.signatures = signatures;
        Ok(tx)
    }
}

impl FeeBumpTransaction {
    /// Creates a new fee bump transaction.
    pub fn new(
        fee_source: MuxedAccount,
        fee: Stroops,
        inner_tx: Transaction,
    ) -> FeeBumpTransaction {
        FeeBumpTransaction {
            fee_source,
            fee,
            inner_tx,
            signatures: Vec::new(),
        }
    }

    /// Retrieves the transaction fee source.
    pub fn fee_source(&self) -> &MuxedAccount {
        &self.fee_source
    }

    /// Retrieves a mutable reference to the transaction fee source.
    pub fn fee_source_mut(&mut self) -> &mut MuxedAccount {
        &mut self.fee_source
    }

    /// Retrievies the transaction fee.
    pub fn fee(&self) -> &Stroops {
        &self.fee
    }

    /// Retrievies a mutable reference to the transaction fee.
    pub fn fee_mut(&mut self) -> &mut Stroops {
        &mut self.fee
    }

    /// Retrieves the transaction inner transaction.
    pub fn inner_transaction(&self) -> &Transaction {
        &self.inner_tx
    }

    /// Retrieves a mutable reference to the transaction inner transaction.
    pub fn inner_transaction_mut(&mut self) -> &mut Transaction {
        &mut self.inner_tx
    }

    /// Retrieves the transaction signatures.
    pub fn signatures(&self) -> &Vec<DecoratedSignature> {
        &self.signatures
    }

    /// Retrieves a mutable reference the transaction signatures.
    pub fn signatures_mut(&mut self) -> &mut Vec<DecoratedSignature> {
        &mut self.signatures
    }

    /// Creates a `TransactionEnvelope` from the transaction.
    ///
    /// This consumes the transaction and takes ownership of it.
    pub fn into_envelope(self) -> TransactionEnvelope {
        TransactionEnvelope::FeeBumpTransaction(self)
    }

    /// Creates a `TransactionEnvelope` from the transaction.
    pub fn to_envelope(&self) -> TransactionEnvelope {
        self.clone().into_envelope()
    }

    /// Sign transaction with `preimage`, and add signature.
    ///
    /// This signs the transaction with the preimage `x` of `hash(x)`.
    pub fn sign_hashx(&mut self, preimage: &[u8]) -> Result<()> {
        let signature = self.decorated_signature_from_preimage(&preimage)?;
        self.signatures.push(signature);
        Ok(())
    }

    /// Sign transaction with `key` for `network`, and add signature.
    pub fn sign(&mut self, key: &KeyPair, network: &Network) -> Result<()> {
        let signature = self.decorated_signature(&key, &network)?;
        self.signatures.push(signature);
        Ok(())
    }

    /// Returns the decorated signature of the transaction create with `image`.
    pub fn decorated_signature_from_preimage(&self, preimage: &[u8]) -> Result<DecoratedSignature> {
        DecoratedSignature::new_from_preimage(&preimage)
    }

    /// Returns the decorated signature of the transaction create with `key` for `network`.
    pub fn decorated_signature(
        &self,
        key: &KeyPair,
        network: &Network,
    ) -> Result<DecoratedSignature> {
        let tx_hash = self.hash(&network)?;
        Ok(key.sign_decorated(&tx_hash))
    }

    /// Returns the transaction hash for the transaction on `network`.
    pub fn hash(&self, network: &Network) -> Result<Vec<u8>> {
        let signature_data = self.signature_data(network)?;
        Ok(hash(&signature_data))
    }

    /// Returns the transaction signature data as bytes.
    pub fn signature_data(&self, network: &Network) -> Result<Vec<u8>> {
        let mut base = Vec::new();
        let tx_signature_payload = self.to_xdr_transaction_signature_payload(&network)?;
        tx_signature_payload
            .write_xdr(&mut base)
            .map_err(Error::XdrError)?;
        Ok(base)
    }

    /// Returns the xdr object.
    pub fn to_xdr(&self) -> Result<xdr::FeeBumpTransaction> {
        let fee_source = self.fee_source.to_xdr()?;
        let fee = self.fee.to_xdr_int64()?;
        let tx_envelope = self.inner_tx.to_xdr_envelope()?;
        let inner_tx = xdr::FeeBumpTransactionInnerTx::EnvelopeTypeTx(tx_envelope);
        let ext = xdr::FeeBumpTransactionExt::V0(());
        Ok(xdr::FeeBumpTransaction {
            fee_source,
            fee,
            inner_tx,
            ext,
        })
    }

    /// Returns the fee bump transaction envelope xdr object.
    pub fn to_xdr_envelope(&self) -> Result<xdr::FeeBumpTransactionEnvelope> {
        let tx = self.to_xdr()?;
        let signatures = signatures_to_xdr(self.signatures())?;
        Ok(xdr::FeeBumpTransactionEnvelope { tx, signatures })
    }

    /// Creates from xdr object.
    pub fn from_xdr(x: &xdr::FeeBumpTransaction) -> Result<FeeBumpTransaction> {
        let fee_source = MuxedAccount::from_xdr(&x.fee_source)?;
        let fee = Stroops::new(x.fee.value);
        let inner_tx = match &x.inner_tx {
            xdr::FeeBumpTransactionInnerTx::EnvelopeTypeTx(inner_tx) => {
                Transaction::from_xdr_envelope(&inner_tx)?
            }
        };
        Ok(FeeBumpTransaction {
            fee_source,
            fee,
            inner_tx,
            signatures: Vec::new(),
        })
    }

    /// Creates from xdr envelope object.
    pub fn from_xdr_envelope(x: &xdr::FeeBumpTransactionEnvelope) -> Result<FeeBumpTransaction> {
        let mut tx = FeeBumpTransaction::from_xdr(&x.tx)?;
        let signatures = signatures_from_xdr(&x.signatures)?;
        tx.signatures = signatures;
        Ok(tx)
    }

    /// Returns the xdr transaction signature payload object.
    pub fn to_xdr_transaction_signature_payload(
        &self,
        network: &Network,
    ) -> Result<xdr::TransactionSignaturePayload> {
        let network_id = xdr::Hash::new(network.network_id());
        let inner = self.to_xdr()?;
        let tagged_transaction =
            xdr::TransactionSignaturePayloadTaggedTransaction::EnvelopeTypeTxFeeBump(inner);
        Ok(xdr::TransactionSignaturePayload {
            network_id,
            tagged_transaction,
        })
    }
}

impl TransactionEnvelope {
    /// If the transaction is a Transaction, returns its value. Returns None otherwise.
    pub fn as_transaction(&self) -> Option<&Transaction> {
        match *self {
            TransactionEnvelope::Transaction(ref tx) => Some(tx),
            _ => None,
        }
    }

    /// If the transaction is a Transaction, returns its mutable value. Returns None otherwise.
    pub fn as_transaction_mut(&mut self) -> Option<&mut Transaction> {
        match *self {
            TransactionEnvelope::Transaction(ref mut tx) => Some(tx),
            _ => None,
        }
    }

    /// Returns true if the transaction is a Transaction.
    pub fn is_transaction(&self) -> bool {
        self.as_transaction().is_some()
    }

    /// If the transaction is a FeeBumpTransaction, returns its value. Returns None otherwise.
    pub fn as_fee_bump_transaction(&self) -> Option<&FeeBumpTransaction> {
        match *self {
            TransactionEnvelope::FeeBumpTransaction(ref tx) => Some(tx),
            _ => None,
        }
    }

    /// If the transaction is a FeeBumpTransaction, returns its mutable value. Returns None otherwise.
    pub fn as_fee_bump_transaction_mut(&mut self) -> Option<&mut FeeBumpTransaction> {
        match *self {
            TransactionEnvelope::FeeBumpTransaction(ref mut tx) => Some(tx),
            _ => None,
        }
    }

    /// Returns true if the transaction is a FeeBumpTransaction.
    pub fn is_fee_bump_transaction(&self) -> bool {
        self.as_fee_bump_transaction().is_some()
    }

    /// Sign transaction with `preimage`, and add signature.
    ///
    /// This signs the transaction with the preimage `x` of `hash(x)`.
    pub fn sign_hashx(&mut self, preimage: &[u8]) -> Result<()> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.sign_hashx(&preimage),
            TransactionEnvelope::FeeBumpTransaction(tx) => tx.sign_hashx(&preimage),
        }
    }

    /// Sign transaction with `key` for `network`, and add signature.
    pub fn sign(&mut self, key: &KeyPair, network: &Network) -> Result<()> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.sign(&key, &network),
            TransactionEnvelope::FeeBumpTransaction(tx) => tx.sign(&key, &network),
        }
    }

    /// Returns the decorated signature of the transaction create with `image`.
    pub fn decorated_signature_from_preimage(&self, preimage: &[u8]) -> Result<DecoratedSignature> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.decorated_signature_from_preimage(&preimage),
            TransactionEnvelope::FeeBumpTransaction(tx) => {
                tx.decorated_signature_from_preimage(&preimage)
            }
        }
    }

    /// Returns the decorated signature of the transaction create with `key` for `network`.
    pub fn decorated_signature(
        &self,
        key: &KeyPair,
        network: &Network,
    ) -> Result<DecoratedSignature> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.decorated_signature(&key, &network),
            TransactionEnvelope::FeeBumpTransaction(tx) => tx.decorated_signature(&key, &network),
        }
    }

    /// Returns the transaction hash for the transaction on `network`.
    pub fn hash(&self, network: &Network) -> Result<Vec<u8>> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.hash(&network),
            TransactionEnvelope::FeeBumpTransaction(tx) => tx.hash(&network),
        }
    }

    /// Returns the transaction signature data as bytes.
    pub fn signature_data(&self, network: &Network) -> Result<Vec<u8>> {
        match self {
            TransactionEnvelope::Transaction(tx) => tx.signature_data(&network),
            TransactionEnvelope::FeeBumpTransaction(tx) => tx.signature_data(&network),
        }
    }

    /// Returns the xdr object.
    pub fn to_xdr(&self) -> Result<xdr::TransactionEnvelope> {
        match self {
            TransactionEnvelope::Transaction(tx) => {
                let inner = tx.to_xdr_envelope()?;
                Ok(xdr::TransactionEnvelope::EnvelopeTypeTx(inner))
            }
            TransactionEnvelope::FeeBumpTransaction(tx) => {
                let inner = tx.to_xdr_envelope()?;
                Ok(xdr::TransactionEnvelope::EnvelopeTypeTxFeeBump(inner))
            }
        }
    }

    /// Creates from xdr object.
    pub fn from_xdr(x: &xdr::TransactionEnvelope) -> Result<TransactionEnvelope> {
        match x {
            xdr::TransactionEnvelope::EnvelopeTypeTx(inner) => {
                let tx = Transaction::from_xdr_envelope(inner)?;
                Ok(TransactionEnvelope::Transaction(tx))
            }
            xdr::TransactionEnvelope::EnvelopeTypeTxV0(_) => todo!(),
            xdr::TransactionEnvelope::EnvelopeTypeTxFeeBump(inner) => {
                let tx = FeeBumpTransaction::from_xdr_envelope(inner)?;
                Ok(TransactionEnvelope::FeeBumpTransaction(tx))
            }
        }
    }

    /// Returns the xdr transaction signature payload object.
    pub fn to_xdr_transaction_signature_payload(
        &self,
        network: &Network,
    ) -> Result<xdr::TransactionSignaturePayload> {
        match self {
            TransactionEnvelope::Transaction(tx) => {
                tx.to_xdr_transaction_signature_payload(&network)
            }
            TransactionEnvelope::FeeBumpTransaction(tx) => {
                tx.to_xdr_transaction_signature_payload(&network)
            }
        }
    }
}

impl TransactionBuilder {
    pub fn new<S: Into<MuxedAccount>>(
        source_account: S,
        sequence: i64,
        base_fee: Stroops,
    ) -> TransactionBuilder {
        let tx = Transaction {
            source_account: source_account.into(),
            sequence,
            fee: Stroops::new(0),
            time_bounds: None,
            memo: Memo::new_none(),
            operations: Vec::new(),
            signatures: Vec::new(),
        };
        let tx = if base_fee < MIN_BASE_FEE {
            Err(Error::TransactionFeeTooLow)
        } else {
            Ok(tx)
        };
        TransactionBuilder { tx, base_fee }
    }

    pub fn with_time_bounds(mut self, time_bounds: TimeBounds) -> TransactionBuilder {
        if let Ok(ref mut tx) = self.tx {
            *tx.time_bounds_mut() = Some(time_bounds);
        }
        self
    }

    pub fn with_memo(mut self, memo: Memo) -> TransactionBuilder {
        if let Ok(ref mut tx) = self.tx {
            *tx.memo_mut() = memo;
        }
        self
    }

    pub fn add_operation(mut self, operation: Operation) -> TransactionBuilder {
        let mut error = None;
        if let Ok(ref mut tx) = self.tx {
            let operations = tx.operations_mut();
            if operations.len() > xdr::MAX_OPS_PER_TX as usize {
                error = Some(Err(Error::TooManyOperations));
            } else {
                operations.push(operation);
            }
        }
        if let Some(error) = error {
            self.tx = error;
        }
        self
    }

    pub fn into_transaction(mut self) -> Result<Transaction> {
        let mut error = None;
        if let Ok(ref mut tx) = self.tx {
            if tx.operations().is_empty() {
                error = Some(Err(Error::MissingOperations));
            }
            let fee = self
                .base_fee
                .checked_mul(&Stroops::new(tx.operations.len() as i64))
                .ok_or_else(|| Error::TransactionFeeOverflow)?;
            *tx.fee_mut() = fee;
        }

        if let Some(error) = error {
            self.tx = error;
        }
        self.tx
    }
}

impl XDRSerialize for TransactionEnvelope {
    fn write_xdr(&self, mut out: &mut Vec<u8>) -> Result<u64> {
        let xdr_tx = self.to_xdr()?;
        xdr_tx.write_xdr(&mut out).map_err(Error::XdrError)
    }
}

impl XDRDeserialize for TransactionEnvelope {
    fn from_xdr_bytes(buffer: &[u8]) -> Result<(Self, u64)> {
        let (xdr_tx, bytes_read) =
            xdr::TransactionEnvelope::read_xdr(&buffer).map_err(Error::XdrError)?;
        let res = TransactionEnvelope::from_xdr(&xdr_tx)?;
        Ok((res, bytes_read))
    }
}

fn signatures_to_xdr(signatures: &[DecoratedSignature]) -> Result<Vec<xdr::DecoratedSignature>> {
    let mut xdr_signatures = Vec::new();
    for signature in signatures {
        let xdr_signature = signature.to_xdr()?;
        xdr_signatures.push(xdr_signature);
    }
    Ok(xdr_signatures)
}

fn signatures_from_xdr(
    xdr_signatures: &[xdr::DecoratedSignature],
) -> Result<Vec<DecoratedSignature>> {
    let mut signatures = Vec::new();
    for xdr_signature in xdr_signatures {
        let signature = DecoratedSignature::from_xdr(&xdr_signature)?;
        signatures.push(signature);
    }
    Ok(signatures)
}

#[cfg(test)]
mod tests {
    use super::Transaction;
    use crate::amount::Stroops;
    use crate::crypto::KeyPair;
    use crate::memo::Memo;
    use crate::operations::Operation;
    use crate::time_bounds::TimeBounds;

    #[test]
    fn test_transaction_builder() {
        let kp = KeyPair::random().unwrap();
        let tx = Transaction::builder(kp.public_key().clone(), 123, Stroops::new(100))
            .with_memo(Memo::new_id(987))
            .with_time_bounds(TimeBounds::always_valid())
            .add_operation(Operation::new_inflation().build())
            .into_transaction()
            .unwrap();
        assert_eq!(123, *tx.sequence());
        assert_eq!(&Stroops::new(100), tx.fee());
        assert!(tx.memo().is_id());
        assert!(tx.time_bounds().is_some());
        assert_eq!(1, tx.operations().len());
    }
}