/
tx_builder.rs
3758 lines (3284 loc) · 148 KB
/
tx_builder.rs
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
use super::fees;
use super::utils;
use std::collections::{BTreeMap, BTreeSet, HashSet};
// comes from witsVKeyNeeded in the Ledger spec
fn witness_keys_for_cert(cert_enum: &Certificate, keys: &mut BTreeSet<Ed25519KeyHash>) {
match &cert_enum.0 {
// stake key registrations do not require a witness
CertificateEnum::StakeRegistration(_cert) => {},
CertificateEnum::StakeDeregistration(cert) => {
keys.insert(cert.stake_credential().to_keyhash().unwrap());
},
CertificateEnum::StakeDelegation(cert) => {
keys.insert(cert.stake_credential().to_keyhash().unwrap());
},
CertificateEnum::PoolRegistration(cert) => {
for owner in &cert.pool_params().pool_owners().0 {
keys.insert(owner.clone());
}
keys.insert(
Ed25519KeyHash::from_bytes(cert.pool_params().operator().to_bytes()).unwrap()
);
},
CertificateEnum::PoolRetirement(cert) => {
keys.insert(
Ed25519KeyHash::from_bytes(cert.pool_keyhash().to_bytes()).unwrap()
);
},
CertificateEnum::GenesisKeyDelegation(cert) => {
keys.insert(
Ed25519KeyHash::from_bytes(cert.genesis_delegate_hash().to_bytes()).unwrap()
);
},
// not witness as there is no single core node or genesis key that posts the certificate
CertificateEnum::MoveInstantaneousRewardsCert(_cert) => {},
}
}
fn fake_private_key() -> Bip32PrivateKey {
Bip32PrivateKey::from_bytes(
&[0xb8, 0xf2, 0xbe, 0xce, 0x9b, 0xdf, 0xe2, 0xb0, 0x28, 0x2f, 0x5b, 0xad, 0x70, 0x55, 0x62, 0xac, 0x99, 0x6e, 0xfb, 0x6a, 0xf9, 0x6b, 0x64, 0x8f,
0x44, 0x45, 0xec, 0x44, 0xf4, 0x7a, 0xd9, 0x5c, 0x10, 0xe3, 0xd7, 0x2f, 0x26, 0xed, 0x07, 0x54, 0x22, 0xa3, 0x6e, 0xd8, 0x58, 0x5c, 0x74, 0x5a,
0x0e, 0x11, 0x50, 0xbc, 0xce, 0xba, 0x23, 0x57, 0xd0, 0x58, 0x63, 0x69, 0x91, 0xf3, 0x8a, 0x37, 0x91, 0xe2, 0x48, 0xde, 0x50, 0x9c, 0x07, 0x0d,
0x81, 0x2a, 0xb2, 0xfd, 0xa5, 0x78, 0x60, 0xac, 0x87, 0x6b, 0xc4, 0x89, 0x19, 0x2c, 0x1e, 0xf4, 0xce, 0x25, 0x3c, 0x19, 0x7e, 0xe2, 0x19, 0xa4]
).unwrap()
}
fn fake_raw_key_sig() -> Ed25519Signature {
Ed25519Signature::from_bytes(
vec![36, 248, 153, 211, 155, 23, 253, 93, 102, 193, 146, 196, 181, 13, 52, 62, 66, 247, 35, 91, 48, 80, 76, 138, 231, 97, 159, 147, 200, 40, 220, 109, 206, 69, 104, 221, 105, 23, 124, 85, 24, 40, 73, 45, 119, 122, 103, 39, 253, 102, 194, 251, 204, 189, 168, 194, 174, 237, 146, 3, 44, 153, 121, 10]
).unwrap()
}
fn fake_raw_key_public() -> PublicKey {
PublicKey::from_bytes(
&[207, 118, 57, 154, 33, 13, 232, 114, 14, 159, 168, 148, 228, 94, 65, 226, 154, 181, 37, 227, 11, 196, 2, 128, 28, 7, 98, 80, 209, 88, 91, 205]
).unwrap()
}
fn count_needed_vkeys(tx_builder: &TransactionBuilder) -> usize {
let input_hashes = &tx_builder.input_types.vkeys;
match &tx_builder.mint_scripts {
None => input_hashes.len(),
Some(scripts) => {
// Union all input keys with minting keys
input_hashes.union(&RequiredSignersSet::from(scripts)).count()
}
}
}
// tx_body must be the result of building from tx_builder
// constructs the rest of the Transaction using fake witness data of the correct length
// for use in calculating the size of the final Transaction
fn fake_full_tx(tx_builder: &TransactionBuilder, body: TransactionBody) -> Result<Transaction, JsError> {
let fake_key_root = fake_private_key();
let raw_key_public = fake_raw_key_public();
let fake_sig = fake_raw_key_sig();
// recall: this includes keys for input, certs and withdrawals
let vkeys = match count_needed_vkeys(tx_builder) {
0 => None,
x => {
let fake_vkey_witness = Vkeywitness::new(
&Vkey::new(&raw_key_public),
&fake_sig
);
let mut result = Vkeywitnesses::new();
for _i in 0..x {
result.add(&fake_vkey_witness.clone());
}
Some(result)
},
};
let script_keys: Option<NativeScripts> = match tx_builder.input_types.scripts.len() {
0 => None,
_x => {
// TODO: figure out how to populate fake witnesses for these
return Err(JsError::from_str("Script inputs not supported yet"))
},
};
let bootstrap_keys = match tx_builder.input_types.bootstraps.len() {
0 => None,
_x => {
let mut result = BootstrapWitnesses::new();
for addr in &tx_builder.input_types.bootstraps {
// picking icarus over daedalus for fake witness generation shouldn't matter
result.add(&make_icarus_bootstrap_witness(
&TransactionHash::from([0u8; TransactionHash::BYTE_COUNT]),
&ByronAddress::from_bytes(addr.clone()).unwrap(),
&fake_key_root
));
}
Some(result)
},
};
let full_script_keys = match &tx_builder.mint_scripts {
None => script_keys,
Some(witness_scripts) => {
let mut ns = script_keys
.map(|x| { x.clone() })
.unwrap_or(NativeScripts::new());
witness_scripts.0.iter().for_each(|s| {
ns.add(s);
});
Some(ns)
}
};
let witness_set = TransactionWitnessSet {
vkeys,
native_scripts: full_script_keys,
bootstraps: bootstrap_keys,
// TODO: plutus support?
plutus_scripts: None,
plutus_data: None,
redeemers: None,
};
Ok(Transaction {
body,
witness_set,
is_valid: true,
auxiliary_data: tx_builder.auxiliary_data.clone(),
})
}
fn assert_required_mint_scripts(mint: &Mint, maybe_mint_scripts: Option<&NativeScripts>) -> Result<(), JsError> {
if maybe_mint_scripts.is_none_or_empty() {
return Err(JsError::from_str(
"Mint is present in the builder, but witness scripts are not provided!",
));
}
let mint_scripts = maybe_mint_scripts.unwrap();
let witness_hashes: HashSet<ScriptHash> = mint_scripts.0.iter().map(|script| {
script.hash(ScriptHashNamespace::NativeScript)
}).collect();
for mint_hash in mint.keys().0.iter() {
if !witness_hashes.contains(mint_hash) {
return Err(JsError::from_str(
&format!(
"No witness script is found for mint policy '{:?}'! Script is required!",
hex::encode(mint_hash.to_bytes()),
))
);
}
}
Ok(())
}
fn min_fee(tx_builder: &TransactionBuilder) -> Result<Coin, JsError> {
// Commented out for performance, `min_fee` is a critical function
// This was mostly added here as a paranoid step anyways
// If someone is using `set_mint` and `add_mint*` API function, everything is expected to be intact
// TODO: figure out if assert is needed here and a better way to do it maybe only once if mint doesn't change
// if let Some(mint) = tx_builder.mint.as_ref() {
// assert_required_mint_scripts(mint, tx_builder.mint_scripts.as_ref())?;
// }
let full_tx = fake_full_tx(tx_builder, tx_builder.build()?)?;
fees::min_fee(&full_tx, &tx_builder.config.fee_algo)
}
// We need to know how many of each type of witness will be in the transaction so we can calculate the tx fee
#[derive(Clone, Debug)]
struct MockWitnessSet {
vkeys: BTreeSet<Ed25519KeyHash>,
scripts: BTreeSet<ScriptHash>,
bootstraps: BTreeSet<Vec<u8>>,
}
#[derive(Clone, Debug)]
struct TxBuilderInput {
input: TransactionInput,
amount: Value, // we need to keep track of the amount in the inputs for input selection
}
#[wasm_bindgen]
pub enum CoinSelectionStrategyCIP2 {
LargestFirst,
RandomImprove,
}
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilderConfig {
fee_algo: fees::LinearFee,
pool_deposit: BigNum, // protocol parameter
key_deposit: BigNum, // protocol parameter
max_value_size: u32, // protocol parameter
max_tx_size: u32, // protocol parameter
coins_per_utxo_word: Coin, // protocol parameter
prefer_pure_change: bool,
}
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilderConfigBuilder {
fee_algo: Option<fees::LinearFee>,
pool_deposit: Option<BigNum>, // protocol parameter
key_deposit: Option<BigNum>, // protocol parameter
max_value_size: Option<u32>, // protocol parameter
max_tx_size: Option<u32>, // protocol parameter
coins_per_utxo_word: Option<Coin>, // protocol parameter
prefer_pure_change: bool,
}
#[wasm_bindgen]
impl TransactionBuilderConfigBuilder {
pub fn new() -> Self {
Self {
fee_algo: None,
pool_deposit: None,
key_deposit: None,
max_value_size: None,
max_tx_size: None,
coins_per_utxo_word: None,
prefer_pure_change: false,
}
}
pub fn fee_algo(&self, fee_algo: &fees::LinearFee) -> Self {
let mut cfg = self.clone();
cfg.fee_algo = Some(fee_algo.clone());
cfg
}
pub fn coins_per_utxo_word(&self, coins_per_utxo_word: &Coin) -> Self {
let mut cfg = self.clone();
cfg.coins_per_utxo_word = Some(coins_per_utxo_word.clone());
cfg
}
pub fn pool_deposit(&self, pool_deposit: &BigNum) -> Self {
let mut cfg = self.clone();
cfg.pool_deposit = Some(pool_deposit.clone());
cfg
}
pub fn key_deposit(&self, key_deposit: &BigNum) -> Self {
let mut cfg = self.clone();
cfg.key_deposit = Some(key_deposit.clone());
cfg
}
pub fn max_value_size(&self, max_value_size: u32) -> Self {
let mut cfg = self.clone();
cfg.max_value_size = Some(max_value_size);
cfg
}
pub fn max_tx_size(&self, max_tx_size: u32) -> Self {
let mut cfg = self.clone();
cfg.max_tx_size = Some(max_tx_size);
cfg
}
pub fn prefer_pure_change(&self, prefer_pure_change: bool) -> Self {
let mut cfg = self.clone();
cfg.prefer_pure_change = prefer_pure_change;
cfg
}
pub fn build(&self) -> Result<TransactionBuilderConfig, JsError> {
let cfg = self.clone();
Ok(TransactionBuilderConfig {
fee_algo: cfg.fee_algo.ok_or(JsError::from_str("uninitialized field: fee_algo"))?,
pool_deposit: cfg.pool_deposit.ok_or(JsError::from_str("uninitialized field: pool_deposit"))?,
key_deposit: cfg.key_deposit.ok_or(JsError::from_str("uninitialized field: key_deposit"))?,
max_value_size: cfg.max_value_size.ok_or(JsError::from_str("uninitialized field: max_value_size"))?,
max_tx_size: cfg.max_tx_size.ok_or(JsError::from_str("uninitialized field: max_tx_size"))?,
coins_per_utxo_word: cfg.coins_per_utxo_word.ok_or(JsError::from_str("uninitialized field: coins_per_utxo_word"))?,
prefer_pure_change: cfg.prefer_pure_change,
})
}
}
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct TransactionBuilder {
config: TransactionBuilderConfig,
inputs: Vec<TxBuilderInput>,
outputs: TransactionOutputs,
fee: Option<Coin>,
ttl: Option<Slot>, // absolute slot number
certs: Option<Certificates>,
withdrawals: Option<Withdrawals>,
auxiliary_data: Option<AuxiliaryData>,
validity_start_interval: Option<Slot>,
input_types: MockWitnessSet,
mint: Option<Mint>,
mint_scripts: Option<NativeScripts>,
}
#[wasm_bindgen]
impl TransactionBuilder {
/// This automatically selects and adds inputs from {inputs} consisting of just enough to cover
/// the outputs that have already been added.
/// This should be called after adding all certs/outputs/etc and will be an error otherwise.
/// Uses CIP2: https://github.com/cardano-foundation/CIPs/blob/master/CIP-0002/CIP-0002.md
/// Adding a change output must be called after via TransactionBuilder::add_change_if_needed()
/// This function, diverging from CIP2, takes into account fees and will attempt to add additional
/// inputs to cover the minimum fees. This does not, however, set the txbuilder's fee.
pub fn add_inputs_from(&mut self, inputs: &TransactionUnspentOutputs, strategy: CoinSelectionStrategyCIP2) -> Result<(), JsError> {
let mut available_inputs = inputs.0.clone();
let mut input_total = self.get_total_input()?;
let mut output_total = self
.get_explicit_output()?
.checked_add(&Value::new(&self.get_deposit()?))?
.checked_add(&Value::new(&self.min_fee()?))?;
match strategy {
CoinSelectionStrategyCIP2::LargestFirst => {
available_inputs.sort_by_key(|input| input.output.amount.coin);
// iterate in decreasing order of ADA-only value
for input in available_inputs.iter().rev() {
if input_total >= output_total {
break;
}
// differing from CIP2, we include the needed fees in the targets instead of just output values
let input_fee = self.fee_for_input(&input.output.address, &input.input, &input.output.amount)?;
self.add_input(&input.output.address, &input.input, &input.output.amount);
input_total = input_total.checked_add(&input.output.amount)?;
output_total = output_total.checked_add(&Value::new(&input_fee))?;
}
if input_total < output_total {
return Err(JsError::from_str("UTxO Balance Insufficient"));
}
},
CoinSelectionStrategyCIP2::RandomImprove => {
fn add_random_input(
s: &mut TransactionBuilder,
rng: &mut rand::rngs::ThreadRng,
available_inputs: &mut Vec<TransactionUnspentOutput>,
input_total: &Value,
output_total: &Value,
added: &Value,
needed: &Value
) -> Result<(Value, Value, Value, Value, TransactionUnspentOutput), JsError> {
let random_index = rng.gen_range(0..available_inputs.len());
let input = available_inputs.swap_remove(random_index);
// differing from CIP2, we include the needed fees in the targets instead of just output values
let input_fee = s.fee_for_input(&input.output.address, &input.input, &input.output.amount)?;
s.add_input(&input.output.address, &input.input, &input.output.amount);
let new_input_total = input_total.checked_add(&input.output.amount)?;
let new_output_total = output_total.checked_add(&Value::new(&input_fee))?;
let new_needed = needed.checked_add(&Value::new(&input_fee))?;
let new_added = added.checked_add(&input.output.amount)?;
Ok((new_input_total, new_output_total, new_added, new_needed, input))
}
use rand::Rng;
if self.outputs.0.iter().any(|output| output.amount.multiasset.is_some()) {
return Err(JsError::from_str("Multiasset values not supported by RandomImprove. Please use LargestFirst"));
}
// Phase 1: Random Selection
let mut associated_inputs: BTreeMap<TransactionOutput, Vec<TransactionUnspentOutput>> = BTreeMap::new();
let mut rng = rand::thread_rng();
let mut outputs = self.outputs.0.clone();
outputs.sort_by_key(|output| output.amount.coin);
for output in outputs.iter().rev() {
let mut added = Value::new(&Coin::zero());
let mut needed = output.amount.clone();
while added < needed {
if available_inputs.is_empty() {
return Err(JsError::from_str("UTxO Balance Insufficient"));
}
let (new_input_total, new_output_total, new_added, new_needed, input) = add_random_input(self, &mut rng, &mut available_inputs, &input_total, &output_total, &added, &needed)?;
input_total = new_input_total;
output_total = new_output_total;
added = new_added;
needed = new_needed;
associated_inputs.entry(output.clone()).or_default().push(input);
}
}
if !available_inputs.is_empty() {
// Phase 2: Improvement
for output in outputs.iter_mut() {
let associated = associated_inputs.get_mut(output).unwrap();
for input in associated.iter_mut() {
let random_index = rng.gen_range(0..available_inputs.len());
let new_input = available_inputs.get_mut(random_index).unwrap();
let cur = from_bignum(&input.output.amount.coin);
let new = from_bignum(&new_input.output.amount.coin);
let min = from_bignum(&output.amount.coin);
let ideal = 2 * min;
let max = 3 * min;
let move_closer = (ideal as i128 - new as i128).abs() < (ideal as i128 - cur as i128).abs();
let not_exceed_max = new < max;
if move_closer && not_exceed_max {
std::mem::swap(input, new_input);
}
}
}
}
// Phase 3: add extra inputs needed for fees
// We do this at the end because this new inputs won't be associated with
// a specific output, so the improvement algorithm we do above does not apply here.
if input_total < output_total {
let mut added = Value::new(&Coin::zero());
let mut remaining_amount = output_total.checked_sub(&input_total)?;
while added < remaining_amount {
if available_inputs.is_empty() {
return Err(JsError::from_str("UTxO Balance Insufficient"));
}
let (new_input_total, new_output_total, new_added, new_remaining_amount, _) = add_random_input(self, &mut rng, &mut available_inputs, &input_total, &output_total, &added, &remaining_amount)?;
input_total = new_input_total;
output_total = new_output_total;
added = new_added;
remaining_amount = new_remaining_amount;
}
}
},
}
Ok(())
}
/// We have to know what kind of inputs these are to know what kind of mock witnesses to create since
/// 1) mock witnesses have different lengths depending on the type which changes the expecting fee
/// 2) Witnesses are a set so we need to get rid of duplicates to avoid over-estimating the fee
pub fn add_key_input(&mut self, hash: &Ed25519KeyHash, input: &TransactionInput, amount: &Value) {
self.inputs.push(TxBuilderInput {
input: input.clone(),
amount: amount.clone(),
});
self.input_types.vkeys.insert(hash.clone());
}
pub fn add_script_input(&mut self, hash: &ScriptHash, input: &TransactionInput, amount: &Value) {
self.inputs.push(TxBuilderInput {
input: input.clone(),
amount: amount.clone(),
});
self.input_types.scripts.insert(hash.clone());
}
pub fn add_bootstrap_input(&mut self, hash: &ByronAddress, input: &TransactionInput, amount: &Value) {
self.inputs.push(TxBuilderInput {
input: input.clone(),
amount: amount.clone(),
});
self.input_types.bootstraps.insert(hash.to_bytes());
}
pub fn add_input(&mut self, address: &Address, input: &TransactionInput, amount: &Value) {
match &BaseAddress::from_address(address) {
Some(addr) => {
match &addr.payment_cred().to_keyhash() {
Some(hash) => return self.add_key_input(hash, input, amount),
None => (),
}
match &addr.payment_cred().to_scripthash() {
Some(hash) => return self.add_script_input(hash, input, amount),
None => (),
}
},
None => (),
}
match &EnterpriseAddress::from_address(address) {
Some(addr) => {
match &addr.payment_cred().to_keyhash() {
Some(hash) => return self.add_key_input(hash, input, amount),
None => (),
}
match &addr.payment_cred().to_scripthash() {
Some(hash) => return self.add_script_input(hash, input, amount),
None => (),
}
},
None => (),
}
match &PointerAddress::from_address(address) {
Some(addr) => {
match &addr.payment_cred().to_keyhash() {
Some(hash) => return self.add_key_input(hash, input, amount),
None => (),
}
match &addr.payment_cred().to_scripthash() {
Some(hash) => return self.add_script_input(hash, input, amount),
None => (),
}
},
None => (),
}
match &ByronAddress::from_address(address) {
Some(addr) => {
return self.add_bootstrap_input(addr, input, amount);
},
None => (),
}
}
/// calculates how much the fee would increase if you added a given output
pub fn fee_for_input(&self, address: &Address, input: &TransactionInput, amount: &Value) -> Result<Coin, JsError> {
let mut self_copy = self.clone();
// we need some value for these for it to be a a valid transaction
// but since we're only calculating the difference between the fee of two transactions
// it doesn't matter what these are set as, since it cancels out
self_copy.set_fee(&to_bignum(0));
let fee_before = min_fee(&self_copy)?;
self_copy.add_input(&address, &input, &amount);
let fee_after = min_fee(&self_copy)?;
fee_after.checked_sub(&fee_before)
}
/// Add output by specifying the Address and Value
pub fn add_output_amount(&mut self, address: &Address, amount: &Value) -> Result<(), JsError> {
self.add_output(&TransactionOutput::new(address, amount))
}
/// Add output by specifying the Address and Coin (BigNum)
/// Output will have no additional assets
pub fn add_output_coin(&mut self, address: &Address, coin: &Coin) -> Result<(), JsError> {
self.add_output_amount(address, &Value::new(coin))
}
/// Add output by specifying the Address, the Coin (BigNum), and the MultiAsset
pub fn add_output_coin_and_asset(
&mut self,
address: &Address,
coin: &Coin,
multiasset: &MultiAsset,
) -> Result<(), JsError> {
let mut val = Value::new(coin);
val.set_multiasset(multiasset);
self.add_output_amount(address, &val)
}
/// Add output by specifying the Address and the MultiAsset
/// The output will be set to contain the minimum required amount of Coin
pub fn add_output_asset_and_min_required_coin(
&mut self,
address: &Address,
multiasset: &MultiAsset,
) -> Result<(), JsError> {
let min_possible_coin = min_pure_ada(&self.config.coins_per_utxo_word)?;
let mut value = Value::new(&min_possible_coin);
value.set_multiasset(multiasset);
let required_coin = min_ada_required(
&value,
false,
&self.config.coins_per_utxo_word,
)?;
self.add_output_coin_and_asset(address, &required_coin, multiasset)
}
/// Add explicit output via a TransactionOutput object
pub fn add_output(&mut self, output: &TransactionOutput) -> Result<(), JsError> {
let value_size = output.amount.to_bytes().len();
if value_size > self.config.max_value_size as usize {
return Err(JsError::from_str(&format!(
"Maximum value size of {} exceeded. Found: {}",
self.config.max_value_size,
value_size
)));
}
let min_ada = min_ada_required(
&output.amount(),
false,
&self.config.coins_per_utxo_word,
)?;
if output.amount().coin() < min_ada {
Err(JsError::from_str(&format!(
"Value {} less than the minimum UTXO value {}",
from_bignum(&output.amount().coin()),
from_bignum(&min_ada)
)))
} else {
self.outputs.add(output);
Ok(())
}
}
/// calculates how much the fee would increase if you added a given output
pub fn fee_for_output(&self, output: &TransactionOutput) -> Result<Coin, JsError> {
let mut self_copy = self.clone();
// we need some value for these for it to be a a valid transaction
// but since we're only calculating the different between the fee of two transactions
// it doesn't matter what these are set as, since it cancels out
self_copy.set_fee(&to_bignum(0));
let fee_before = min_fee(&self_copy)?;
self_copy.add_output(&output)?;
let fee_after = min_fee(&self_copy)?;
fee_after.checked_sub(&fee_before)
}
pub fn set_fee(&mut self, fee: &Coin) {
self.fee = Some(fee.clone())
}
pub fn set_ttl(&mut self, ttl: Slot) {
self.ttl = Some(ttl)
}
pub fn set_validity_start_interval(&mut self, validity_start_interval: Slot) {
self.validity_start_interval = Some(validity_start_interval)
}
pub fn set_certs(&mut self, certs: &Certificates) {
self.certs = Some(certs.clone());
for cert in &certs.0 {
witness_keys_for_cert(cert, &mut self.input_types.vkeys);
};
}
pub fn set_withdrawals(&mut self, withdrawals: &Withdrawals) {
self.withdrawals = Some(withdrawals.clone());
for (withdrawal, _coin) in &withdrawals.0 {
self.input_types.vkeys.insert(withdrawal.payment_cred().to_keyhash().unwrap().clone());
};
}
pub fn get_auxiliary_data(&self) -> Option<AuxiliaryData> {
self.auxiliary_data.clone()
}
/// Set explicit auxiliary data via an AuxiliaryData object
/// It might contain some metadata plus native or Plutus scripts
pub fn set_auxiliary_data(&mut self, auxiliary_data: &AuxiliaryData) {
self.auxiliary_data = Some(auxiliary_data.clone())
}
/// Set metadata using a GeneralTransactionMetadata object
/// It will be set to the existing or new auxiliary data in this builder
pub fn set_metadata(&mut self, metadata: &GeneralTransactionMetadata) {
let mut aux = self.auxiliary_data.as_ref().cloned().unwrap_or(AuxiliaryData::new());
aux.set_metadata(metadata);
self.set_auxiliary_data(&aux);
}
/// Add a single metadatum using TransactionMetadatumLabel and TransactionMetadatum objects
/// It will be securely added to existing or new metadata in this builder
pub fn add_metadatum(&mut self, key: &TransactionMetadatumLabel, val: &TransactionMetadatum) {
let mut metadata = self.auxiliary_data.as_ref()
.map(|aux| { aux.metadata().as_ref().cloned() })
.unwrap_or(None)
.unwrap_or(GeneralTransactionMetadata::new());
metadata.insert(key, val);
self.set_metadata(&metadata);
}
/// Add a single JSON metadatum using a TransactionMetadatumLabel and a String
/// It will be securely added to existing or new metadata in this builder
pub fn add_json_metadatum(
&mut self,
key: &TransactionMetadatumLabel,
val: String,
) -> Result<(), JsError> {
self.add_json_metadatum_with_schema(key, val, MetadataJsonSchema::NoConversions)
}
/// Add a single JSON metadatum using a TransactionMetadatumLabel, a String, and a MetadataJsonSchema object
/// It will be securely added to existing or new metadata in this builder
pub fn add_json_metadatum_with_schema(
&mut self,
key: &TransactionMetadatumLabel,
val: String,
schema: MetadataJsonSchema,
) -> Result<(), JsError> {
let metadatum = encode_json_str_to_metadatum(val, schema)?;
self.add_metadatum(key, &metadatum);
Ok(())
}
/// Set explicit Mint object and the required witnesses to this builder
/// it will replace any previously existing mint and mint scripts
/// NOTE! Error will be returned in case a mint policy does not have a matching script
pub fn set_mint(&mut self, mint: &Mint, mint_scripts: &NativeScripts) -> Result<(), JsError> {
assert_required_mint_scripts(mint, Some(mint_scripts))?;
self.mint = Some(mint.clone());
self.mint_scripts = Some(mint_scripts.clone());
Ok(())
}
/// Returns a copy of the current mint state in the builder
pub fn get_mint(&self) -> Option<Mint> {
self.mint.clone()
}
/// Returns a copy of the current mint witness scripts in the builder
pub fn get_mint_scripts(&self) -> Option<NativeScripts> {
self.mint_scripts.clone()
}
fn _set_mint_asset(&mut self, policy_id: &PolicyID, policy_script: &NativeScript, mint_assets: &MintAssets) {
let mut mint = self.mint.as_ref().cloned().unwrap_or(Mint::new());
let is_new_policy = mint.insert(&policy_id, mint_assets).is_none();
let mint_scripts = {
let mut witness_scripts = self.mint_scripts.as_ref().cloned()
.unwrap_or(NativeScripts::new());
if is_new_policy {
// If policy has not been encountered before - insert the script into witnesses
witness_scripts.add(&policy_script.clone());
}
witness_scripts
};
self.mint = Some(mint);
self.mint_scripts = Some(mint_scripts.clone());
}
/// Add a mint entry to this builder using a PolicyID and MintAssets object
/// It will be securely added to existing or new Mint in this builder
/// It will replace any existing mint assets with the same PolicyID
pub fn set_mint_asset(&mut self, policy_script: &NativeScript, mint_assets: &MintAssets) {
let policy_id: PolicyID = policy_script.hash(ScriptHashNamespace::NativeScript);
self._set_mint_asset(&policy_id, policy_script, mint_assets);
}
fn _add_mint_asset(&mut self, policy_id: &PolicyID, policy_script: &NativeScript, asset_name: &AssetName, amount: Int) {
let mut asset = self.mint.as_ref()
.map(|m| { m.get(&policy_id).as_ref().cloned() })
.unwrap_or(None)
.unwrap_or(MintAssets::new());
asset.insert(asset_name, amount);
self._set_mint_asset(&policy_id, policy_script, &asset);
}
/// Add a mint entry to this builder using a PolicyID, AssetName, and Int object for amount
/// It will be securely added to existing or new Mint in this builder
/// It will replace any previous existing amount same PolicyID and AssetName
pub fn add_mint_asset(&mut self, policy_script: &NativeScript, asset_name: &AssetName, amount: Int) {
let policy_id: PolicyID = policy_script.hash(ScriptHashNamespace::NativeScript);
self._add_mint_asset(&policy_id, policy_script, asset_name, amount);
}
/// Add a mint entry together with an output to this builder
/// Using a PolicyID, AssetName, Int for amount, Address, and Coin (BigNum) objects
/// The asset will be securely added to existing or new Mint in this builder
/// A new output will be added with the specified Address, the Coin value, and the minted asset
pub fn add_mint_asset_and_output(
&mut self,
policy_script: &NativeScript,
asset_name: &AssetName,
amount: Int,
address: &Address,
output_coin: &Coin,
) -> Result<(), JsError> {
if !amount.is_positive() {
return Err(JsError::from_str("Output value must be positive!"));
}
let policy_id: PolicyID = policy_script.hash(ScriptHashNamespace::NativeScript);
self._add_mint_asset(&policy_id, policy_script, asset_name, amount.clone());
let multiasset = Mint::new_from_entry(
&policy_id,
&MintAssets::new_from_entry(asset_name, amount.clone())
).as_positive_multiasset();
self.add_output_coin_and_asset(address, output_coin, &multiasset)
}
/// Add a mint entry together with an output to this builder
/// Using a PolicyID, AssetName, Int for amount, and Address objects
/// The asset will be securely added to existing or new Mint in this builder
/// A new output will be added with the specified Address and the minted asset
/// The output will be set to contain the minimum required amount of Coin
pub fn add_mint_asset_and_output_min_required_coin(
&mut self,
policy_script: &NativeScript,
asset_name: &AssetName,
amount: Int,
address: &Address,
) -> Result<(), JsError> {
if !amount.is_positive() {
return Err(JsError::from_str("Output value must be positive!"));
}
let policy_id: PolicyID = policy_script.hash(ScriptHashNamespace::NativeScript);
self._add_mint_asset(&policy_id, policy_script, asset_name, amount.clone());
let multiasset = Mint::new_from_entry(
&policy_id,
&MintAssets::new_from_entry(asset_name, amount.clone())
).as_positive_multiasset();
self.add_output_asset_and_min_required_coin(address, &multiasset)
}
pub fn new(cfg: &TransactionBuilderConfig) -> Self {
Self {
config: cfg.clone(),
inputs: Vec::new(),
outputs: TransactionOutputs::new(),
fee: None,
ttl: None,
certs: None,
withdrawals: None,
auxiliary_data: None,
input_types: MockWitnessSet {
vkeys: BTreeSet::new(),
scripts: BTreeSet::new(),
bootstraps: BTreeSet::new(),
},
validity_start_interval: None,
mint: None,
mint_scripts: None,
}
}
/// does not include refunds or withdrawals
pub fn get_explicit_input(&self) -> Result<Value, JsError> {
self.inputs
.iter()
.try_fold(Value::zero(), |acc, ref tx_builder_input| {
acc.checked_add(&tx_builder_input.amount)
})
}
/// withdrawals and refunds
pub fn get_implicit_input(&self) -> Result<Value, JsError> {
internal_get_implicit_input(
&self.withdrawals,
&self.certs,
&self.config.pool_deposit,
&self.config.key_deposit,
)
}
/// Returns mint as tuple of (mint_value, burn_value) or two zero values
fn get_mint_as_values(&self) -> (Value, Value) {
self.mint.as_ref().map(|m| {
(Value::new_from_assets(&m.as_positive_multiasset()),
Value::new_from_assets(&m.as_negative_multiasset()))
}).unwrap_or((Value::zero(), Value::zero()))
}
fn get_total_input(&self) -> Result<Value, JsError> {
let (mint_value, burn_value) = self.get_mint_as_values();
self.get_explicit_input()?
.checked_add(&self.get_implicit_input()?)?
.checked_add(&mint_value)?
.checked_sub(&burn_value)
}
/// does not include fee
pub fn get_explicit_output(&self) -> Result<Value, JsError> {
self.outputs
.0
.iter()
.try_fold(Value::new(&to_bignum(0)), |acc, ref output| {
acc.checked_add(&output.amount())
})
}
pub fn get_deposit(&self) -> Result<Coin, JsError> {
internal_get_deposit(
&self.certs,
&self.config.pool_deposit,
&self.config.key_deposit,
)
}
pub fn get_fee_if_set(&self) -> Option<Coin> {
self.fee.clone()
}
/// Warning: this function will mutate the /fee/ field
/// Make sure to call this function last after setting all other tx-body properties
/// Editing inputs, outputs, mint, etc. after change been calculated
/// might cause a mismatch in calculated fee versus the required fee
pub fn add_change_if_needed(&mut self, address: &Address) -> Result<bool, JsError> {
let fee = match &self.fee {
None => self.min_fee(),
// generating the change output involves changing the fee
Some(_x) => {
return Err(JsError::from_str(
"Cannot calculate change if fee was explicitly specified",
))
}
}?;
let input_total = self.get_total_input()?;
let output_total = self
.get_explicit_output()?
.checked_add(&Value::new(&self.get_deposit()?))?;
use std::cmp::Ordering;
match &input_total.partial_cmp(&output_total.checked_add(&Value::new(&fee))?) {
Some(Ordering::Equal) => {
// recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
self.set_fee(&input_total.checked_sub(&output_total)?.coin());
Ok(false)
},
Some(Ordering::Less) => Err(JsError::from_str("Insufficient input in transaction")),
Some(Ordering::Greater) => {
fn has_assets(ma: Option<MultiAsset>) -> bool {
ma.map(|assets| assets.len() > 0).unwrap_or(false)
}
let change_estimator = input_total.checked_sub(&output_total)?;
if has_assets(change_estimator.multiasset()) {
fn will_adding_asset_make_output_overflow(output: &TransactionOutput, current_assets: &Assets, asset_to_add: (PolicyID, AssetName, BigNum), max_value_size: u32) -> bool {
let (policy, asset_name, value) = asset_to_add;
let mut current_assets_clone = current_assets.clone();
current_assets_clone.insert(&asset_name, &value);
let mut amount_clone = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut ma = MultiAsset::new();
ma.insert(&policy, ¤t_assets_clone);
val.set_multiasset(&ma);
amount_clone = amount_clone.checked_add(&val).unwrap();
amount_clone.to_bytes().len() > max_value_size as usize
}
fn pack_nfts_for_change(max_value_size: u32, change_address: &Address, change_estimator: &Value) -> Result<Vec<MultiAsset>, JsError> {
// we insert the entire available ADA temporarily here since that could potentially impact the size
// as it could be 1, 2 3 or 4 bytes for Coin.
let mut change_assets: Vec<MultiAsset> = Vec::new();
let mut base_coin = Value::new(&change_estimator.coin());
base_coin.set_multiasset(&MultiAsset::new());
let mut output = TransactionOutput::new(change_address, &base_coin);
// If this becomes slow on large TXs we can optimize it like the folowing
// to avoid cloning + reserializing the entire output.
// This would probably be more relevant if we use a smarter packing algorithm
// which might need to compare more size differences than greedy
//let mut bytes_used = output.to_bytes().len();
// a greedy packing is done here to avoid an exponential bin-packing
// which in most cases likely shouldn't be the difference between
// having an extra change output or not unless there are gigantic
// differences in NFT policy sizes
for (policy, assets) in change_estimator.multiasset().unwrap().0.iter() {
// for simplicity we also don't split assets within a single policy since
// you would need to have a very high amoun of assets (which add 1-36 bytes each)
// in a single policy to make a difference. In the future if this becomes an issue
// we can change that here.
// this is the other part of the optimization but we need to take into account
// the difference between CBOR encoding which can change which happens in two places:
// a) length within assets of one policy id
// b) length of the entire multiasset
// so for simplicity we will just do it the safe, naive way unless
// performance becomes an issue.
//let extra_bytes = policy.to_bytes().len() + assets.to_bytes().len() + 2 + cbor_len_diff;
//if bytes_used + extra_bytes <= max_value_size as usize {
let mut old_amount = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut next_nft = MultiAsset::new();
let asset_names = assets.keys();
let mut rebuilt_assets = Assets::new();
for n in 0..asset_names.len() {
let asset_name = asset_names.get(n);
let value = assets.get(&asset_name).unwrap();
if will_adding_asset_make_output_overflow(&output, &rebuilt_assets, (policy.clone(), asset_name.clone(), value), max_value_size) {
// if we got here, this means we will run into a overflow error,
// so we want to split into multiple outputs, for that we...
// 1. insert the current assets as they are, as this won't overflow
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
change_assets.push(output.amount.multiasset().unwrap());
// 2. create a new output with the base coin value as zero
base_coin = Value::new(&Coin::zero());
base_coin.set_multiasset(&MultiAsset::new());
output = TransactionOutput::new(change_address, &base_coin);
// 3. continue building the new output from the asset we stopped
old_amount = output.amount.clone();
val = Value::new(&Coin::zero());
next_nft = MultiAsset::new();
rebuilt_assets = Assets::new();
}
rebuilt_assets.insert(&asset_name, &value);
}
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
if output.amount.to_bytes().len() > max_value_size as usize {
output.amount = old_amount;
break;
}
}
change_assets.push(output.amount.multiasset().unwrap());
Ok(change_assets)