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
use crate::consts::*;
use fuel_asm::Opcode;
use fuel_crypto::PublicKey;
use fuel_types::bytes::{self, SizedBytes};
use fuel_types::{Address, AssetId, Bytes32, Salt, Word};
#[cfg(feature = "std")]
use fuel_crypto::{Message, SecretKey, Signature};
#[cfg(feature = "std")]
use std::io;
use alloc::vec::Vec;
use core::mem;
mod fee;
mod internals;
mod metadata;
mod offset;
mod repr;
mod types;
mod validation;
#[cfg(feature = "std")]
mod id;
#[cfg(feature = "std")]
mod txio;
pub mod consensus_parameters;
pub use consensus_parameters::ConsensusParameters;
pub use fee::TransactionFee;
pub use metadata::Metadata;
pub use repr::TransactionRepr;
pub use types::{Input, InputRepr, Output, OutputRepr, StorageSlot, TxPointer, UtxoId, Witness};
pub use validation::ValidationError;
pub type TxId = Bytes32;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Transaction {
Script {
gas_price: Word,
gas_limit: Word,
maturity: Word,
receipts_root: Bytes32,
script: Vec<u8>,
script_data: Vec<u8>,
inputs: Vec<Input>,
outputs: Vec<Output>,
witnesses: Vec<Witness>,
metadata: Option<Metadata>,
},
Create {
gas_price: Word,
gas_limit: Word,
maturity: Word,
bytecode_length: Word,
bytecode_witness_index: u8,
salt: Salt,
storage_slots: Vec<StorageSlot>,
inputs: Vec<Input>,
outputs: Vec<Output>,
witnesses: Vec<Witness>,
metadata: Option<Metadata>,
},
}
impl Default for Transaction {
fn default() -> Self {
use alloc::vec;
let script = Opcode::RET(0x10).to_bytes().to_vec();
Transaction::script(
0,
ConsensusParameters::DEFAULT.max_gas_per_tx,
0,
script,
vec![],
vec![],
vec![],
vec![],
)
}
}
impl Transaction {
pub const fn script(
gas_price: Word,
gas_limit: Word,
maturity: Word,
script: Vec<u8>,
script_data: Vec<u8>,
inputs: Vec<Input>,
outputs: Vec<Output>,
witnesses: Vec<Witness>,
) -> Self {
let receipts_root = Bytes32::zeroed();
Self::Script {
gas_price,
gas_limit,
maturity,
receipts_root,
script,
script_data,
inputs,
outputs,
witnesses,
metadata: None,
}
}
pub fn create(
gas_price: Word,
gas_limit: Word,
maturity: Word,
bytecode_witness_index: u8,
salt: Salt,
storage_slots: Vec<StorageSlot>,
inputs: Vec<Input>,
outputs: Vec<Output>,
witnesses: Vec<Witness>,
) -> Self {
let bytecode_length = witnesses
.get(bytecode_witness_index as usize)
.map(|witness| witness.as_ref().len() as Word / 4)
.unwrap_or(0);
Self::Create {
gas_price,
gas_limit,
maturity,
bytecode_length,
bytecode_witness_index,
salt,
storage_slots,
inputs,
outputs,
witnesses,
metadata: None,
}
}
pub fn input_asset_ids(&self) -> impl Iterator<Item = &AssetId> {
self.inputs().iter().filter_map(|input| match input {
Input::CoinPredicate { asset_id, .. } | Input::CoinSigned { asset_id, .. } => {
Some(asset_id)
}
_ => None,
})
}
pub fn input_asset_ids_unique(&self) -> impl Iterator<Item = &AssetId> {
use itertools::Itertools;
let asset_ids = self.input_asset_ids();
#[cfg(feature = "std")]
let asset_ids = asset_ids.unique();
#[cfg(not(feature = "std"))]
let asset_ids = asset_ids.sorted().dedup();
asset_ids
}
#[cfg(feature = "std")]
pub fn input_contracts(&self) -> impl Iterator<Item = &fuel_types::ContractId> {
use itertools::Itertools;
self.inputs()
.iter()
.filter_map(|input| match input {
Input::Contract { contract_id, .. } => Some(contract_id),
_ => None,
})
.unique()
}
#[cfg(feature = "std")]
pub fn check_predicate_owners(&self) -> bool {
self.inputs()
.iter()
.filter_map(|i| match i {
Input::CoinPredicate {
owner, predicate, ..
} => Some((owner, predicate)),
_ => None,
})
.fold(true, |result, (owner, predicate)| {
result && Input::is_predicate_owner_valid(owner, predicate)
})
}
#[cfg(feature = "std")]
pub fn check_predicate_owner(&self, idx: usize) -> bool {
matches!(self.inputs().get(idx),
Some(Input::CoinPredicate {
owner, predicate, ..
}) if Input::is_predicate_owner_valid(owner, predicate)
)
}
pub const fn gas_price(&self) -> Word {
match self {
Self::Script { gas_price, .. } => *gas_price,
Self::Create { gas_price, .. } => *gas_price,
}
}
pub fn set_gas_price(&mut self, price: Word) {
match self {
Self::Script { gas_price, .. } => *gas_price = price,
Self::Create { gas_price, .. } => *gas_price = price,
}
}
pub const fn gas_limit(&self) -> Word {
match self {
Self::Script { gas_limit, .. } => *gas_limit,
Self::Create { gas_limit, .. } => *gas_limit,
}
}
pub fn set_gas_limit(&mut self, limit: Word) {
match self {
Self::Script { gas_limit, .. } => *gas_limit = limit,
Self::Create { gas_limit, .. } => *gas_limit = limit,
}
}
pub const fn maturity(&self) -> Word {
match self {
Self::Script { maturity, .. } => *maturity,
Self::Create { maturity, .. } => *maturity,
}
}
pub fn set_maturity(&mut self, mat: Word) {
match self {
Self::Script { maturity, .. } => *maturity = mat,
Self::Create { maturity, .. } => *maturity = mat,
}
}
pub const fn is_script(&self) -> bool {
matches!(self, Self::Script { .. })
}
pub const fn metadata(&self) -> Option<&Metadata> {
match self {
Self::Script { metadata, .. } => metadata.as_ref(),
Self::Create { metadata, .. } => metadata.as_ref(),
}
}
pub const fn salt(&self) -> Option<&Salt> {
match self {
Transaction::Create { salt, .. } => Some(salt),
Transaction::Script { .. } => None,
}
}
pub fn inputs(&self) -> &[Input] {
match self {
Self::Script { inputs, .. } => inputs.as_slice(),
Self::Create { inputs, .. } => inputs.as_slice(),
}
}
pub fn outputs(&self) -> &[Output] {
match self {
Self::Script { outputs, .. } => outputs.as_slice(),
Self::Create { outputs, .. } => outputs.as_slice(),
}
}
pub fn witnesses(&self) -> &[Witness] {
match self {
Self::Script { witnesses, .. } => witnesses.as_slice(),
Self::Create { witnesses, .. } => witnesses.as_slice(),
}
}
pub fn set_witnesses(&mut self, new_witnesses: Vec<Witness>) {
match self {
Self::Script { witnesses, .. } => *witnesses = new_witnesses,
Self::Create { witnesses, .. } => *witnesses = new_witnesses,
}
}
pub const fn receipts_root(&self) -> Option<&Bytes32> {
match self {
Self::Script { receipts_root, .. } => Some(receipts_root),
_ => None,
}
}
pub fn set_receipts_root(&mut self, root: Bytes32) -> Option<Bytes32> {
match self {
Self::Script { receipts_root, .. } => Some(mem::replace(receipts_root, root)),
_ => None,
}
}
pub fn add_unsigned_coin_input(
&mut self,
utxo_id: UtxoId,
owner: &PublicKey,
amount: Word,
asset_id: AssetId,
tx_pointer: TxPointer,
maturity: Word,
) {
let owner = Input::owner(owner);
let witness_index = self.witnesses().len() as u8;
let input = Input::coin_signed(
utxo_id,
owner,
amount,
asset_id,
tx_pointer,
witness_index,
maturity,
);
self._add_witness(Witness::default());
self._add_input(input);
}
pub fn add_unsigned_message_input(
&mut self,
sender: Address,
recipient: Address,
nonce: Word,
owner: &PublicKey,
amount: Word,
data: Vec<u8>,
) {
let owner = Input::owner(owner);
let message_id =
Input::compute_message_id(&sender, &recipient, nonce, &owner, amount, &data);
let witness_index = self.witnesses().len() as u8;
let input = Input::message_signed(
message_id,
sender,
recipient,
amount,
nonce,
owner,
witness_index,
data,
);
self._add_witness(Witness::default());
self._add_input(input);
}
#[cfg(feature = "std")]
pub fn sign_inputs(&mut self, secret: &SecretKey) {
use itertools::Itertools;
let pk = PublicKey::from(secret);
let pk = Input::owner(&pk);
let id = self.id();
let message = unsafe { Message::as_ref_unchecked(id.as_ref()) };
let signature = Signature::sign(secret, message);
let (inputs, witnesses) = match self {
Self::Script {
inputs, witnesses, ..
} => (inputs, witnesses),
Self::Create {
inputs, witnesses, ..
} => (inputs, witnesses),
};
inputs
.iter()
.filter_map(|input| match input {
Input::CoinSigned {
owner,
witness_index,
..
}
| Input::MessageSigned {
owner,
witness_index,
..
} if owner == &pk => Some(*witness_index as usize),
_ => None,
})
.dedup()
.for_each(|w| {
if let Some(w) = witnesses.get_mut(w) {
*w = signature.as_ref().into();
}
});
}
pub fn metered_bytes_size(&self) -> usize {
let witness_data = self
.witnesses()
.iter()
.map(|w| w.serialized_size())
.sum::<usize>();
self.serialized_size() - witness_data
}
pub(crate) fn _inputs_mut(&mut self) -> &mut [Input] {
match self {
Self::Script { inputs, .. } => inputs.as_mut_slice(),
Self::Create { inputs, .. } => inputs.as_mut_slice(),
}
}
pub(crate) fn _outputs_mut(&mut self) -> &mut [Output] {
match self {
Self::Script { outputs, .. } => outputs.as_mut_slice(),
Self::Create { outputs, .. } => outputs.as_mut_slice(),
}
}
pub(crate) fn _witnesses_mut(&mut self) -> &mut [Witness] {
match self {
Self::Script { witnesses, .. } => witnesses.as_mut_slice(),
Self::Create { witnesses, .. } => witnesses.as_mut_slice(),
}
}
#[cfg(feature = "std")]
pub fn prepare_init_script(&mut self) -> io::Result<&mut Self> {
self._outputs_mut()
.iter_mut()
.try_for_each(|o| o.prepare_init_script())?;
Ok(self)
}
pub fn prepare_init_predicate(&mut self) -> &mut Self {
self._inputs_mut()
.iter_mut()
.for_each(|i| i.prepare_init_predicate());
self._outputs_mut()
.iter_mut()
.for_each(|o| o.prepare_init_predicate());
self
}
pub fn script_len(&self) -> Option<usize> {
match self {
Transaction::Script { script, .. } => Some(script.len()),
Transaction::Create { .. } => None,
}
}
pub fn script_data_len(&self) -> Option<usize> {
match self {
Transaction::Script { script_data, .. } => Some(script_data.len()),
Transaction::Create { .. } => None,
}
}
pub const fn bytecode_length(&self) -> Option<Word> {
match self {
Transaction::Create {
bytecode_length, ..
} => Some(*bytecode_length),
Transaction::Script { .. } => None,
}
}
pub const fn bytecode_witness_index(&self) -> Option<u8> {
match self {
Transaction::Create {
bytecode_witness_index,
..
} => Some(*bytecode_witness_index),
Transaction::Script { .. } => None,
}
}
pub fn storage_slots(&self) -> Option<&[StorageSlot]> {
match self {
Transaction::Create { storage_slots, .. } => Some(storage_slots),
Transaction::Script { .. } => None,
}
}
pub const fn salt_offset(&self) -> Option<usize> {
match self {
Transaction::Create { .. } => Some(TRANSACTION_CREATE_SALT_OFFSET),
Transaction::Script { .. } => None,
}
}
pub fn storage_slot_offset(&self, idx: usize) -> Option<usize> {
match self {
Transaction::Create { storage_slots, .. } if idx < storage_slots.len() => {
Some(TRANSACTION_CREATE_FIXED_SIZE + idx * StorageSlot::SLOT_SIZE)
}
_ => None,
}
}
pub fn find_output_contract(&self, input: usize) -> Option<(usize, &Output)> {
self.outputs().iter().enumerate().find(|(_idx, o)| {
matches!(o, Output::Contract {
input_index, ..
} if *input_index as usize == input)
})
}
}
impl SizedBytes for Transaction {
fn serialized_size(&self) -> usize {
let inputs = self
.inputs()
.iter()
.map(|i| i.serialized_size())
.sum::<usize>();
let outputs = self
.outputs()
.iter()
.map(|o| o.serialized_size())
.sum::<usize>();
let witnesses = self
.witnesses()
.iter()
.map(|w| w.serialized_size())
.sum::<usize>();
let n = match self {
Self::Script {
script,
script_data,
..
} => {
TRANSACTION_SCRIPT_FIXED_SIZE
+ bytes::padded_len(script.as_slice())
+ bytes::padded_len(script_data.as_slice())
}
Self::Create { storage_slots, .. } => {
TRANSACTION_CREATE_FIXED_SIZE + storage_slots.len() * StorageSlot::SLOT_SIZE
}
};
n + inputs + outputs + witnesses
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn metered_data_excludes_witnesses() {
let script_with_no_witnesses = Transaction::Script {
gas_price: 0,
gas_limit: 0,
maturity: 0,
receipts_root: Default::default(),
script: vec![],
script_data: vec![],
inputs: vec![],
outputs: vec![],
witnesses: vec![],
metadata: None,
};
let script_with_witnesses = Transaction::Script {
gas_price: 0,
gas_limit: 0,
maturity: 0,
receipts_root: Default::default(),
script: vec![],
script_data: vec![],
inputs: vec![],
outputs: vec![],
witnesses: vec![[0u8; 64].to_vec().into()],
metadata: None,
};
assert_eq!(
script_with_witnesses.metered_bytes_size(),
script_with_no_witnesses.metered_bytes_size()
);
let create_with_no_witnesses = Transaction::Create {
gas_price: 0,
gas_limit: 0,
maturity: 0,
bytecode_length: 0,
bytecode_witness_index: 0,
salt: Default::default(),
storage_slots: vec![],
inputs: vec![],
outputs: vec![],
witnesses: vec![],
metadata: None,
};
let create_with_witnesses = Transaction::Create {
gas_price: 0,
gas_limit: 0,
maturity: 0,
bytecode_length: 0,
bytecode_witness_index: 0,
salt: Default::default(),
storage_slots: vec![],
inputs: vec![],
outputs: vec![],
witnesses: vec![[0u8; 64].to_vec().into()],
metadata: None,
};
assert_eq!(
create_with_witnesses.metered_bytes_size(),
create_with_no_witnesses.metered_bytes_size()
);
}
}