forked from hyperledger-solang/solang
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrevert.rs
More file actions
491 lines (463 loc) · 16.7 KB
/
revert.rs
File metadata and controls
491 lines (463 loc) · 16.7 KB
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
// SPDX-License-Identifier: Apache-2.0
//! Releated to code that ultimately compiles to the target
//! equivalent instruction of EVM revert (0xfd).
use super::encoding::{abi_encode, create_encoder};
use super::expression::expression;
use super::Options;
use super::{
cfg::{ControlFlowGraph, Instr},
vartable::Vartable,
};
use crate::codegen::Expression;
use crate::sema::{
ast,
ast::{FormatArg, Function, Namespace, Type},
file::PathDisplay,
};
use crate::Target;
use num_bigint::{BigInt, Sign};
use parse_display::Display;
use solang_parser::pt::{CodeLocation, Loc, Loc::Codegen};
use tiny_keccak::{Hasher, Keccak};
/// Signature of `Keccak256('Error(string)')[:4]`
pub(crate) const ERROR_SELECTOR: [u8; 4] = [0x08, 0xc3, 0x79, 0xa0];
/// Signature of `Keccak256('Panic(uint256)')[:4]`
pub(crate) const PANIC_SELECTOR: [u8; 4] = [0x4e, 0x48, 0x7b, 0x71];
/// Corresponds to the error types from the Solidity language.
///
/// Marked as non-exhaustive because Solidity may add more variants in the future.
#[non_exhaustive]
#[derive(Debug, PartialEq, Clone)]
pub enum SolidityError {
/// Reverts with "empty error data"; stems from `revert()` or `require()` without string arguments.
Empty,
/// The `Error(string)` selector
String(Expression),
/// The `Panic(uint256)` selector
Panic(PanicCode),
/// User defined errors
Custom {
error_no: usize,
exprs: Vec<Expression>,
},
}
impl SolidityError {
/// Return the selector expression of the error.
pub fn selector_expression(&self, ns: &Namespace) -> Expression {
Expression::NumberLiteral {
loc: Codegen,
ty: Type::Bytes(4),
value: BigInt::from_bytes_be(Sign::Plus, &self.selector(ns)),
}
}
/// Return the selector of the error.
pub fn selector(&self, ns: &Namespace) -> [u8; 4] {
match self {
Self::Empty => unreachable!("empty return data has no selector"),
Self::String(_) => ERROR_SELECTOR,
Self::Panic(_) => PANIC_SELECTOR,
Self::Custom { error_no, .. } => {
let mut buf = [0u8; 32];
let mut hasher = Keccak::v256();
let signature =
ns.signature(&ns.errors[*error_no].name, &ns.errors[*error_no].fields);
hasher.update(signature.as_bytes());
hasher.finalize(&mut buf);
[buf[0], buf[1], buf[2], buf[3]]
}
}
}
/// ABI encode the selector and any error data.
///
/// Returns `None` if the data can't be ABI encoded.
pub(super) fn abi_encode(
&self,
loc: &Loc,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) -> Option<Expression> {
match self {
Self::Empty => None,
Self::String(expr) => {
let args = vec![self.selector_expression(ns), expr.clone()];
create_encoder(ns, false)
.const_encode(&args)
.map(|bytes| {
let size = Expression::NumberLiteral {
loc: Codegen,
ty: Type::Uint(32),
value: bytes.len().into(),
};
Expression::AllocDynamicBytes {
loc: Codegen,
ty: Type::Slice(Type::Bytes(1).into()),
size: size.into(),
initializer: bytes.into(),
}
})
.or_else(|| abi_encode(loc, args, ns, vartab, cfg, false).0.into())
}
Self::Custom { exprs, .. } => {
let mut args = exprs.to_owned();
args.insert(0, self.selector_expression(ns));
create_encoder(ns, false)
.const_encode(&args)
.map(|bytes| {
let size = Expression::NumberLiteral {
loc: Codegen,
ty: Type::Uint(32),
value: bytes.len().into(),
};
Expression::AllocDynamicBytes {
loc: Codegen,
ty: Type::Slice(Type::Bytes(1).into()),
size: size.into(),
initializer: bytes.into(),
}
})
.or_else(|| abi_encode(loc, args, ns, vartab, cfg, false).0.into())
}
Self::Panic(code) => {
let code = Expression::NumberLiteral {
loc: Codegen,
ty: Type::Uint(256),
value: (*code as u8).into(),
};
create_encoder(ns, false)
.const_encode(&[self.selector_expression(ns), code])
.map(|bytes| {
let size = Expression::NumberLiteral {
loc: Codegen,
ty: Type::Uint(32),
value: bytes.len().into(),
};
Expression::AllocDynamicBytes {
loc: Codegen,
ty: Type::Slice(Type::Bytes(1).into()),
size: size.into(),
initializer: bytes.into(),
}
})
}
}
}
}
/// Solidity `Panic` Codes. Source:
/// https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require
///
/// FIXME: Currently, not all panic variants are wired up yet in Solang:
/// * EnumCastOob
/// * StorageBytesEncodingIncorrect
/// * OutOfMemory
///
/// Tracking issue: <https://github.com/hyperledger-solang/solang/issues/1477>
#[derive(Display, Debug, PartialEq, Clone, Copy)]
#[non_exhaustive]
#[repr(u8)]
pub enum PanicCode {
Generic = 0x00,
Assertion = 0x01,
MathOverflow = 0x11,
DivisionByZero = 0x12,
EnumCastOob = 0x21,
StorageBytesEncodingIncorrect = 0x22,
EmptyArrayPop = 0x31,
ArrayIndexOob = 0x32,
OutOfMemory = 0x41,
InternalFunctionUninitialized = 0x51,
}
/// This function encodes the arguments for the assert-failure instruction
/// and inserts it in the CFG.
pub(super) fn assert_failure(
loc: &Loc,
error: SolidityError,
ns: &Namespace,
cfg: &mut ControlFlowGraph,
vartab: &mut Vartable,
) {
// On Solana, returning the encoded arguments has no effect
if ns.target == Target::Solana {
cfg.add(vartab, Instr::AssertFailure { encoded_args: None });
return;
}
let encoded_args = error.abi_encode(loc, ns, vartab, cfg);
cfg.add(vartab, Instr::AssertFailure { encoded_args })
}
pub(super) fn expr_assert(
cfg: &mut ControlFlowGraph,
args: &ast::Expression,
contract_no: usize,
func: Option<&Function>,
ns: &Namespace,
vartab: &mut Vartable,
opt: &Options,
) -> Expression {
let true_ = cfg.new_basic_block("noassert".to_owned());
let false_ = cfg.new_basic_block("doassert".to_owned());
let cond = expression(args, cfg, contract_no, func, ns, vartab, opt);
cfg.add(
vartab,
Instr::BranchCond {
cond,
true_block: true_,
false_block: false_,
},
);
cfg.set_basic_block(false_);
log_runtime_error(
opt.log_runtime_errors,
"assert failure",
args.loc(),
cfg,
vartab,
ns,
);
let error = SolidityError::Panic(PanicCode::Assertion);
assert_failure(&Codegen, error, ns, cfg, vartab);
cfg.set_basic_block(true_);
Expression::Poison
}
pub(super) fn require(
cfg: &mut ControlFlowGraph,
args: &[ast::Expression],
contract_no: usize,
func: Option<&Function>,
ns: &Namespace,
vartab: &mut Vartable,
opt: &Options,
loc: Loc,
) -> Expression {
let true_ = cfg.new_basic_block("noassert".to_owned());
let false_ = cfg.new_basic_block("doassert".to_owned());
let cond = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
cfg.add(
vartab,
Instr::BranchCond {
cond,
true_block: true_,
false_block: false_,
},
);
cfg.set_basic_block(false_);
let expr = args
.get(1)
.map(|s| expression(s, cfg, contract_no, func, ns, vartab, opt));
// On Solana and Polkadot, print the reason
if opt.log_runtime_errors && (ns.target == Target::Solana || ns.target.is_polkadot()) {
if let Some(expr) = expr.clone() {
let prefix = b"runtime_error: ";
let error_string = format!(
" require condition failed in {},\n",
ns.loc_to_string(PathDisplay::Filename, &expr.loc())
);
let print_expr = Expression::FormatString {
loc: Loc::Codegen,
args: vec![
(
FormatArg::StringLiteral,
Expression::BytesLiteral {
loc: Loc::Codegen,
ty: Type::Bytes(prefix.len() as u8),
value: prefix.to_vec(),
},
),
(FormatArg::Default, expr),
(
FormatArg::StringLiteral,
Expression::BytesLiteral {
loc: Loc::Codegen,
ty: Type::Bytes(error_string.len() as u8),
value: error_string.as_bytes().to_vec(),
},
),
],
};
cfg.add(vartab, Instr::Print { expr: print_expr });
} else {
log_runtime_error(
opt.log_runtime_errors,
"require condition failed",
loc,
cfg,
vartab,
ns,
);
}
}
let error = expr
.map(SolidityError::String)
.unwrap_or(SolidityError::Empty);
assert_failure(&Codegen, error, ns, cfg, vartab);
cfg.set_basic_block(true_);
Expression::Poison
}
pub(super) fn revert(
args: &[ast::Expression],
error_no: &Option<usize>,
cfg: &mut ControlFlowGraph,
contract_no: usize,
func: Option<&Function>,
ns: &Namespace,
vartab: &mut Vartable,
opt: &Options,
loc: &Loc,
) {
let exprs = args
.iter()
.map(|s| expression(s, cfg, contract_no, func, ns, vartab, opt))
.collect::<Vec<_>>();
if opt.log_runtime_errors {
match (error_no, exprs.first()) {
// In the case of Error(string), we can print the reason
(None, Some(expr)) => {
let prefix = b"runtime_error: ";
let error_string = format!(
" revert encountered in {},\n",
ns.loc_to_string(PathDisplay::Filename, loc)
);
let print_expr = Expression::FormatString {
loc: Codegen,
args: vec![
(
FormatArg::StringLiteral,
Expression::BytesLiteral {
loc: Codegen,
ty: Type::Bytes(prefix.len() as u8),
value: prefix.to_vec(),
},
),
(FormatArg::Default, expr.clone()),
(
FormatArg::StringLiteral,
Expression::BytesLiteral {
loc: Codegen,
ty: Type::Bytes(error_string.len() as u8),
value: error_string.as_bytes().to_vec(),
},
),
],
};
cfg.add(vartab, Instr::Print { expr: print_expr });
}
// Else: Not all fields might be formattable, just print the error type
_ => {
let error_ty = error_no
.map(|n| ns.errors[n].name.as_str())
.unwrap_or("unspecified");
let reason = format!("{} revert encountered", error_ty);
log_runtime_error(opt.log_runtime_errors, &reason, *loc, cfg, vartab, ns);
}
}
}
let error = match (*error_no, exprs.first()) {
// Having an error number requires a custom error
(Some(error_no), _) => SolidityError::Custom { error_no, exprs },
// No error number but an expression requires Error(String)
(None, Some(expr)) => SolidityError::String(expr.clone()),
// No error number and no data means just "revert();" without any reason
(None, None) => SolidityError::Empty,
};
assert_failure(&Codegen, error, ns, cfg, vartab);
}
pub(crate) fn log_runtime_error(
report_error: bool,
reason: &str,
reason_loc: Loc,
cfg: &mut ControlFlowGraph,
vartab: &mut Vartable,
ns: &Namespace,
) {
if report_error {
let error_with_loc = error_msg_with_loc(ns, reason.to_string(), Some(reason_loc));
let expr = string_to_expr(error_with_loc);
cfg.add(vartab, Instr::Print { expr });
}
}
pub(crate) fn error_msg_with_loc(ns: &Namespace, error: String, loc: Option<Loc>) -> String {
match &loc {
Some(loc @ Loc::File(..)) => {
let loc_from_file = ns.loc_to_string(PathDisplay::Filename, loc);
format!("runtime_error: {error} in {loc_from_file},\n")
}
_ => error + ",\n",
}
}
pub(super) fn string_to_expr(string: String) -> Expression {
Expression::FormatString {
loc: Loc::Codegen,
args: vec![(
FormatArg::StringLiteral,
Expression::BytesLiteral {
loc: Loc::Codegen,
ty: Type::Bytes(string.len() as u8),
value: string.as_bytes().to_vec(),
},
)],
}
}
#[cfg(test)]
mod tests {
use crate::{
codegen::{
revert::{PanicCode, SolidityError, ERROR_SELECTOR, PANIC_SELECTOR},
Expression,
},
sema::ast::{ErrorDecl, Namespace, Parameter, Type},
Target,
};
#[test]
fn panic_code_as_byte() {
assert_eq!(0x00, PanicCode::Generic as u8);
assert_eq!(0x01, PanicCode::Assertion as u8);
assert_eq!(0x11, PanicCode::MathOverflow as u8);
assert_eq!(0x12, PanicCode::DivisionByZero as u8);
assert_eq!(0x21, PanicCode::EnumCastOob as u8);
assert_eq!(0x22, PanicCode::StorageBytesEncodingIncorrect as u8);
assert_eq!(0x31, PanicCode::EmptyArrayPop as u8);
assert_eq!(0x32, PanicCode::ArrayIndexOob as u8);
assert_eq!(0x41, PanicCode::OutOfMemory as u8);
assert_eq!(0x51, PanicCode::InternalFunctionUninitialized as u8);
}
#[test]
fn default_error_selector_expression() {
let ns = Namespace::new(Target::default_polkadot());
assert_eq!(
ERROR_SELECTOR,
SolidityError::String(Expression::Poison).selector(&ns),
);
assert_eq!(
PANIC_SELECTOR,
SolidityError::Panic(PanicCode::Generic).selector(&ns),
);
}
/// Error selector calculation uses the same signature algorithm used for message selectors.
/// Tests the error selector calculation to be correct against two examples:
/// - `error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);`
/// - `error Unauthorized();`
#[test]
fn custom_error_selector_expression() {
let mut ns = Namespace::new(Target::default_polkadot());
ns.errors = vec![
ErrorDecl {
name: "Unauthorized".to_string(),
..Default::default()
},
ErrorDecl {
name: "ERC20InsufficientBalance".to_string(),
fields: vec![
Parameter::new_default(Type::Address(false)),
Parameter::new_default(Type::Uint(256)),
Parameter::new_default(Type::Uint(256)),
],
..Default::default()
},
];
let exprs = vec![Expression::Poison];
let expected_selector = SolidityError::Custom { error_no: 0, exprs }.selector(&ns);
assert_eq!([0x82, 0xb4, 0x29, 0x00], expected_selector);
let exprs = vec![Expression::Poison];
let expected_selector = SolidityError::Custom { error_no: 1, exprs }.selector(&ns);
assert_eq!([0xe4, 0x50, 0xd3, 0x8c], expected_selector);
}
}