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
use crate::consts::*;
use crate::interpreter::Interpreter;
use fuel_asm::Word;
use fuel_tx::{CheckedTransaction, ValidationError};
use fuel_types::AssetId;
use itertools::Itertools;
use std::collections::HashMap;
use std::ops::Index;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Balance {
value: Word,
offset: usize,
}
impl Balance {
pub const fn new(value: Word, offset: usize) -> Self {
Self { value, offset }
}
pub const fn offset(&self) -> usize {
self.offset
}
pub const fn value(&self) -> Word {
self.value
}
pub fn checked_add(&mut self, value: Word) -> Option<&mut Self> {
self.value.checked_add(value).map(|v| self.value = v).map(|_| self)
}
pub fn checked_sub(&mut self, value: Word) -> Option<&mut Self> {
self.value.checked_sub(value).map(|v| self.value = v).map(|_| self)
}
}
#[derive(Debug, Default, Clone)]
pub struct RuntimeBalances {
state: HashMap<AssetId, Balance>,
}
impl From<&CheckedTransaction> for RuntimeBalances {
fn from(tx: &CheckedTransaction) -> Self {
let iter = tx.free_balances().map(|(asset, value)| (*asset, *value));
Self::try_from_iter(iter).expect(
r#"This is a bug!
A checked transaction shouldn't produce a malformed initial free balances set.
Please, file a report mentioning an incorrect transaction validation implementation that allowed a type-safe checked transaction to be created from a malformed inputs set."#)
}
}
impl RuntimeBalances {
pub fn try_from_iter<T>(iter: T) -> Result<Self, ValidationError>
where
T: IntoIterator<Item = (AssetId, Word)>,
{
iter.into_iter()
.sorted_by_key(|k| k.0)
.enumerate()
.try_fold(HashMap::new(), |mut state, (i, (asset, balance))| {
let offset = VM_MEMORY_BALANCES_OFFSET + i * (AssetId::LEN + WORD_SIZE);
state
.entry(asset)
.or_insert(Balance::new(0, offset))
.checked_add(balance)
.ok_or(ValidationError::ArithmeticOverflow)?;
Ok(state)
})
.map(|state| Self { state })
}
pub fn balance(&self, asset: &AssetId) -> Option<Word> {
self.state.get(asset).map(Balance::value)
}
fn _set_memory_balance(balance: &Balance, memory: &mut [u8]) -> Word {
let value = balance.value();
let offset = balance.offset();
let offset = offset + AssetId::LEN;
let memory = &mut memory[offset..offset + WORD_SIZE];
memory.copy_from_slice(&value.to_be_bytes());
value
}
pub fn checked_balance_add(&mut self, memory: &mut [u8], asset: &AssetId, value: Word) -> Option<Word> {
self.state
.get_mut(asset)
.and_then(|b| b.checked_add(value))
.map(|balance| Self::_set_memory_balance(balance, memory))
.or((value == 0).then(|| 0))
}
pub fn checked_balance_sub(&mut self, memory: &mut [u8], asset: &AssetId, value: Word) -> Option<Word> {
self.state
.get_mut(asset)
.and_then(|b| b.checked_sub(value))
.map(|balance| Self::_set_memory_balance(balance, memory))
.or((value == 0).then(|| 0))
}
pub fn to_vm<S>(self, vm: &mut Interpreter<S>) {
let len = vm.params().max_inputs * (AssetId::LEN + WORD_SIZE) as Word;
vm.registers[REG_SP] += len;
vm.reserve_stack(len)
.expect("consensus parameters won't allow stack overflow for VM initialization");
self.state.iter().for_each(|(asset, balance)| {
let value = balance.value();
let ofs = balance.offset();
(&mut vm.memory[ofs..ofs + AssetId::LEN]).copy_from_slice(asset.as_ref());
(&mut vm.memory[ofs + AssetId::LEN..ofs + AssetId::LEN + WORD_SIZE]).copy_from_slice(&value.to_be_bytes());
});
vm.balances = self;
}
}
impl Index<&AssetId> for RuntimeBalances {
type Output = Word;
fn index(&self, index: &AssetId) -> &Self::Output {
&self.state[index].value
}
}
#[test]
fn writes_to_memory_correctly() {
use crate::prelude::*;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
let rng = &mut StdRng::seed_from_u64(2322u64);
let mut interpreter = Interpreter::without_storage();
let base = AssetId::zeroed();
let base_balance = 950;
let assets = vec![
(rng.gen(), 10),
(rng.gen(), 25),
(rng.gen(), 50),
(base, base_balance),
(rng.gen(), 100),
];
let mut assets_sorted = assets.clone();
assets_sorted.as_mut_slice().sort_by(|a, b| a.0.cmp(&b.0));
assert_ne!(assets_sorted, assets);
let balances = assets.clone().into_iter();
RuntimeBalances::try_from_iter(balances)
.expect("failed to generate balances")
.to_vm(&mut interpreter);
let memory = interpreter.memory();
assets_sorted
.iter()
.fold(VM_MEMORY_BALANCES_OFFSET, |ofs, (asset, value)| {
assert_eq!(asset.as_ref(), &memory[ofs..ofs + AssetId::LEN]);
assert_eq!(
&value.to_be_bytes(),
&memory[ofs + AssetId::LEN..ofs + AssetId::LEN + WORD_SIZE]
);
ofs + AssetId::LEN + WORD_SIZE
});
}
#[test]
fn try_from_iter_wont_overflow() {
use crate::prelude::*;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
let rng = &mut StdRng::seed_from_u64(2322u64);
let a: AssetId = rng.gen();
let b: AssetId = rng.gen();
let c: AssetId = rng.gen();
let balances = vec![(a, u64::MAX), (b, 15), (c, 0)];
let runtime_balances = RuntimeBalances::try_from_iter(balances.clone()).expect("failed to create balance set");
balances.iter().for_each(|(asset, val)| {
let bal = runtime_balances.balance(asset).expect("failed to fetch balance");
assert_eq!(val, &bal);
});
let balances = vec![(a, u64::MAX), (b, 15), (c, 0), (b, 1)];
let balances_aggregated = vec![(a, u64::MAX), (b, 16), (c, 0)];
let runtime_balances = RuntimeBalances::try_from_iter(balances.clone()).expect("failed to create balance set");
balances_aggregated.iter().for_each(|(asset, val)| {
let bal = runtime_balances.balance(asset).expect("failed to fetch balance");
assert_eq!(val, &bal);
});
let balances = vec![(a, u64::MAX), (b, 15), (c, 0), (a, 1)];
let err = RuntimeBalances::try_from_iter(balances.clone()).expect_err("overflow set should fail");
assert_eq!(ValidationError::ArithmeticOverflow, err);
}
#[test]
fn checked_add_and_sub_works() {
use crate::prelude::*;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
let rng = &mut StdRng::seed_from_u64(2322u64);
let mut memory = Interpreter::without_storage().memory;
let asset: AssetId = rng.gen();
let balances = vec![(asset, 0)];
let mut balances = RuntimeBalances::try_from_iter(balances).expect("failed to create set");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(bal, 0);
let asset_b: AssetId = rng.gen();
assert_ne!(asset, asset_b);
let val = balances
.checked_balance_add(&mut memory, &asset_b, 0)
.expect("failed to add balance");
assert_eq!(val, 0);
assert!(balances.balance(&asset_b).is_none());
let val = balances
.checked_balance_add(&mut memory, &asset, 150)
.expect("failed to add balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, 150);
assert_eq!(bal, 150);
let val = balances
.checked_balance_add(&mut memory, &asset, 75)
.expect("failed to add balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, 225);
assert_eq!(bal, 225);
let val = balances
.checked_balance_sub(&mut memory, &asset, 30)
.expect("failed to sub balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, 195);
assert_eq!(bal, 195);
let val = balances
.checked_balance_sub(&mut memory, &asset, 120)
.expect("failed to sub balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, 75);
assert_eq!(bal, 75);
let val = balances
.checked_balance_sub(&mut memory, &asset, 70)
.expect("failed to sub balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, 5);
assert_eq!(bal, 5);
assert!(balances.checked_balance_sub(&mut memory, &asset, 10).is_none());
let val = balances
.checked_balance_add(&mut memory, &asset, u64::MAX - 5)
.expect("failed to add balance");
let bal = balances.balance(&asset).expect("failed to fetch balance");
assert_eq!(val, u64::MAX);
assert_eq!(bal, u64::MAX);
assert!(balances.checked_balance_add(&mut memory, &asset, 1).is_none());
}