| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624 |
- // SPDX-License-Identifier: Apache-2.0
- use crate::build_solidity_with_overflow_check;
- use crate::{build_solidity, BorshToken};
- use num_bigint::{BigInt, BigUint, RandBigInt, ToBigInt};
- use num_traits::{One, ToPrimitive, Zero};
- use rand::seq::SliceRandom;
- use rand::Rng;
- use std::ops::BitAnd;
- use std::ops::Div;
- use std::ops::Mul;
- use std::ops::Rem;
- use std::ops::Shl;
- use std::ops::Shr;
- use std::ops::Sub;
- use std::ops::{Add, BitOr, BitXor, MulAssign, ShlAssign, ShrAssign, SubAssign};
- #[test]
- #[should_panic]
- fn assert_false() {
- // without a working assert, this is not going to work
- let mut vm = build_solidity(
- r#"
- contract foo {
- function assert_fails() public {
- require(false, "humpty-dumpty");
- }
- }"#,
- );
- vm.constructor(&[]);
- vm.function("assert_fails", &[]);
- }
- #[test]
- fn assert_true() {
- // without a working assert, this is not going to work
- let mut vm = build_solidity(
- r#"
- contract foo {
- function assert_fails() public {
- require(true, "humpty-dumpty");
- }
- }"#,
- );
- vm.constructor(&[]);
- vm.function("assert_fails", &[]);
- }
- #[test]
- fn boolean() {
- // we need to test: literals
- // passing address around
- // abi encoding/decoding address
- // comparing address to another
- let mut vm = build_solidity(
- r#"
- contract foo {
- function return_true() public returns (bool) {
- return true;
- }
- function return_false() public returns (bool) {
- return false;
- }
- function true_arg(bool b) public {
- assert(b);
- }
- function false_arg(bool b) public {
- assert(!b);
- }
- }"#,
- );
- vm.constructor(&[]);
- let returns = vm.function("return_true", &[]).unwrap();
- assert_eq!(returns, BorshToken::Bool(true));
- let returns = vm.function("return_false", &[]).unwrap();
- assert_eq!(returns, BorshToken::Bool(false));
- vm.function("true_arg", &[BorshToken::Bool(true)]);
- vm.function("false_arg", &[BorshToken::Bool(false)]);
- }
- #[test]
- fn address() {
- // we need to test: literals
- // passing address around
- // abi encoding/decoding address
- // comparing address to another
- let mut vm = build_solidity(
- r#"
- contract foo {
- function return_address() public returns (address) {
- return address'CXQw5tfeRKKzV4hk6PcdyKyANSvFxoZCKwHkVXAhAYSJ';
- }
- function address_arg(address a) public {
- assert(a == address'66Eh1STPJgabub73TP8YbN7VNCwjaVTEJGHRxCLeBJ4A');
- }
- }"#,
- );
- vm.constructor(&[]);
- let returns = vm.function("return_address", &[]).unwrap();
- assert_eq!(
- returns,
- BorshToken::Address([
- 171, 59, 10, 127, 211, 122, 217, 123, 53, 213, 159, 40, 54, 36, 50, 52, 196, 144, 17,
- 226, 97, 168, 69, 213, 79, 14, 6, 232, 165, 44, 58, 31
- ]),
- );
- vm.function(
- "address_arg",
- &[BorshToken::Address([
- 75, 161, 209, 89, 47, 84, 50, 13, 23, 127, 94, 21, 50, 249, 250, 185, 117, 49, 186,
- 134, 82, 130, 112, 97, 218, 24, 157, 198, 40, 105, 118, 27,
- ])],
- );
- }
- #[test]
- fn test_enum() {
- // we need to test enum literals
- // abi encoding/decode literals
- // comparing enums
- let mut vm = build_solidity(
- r#"
- contract foo {
- enum bar { bar0, bar1, bar2, bar3, bar4, bar5, bar6, bar7, bar8, bar9, bar10 }
- function return_enum() public returns (bar) {
- return bar.bar9;
- }
- function enum_arg(bar a) public {
- assert(a == bar.bar6);
- }
- }"#,
- );
- vm.constructor(&[]);
- let returns = vm.function("return_enum", &[]).unwrap();
- assert_eq!(
- returns,
- BorshToken::Uint {
- width: 8,
- value: BigInt::from(9u8)
- }
- );
- vm.function(
- "enum_arg",
- &[BorshToken::Uint {
- width: 8,
- value: BigInt::from(6u8),
- }],
- );
- }
- #[test]
- fn bytes() {
- let mut rng = rand::thread_rng();
- for width in 1..32 {
- let src = r#"
- contract test {
- function return_literal() public returns (bytes7) {
- return hex"01020304050607";
- }
- function return_arg(bytes7 x) public returns (bytes7) {
- return x;
- }
- function or(bytesN a, bytesN b) public returns (bytesN) {
- return a | b;
- }
- function and(bytesN a, bytesN b) public returns (bytesN) {
- return a & b;
- }
- function xor(bytesN a, bytesN b) public returns (bytesN) {
- return a ^ b;
- }
- function shift_left(bytesN a, uint32 r) public returns (bytesN) {
- return a << r;
- }
- function shift_right(bytesN a, uint32 r) public returns (bytesN) {
- return a >> r;
- }
- }"#
- .replace("bytesN", &format!("bytes{width}"));
- let mut vm = build_solidity(&src);
- vm.constructor(&[]);
- let returns = vm.function("return_literal", &[]).unwrap();
- assert_eq!(
- returns,
- BorshToken::uint8_fixed_array(vec![1, 2, 3, 4, 5, 6, 7])
- );
- let returns = vm
- .function(
- "return_arg",
- &[BorshToken::FixedBytes(vec![1, 2, 3, 4, 5, 6, 7])],
- )
- .unwrap();
- assert_eq!(
- returns,
- BorshToken::uint8_fixed_array(vec![1, 2, 3, 4, 5, 6, 7])
- );
- for _ in 0..10 {
- let mut a = Vec::new();
- let mut b = Vec::new();
- a.resize(width, 0);
- b.resize(width, 0);
- rng.fill(&mut a[..]);
- rng.fill(&mut b[..]);
- let or = vm
- .function(
- "or",
- &[
- BorshToken::FixedBytes(a.to_vec()),
- BorshToken::FixedBytes(b.to_vec()),
- ],
- )
- .unwrap();
- let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a | b).collect();
- println!(
- "{} | {} = {}",
- hex::encode(&a),
- hex::encode(&b),
- hex::encode(&res)
- );
- assert_eq!(or, BorshToken::uint8_fixed_array(res));
- let and = vm
- .function(
- "and",
- &[
- BorshToken::FixedBytes(a.to_vec()),
- BorshToken::FixedBytes(b.to_vec()),
- ],
- )
- .unwrap();
- let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a & b).collect();
- assert_eq!(and, BorshToken::uint8_fixed_array(res));
- let xor = vm
- .function(
- "xor",
- &[
- BorshToken::FixedBytes(a.to_vec()),
- BorshToken::FixedBytes(b.to_vec()),
- ],
- )
- .unwrap();
- let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a ^ b).collect();
- assert_eq!(xor, BorshToken::uint8_fixed_array(res));
- let r = rng.gen::<u32>() % (width as u32 * 8);
- println!("w = {width} r = {r}");
- let shl = vm
- .function(
- "shift_left",
- &[
- BorshToken::FixedBytes(a.to_vec()),
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = (BigUint::from_bytes_be(&a) << r).to_bytes_be();
- while res.len() > width {
- res.remove(0);
- }
- while res.len() < width {
- res.insert(0, 0);
- }
- assert_eq!(shl, BorshToken::uint8_fixed_array(res));
- let shr = vm
- .function(
- "shift_right",
- &[
- BorshToken::FixedBytes(a.to_vec()),
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = (BigUint::from_bytes_be(&a) >> r).to_bytes_be();
- while res.len() < width {
- res.insert(0, 0);
- }
- assert_eq!(shr, BorshToken::uint8_fixed_array(res));
- }
- }
- }
- #[test]
- fn uint() {
- let mut rng = rand::thread_rng();
- for width in (8u16..=256).step_by(8) {
- let src = r#"
- contract test {
- function pass(uintN a) public returns (uintN) {
- print("x:{:x}".format(uint64(a)));
- return 0x7f;
- }
- function add(uintN a, uintN b) public returns (uintN) {
- return a + b;
- }
- function sub(uintN a, uintN b) public returns (uintN) {
- return a - b;
- }
- function mul(uintN a, uintN b) public returns (uintN) {
- unchecked {
- return a * b;
- }
- }
- function div(uintN a, uintN b) public returns (uintN) {
- return a / b;
- }
- function mod(uintN a, uintN b) public returns (uintN) {
- return a % b;
- }
- function pow(uintN a, uintN b) public returns (uintN) {
- unchecked {
- return a ** b;
- }
- }
- function or(uintN a, uintN b) public returns (uintN) {
- return a | b;
- }
- function and(uintN a, uintN b) public returns (uintN) {
- return a & b;
- }
- function xor(uintN a, uintN b) public returns (uintN) {
- return a ^ b;
- }
- function shift_left(uintN a, uint32 r) public returns (uintN) {
- return a << r;
- }
- function shift_right(uintN a, uint32 r) public returns (uintN) {
- return a >> r;
- }
- }"#
- .replace("uintN", &format!("uint{width}"));
- let mut vm = build_solidity(&src);
- vm.constructor(&[]);
- println!("width:{width}");
- let returned_width = width.next_power_of_two();
- for _ in 0..10 {
- let mut a = rng.gen_biguint(width as u64);
- let mut b = rng.gen_biguint(width as u64);
- if b > a {
- std::mem::swap(&mut a, &mut b);
- }
- let res = vm.function(
- "pass",
- &[BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- }],
- );
- println!("{a:x} = {res:?} o");
- let add = vm
- .function(
- "add",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().add(&b);
- truncate_biguint(&mut res, width);
- println!("{a:x} + {b:x} = {add:?} or {res:x}");
- assert_eq!(
- add,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let sub = vm
- .function(
- "sub",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().sub(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- sub,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let mul = vm
- .function(
- "mul",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().mul(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- mul,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- if let Some(mut n) = b.to_u32() {
- n %= 65536;
- let pow = vm
- .function(
- "pow",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: BigInt::from(n),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().pow(n);
- truncate_biguint(&mut res, width);
- assert_eq!(
- pow,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- }
- if b != BigUint::zero() {
- let div = vm
- .function(
- "div",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().div(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- div,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let add = vm
- .function(
- "mod",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().rem(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- add,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- }
- let or = vm
- .function(
- "or",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitor(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- or,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let and = vm
- .function(
- "and",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitand(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- and,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let xor = vm
- .function(
- "xor",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width,
- value: b.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitxor(&b);
- truncate_biguint(&mut res, width);
- assert_eq!(
- xor,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let r = rng.gen::<u32>() % (width as u32);
- let shl = vm
- .function(
- "shift_left",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone();
- res.shl_assign(r);
- truncate_biguint(&mut res, width);
- assert_eq!(
- shl,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- let shr = vm
- .function(
- "shift_right",
- &[
- BorshToken::Uint {
- width,
- value: a.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone();
- res.shr_assign(&r);
- truncate_biguint(&mut res, width);
- assert_eq!(
- shr,
- BorshToken::Uint {
- width: returned_width,
- value: res.to_bigint().unwrap(),
- }
- );
- }
- }
- }
- fn truncate_biguint(n: &mut BigUint, width: u16) {
- let mut bytes = n.to_bytes_le();
- let byte_width = (width / 8) as usize;
- if bytes.len() < byte_width {
- return;
- }
- for item in bytes.iter_mut().skip(byte_width) {
- *item = 0;
- }
- *n = BigUint::from_bytes_le(&bytes);
- }
- #[test]
- fn test_power_overflow_boundaries() {
- for width in (8u16..=256).step_by(8) {
- let src = r#"
- contract test {
- function pow(uintN a, uintN b) public returns (uintN) {
- return a ** b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity_with_overflow_check(&src, true);
- contract.constructor(&[]);
- let return_value = contract
- .function(
- "pow",
- &[
- BorshToken::Uint {
- width,
- value: BigInt::from(2u8),
- },
- BorshToken::Uint {
- width,
- value: BigInt::from(width - 1),
- },
- ],
- )
- .unwrap();
- let res = BigUint::from(2_u32).pow((width - 1) as u32);
- assert_eq!(
- return_value,
- BorshToken::Uint {
- width: width.next_power_of_two(),
- value: res.to_bigint().unwrap(),
- }
- );
- let sesa = contract.function_must_fail(
- "pow",
- &[
- BorshToken::Uint {
- width,
- value: BigInt::from(2u8),
- },
- BorshToken::Uint {
- width,
- value: BigInt::from(width + 1),
- },
- ],
- );
- assert_ne!(sesa, Ok(0));
- }
- }
- #[test]
- fn test_overflow_boundaries() {
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function mul(intN a, intN b) public returns (intN) {
- return a * b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity_with_overflow_check(&src, true);
- // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1]. We generate these boundaries:
- let mut upper_boundary: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- upper_boundary.sub_assign(1);
- let mut lower_boundary: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- lower_boundary.mul_assign(-1);
- let second_op = BigInt::from(1_u32);
- let returned_width = (width as u16).next_power_of_two();
- // Multiply the boundaries by 1.
- contract.constructor(&[]);
- let return_value = contract
- .function(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: upper_boundary.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: second_op.clone(),
- },
- ],
- )
- .unwrap();
- assert_eq!(
- return_value,
- BorshToken::Int {
- width: returned_width,
- value: upper_boundary.clone(),
- }
- );
- let return_value = contract
- .function(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: lower_boundary.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: second_op.clone(),
- },
- ],
- )
- .unwrap();
- assert_eq!(
- return_value,
- BorshToken::Int {
- width: returned_width,
- value: lower_boundary.clone(),
- },
- );
- let upper_boundary_plus_one: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- // We subtract 2 instead of one to make the number even, so that no rounding occurs when we divide by 2 later on.
- let mut lower_boundary_minus_two: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- lower_boundary_minus_two.mul_assign(-1_i32);
- lower_boundary_minus_two.sub_assign(2_i32);
- let upper_second_op = upper_boundary_plus_one.div(2);
- let lower_second_op = lower_boundary_minus_two.div(2);
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: upper_second_op,
- },
- BorshToken::Int {
- width: width as u16,
- value: BigInt::from(2u8),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: lower_second_op,
- },
- BorshToken::Int {
- width: width as u16,
- value: BigInt::from(2),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: upper_boundary.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: upper_boundary.clone(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: lower_boundary.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: lower_boundary.clone(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: upper_boundary.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: lower_boundary.clone(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- }
- }
- #[test]
- fn test_mul_within_range_signed() {
- let mut rng = rand::thread_rng();
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function mul(intN a, intN b) public returns (intN) {
- print("{}*{}".format(a, b));
- return a * b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity(&src);
- // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1]. Here we generate a random number within this range and multiply it by -1, 1 or 0.
- let first_operand_rand = rng.gen_bigint(width - 1).sub(1_u32);
- println!("First op : {first_operand_rand:?}");
- let side = vec![-1, 0, 1];
- // -1, 1 or 0
- let second_op = BigInt::from(*side.choose(&mut rng).unwrap());
- println!("second op : {second_op:?}");
- contract.constructor(&[]);
- let return_value = contract
- .function(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: first_operand_rand.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: second_op.clone(),
- },
- ],
- )
- .unwrap();
- let res = first_operand_rand.mul(second_op);
- assert_eq!(
- return_value,
- BorshToken::Int {
- width: width.next_power_of_two() as u16,
- value: res,
- }
- );
- }
- }
- #[test]
- fn test_mul_within_range() {
- let mut rng = rand::thread_rng();
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function mul(uintN a, uintN b) public returns (uintN) {
- return a * b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity_with_overflow_check(&src, true);
- contract.constructor(&[]);
- for _ in 0..10 {
- // Max number to fit unsigned N bits is (2^N)-1
- let mut limit: BigUint = BigUint::from(2_u32).pow(width as u32);
- limit.sub_assign(1u8);
- // Generate a random number within the the range [0, 2^N -1]
- let first_operand_rand = rng.gen_biguint_range(&BigUint::from(1usize), &limit);
- // Calculate a number that when multiplied by first_operand_rand, the result will not overflow N bits (the result of this division will cast the float result to int result, therefore lowering it. The result of multiplication will never overflow).
- let second_operand_rand = limit.div(&first_operand_rand);
- let return_value = contract
- .function(
- "mul",
- &[
- BorshToken::Uint {
- width: width as u16,
- value: first_operand_rand.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width: width as u16,
- value: second_operand_rand.to_bigint().unwrap(),
- },
- ],
- )
- .unwrap();
- let res = first_operand_rand * second_operand_rand;
- assert_eq!(
- return_value,
- BorshToken::Uint {
- width: (width as u16).next_power_of_two(),
- value: res.to_bigint().unwrap(),
- }
- );
- }
- }
- }
- #[test]
- fn test_overflow_detect_signed() {
- let mut rng = rand::thread_rng();
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function mul(intN a, intN b) public returns (intN) {
- return a * b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity_with_overflow_check(&src, true);
- contract.constructor(&[]);
- // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1] .
- let mut limit: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- limit.sub_assign(1u8);
- // Generate a random number within the the range [(2^N-1)/2, (2^N-1) -1]
- let first_operand_rand =
- rng.gen_bigint_range(&(limit.clone().div(2usize)).add(1usize), &limit);
- // Calculate a number that when multiplied by first_operand_rand, the result will overflow N bits
- let second_operand_rand = rng.gen_bigint_range(&BigInt::from(2usize), &limit);
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: first_operand_rand.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: second_operand_rand.clone(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1] .
- let mut lower_limit: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
- lower_limit.sub_assign(1usize);
- lower_limit.mul_assign(-1_i32);
- // Generate a random number within the the range [-(2^N-1), -(2^N-1)/2]
- let first_operand_rand =
- rng.gen_bigint_range(&lower_limit, &(lower_limit.clone().div(2usize)).add(1usize));
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: first_operand_rand.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: second_operand_rand.clone(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- }
- }
- #[test]
- fn test_overflow_detect_unsigned() {
- let mut rng = rand::thread_rng();
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function mul(uintN a, uintN b) public returns (uintN) {
- return a * b;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut contract = build_solidity_with_overflow_check(&src, true);
- contract.constructor(&[]);
- for _ in 0..10 {
- // N bits can hold the range [0, (2^N)-1]. Generate a value that overflows N bits
- let mut limit: BigUint = BigUint::from(2_u32).pow(width as u32);
- limit.sub_assign(1u8);
- // Generate a random number within the the range [(2^N-1)/2, 2^N -1]
- let first_operand_rand =
- rng.gen_biguint_range(&(limit.clone().div(2usize)).add(1usize), &limit);
- // Calculate a number that when multiplied by first_operand_rand, the result will overflow N bits
- let second_operand_rand = rng.gen_biguint_range(&BigUint::from(2usize), &limit);
- let res = contract.function_must_fail(
- "mul",
- &[
- BorshToken::Uint {
- width: width as u16,
- value: first_operand_rand.to_bigint().unwrap(),
- },
- BorshToken::Uint {
- width: width as u16,
- value: second_operand_rand.to_bigint().unwrap(),
- },
- ],
- );
- assert_ne!(res, Ok(0));
- }
- }
- }
- #[test]
- fn int() {
- let mut rng = rand::thread_rng();
- for width in (8..=256).step_by(8) {
- let src = r#"
- contract test {
- function add(intN a, intN b) public returns (intN) {
- return a + b;
- }
- function sub(intN a, intN b) public returns (intN) {
- return a - b;
- }
- function mul(intN a, intN b) public returns (intN) {
- unchecked {
- return a * b;
- }
- }
- function div(intN a, intN b) public returns (intN) {
- return a / b;
- }
- function mod(intN a, intN b) public returns (intN) {
- return a % b;
- }
- function or(intN a, intN b) public returns (intN) {
- return a | b;
- }
- function and(intN a, intN b) public returns (intN) {
- return a & b;
- }
- function xor(intN a, intN b) public returns (intN) {
- return a ^ b;
- }
- function shift_left(intN a, uint32 r) public returns (intN) {
- return a << r;
- }
- function shift_right(intN a, uint32 r) public returns (intN) {
- return a >> r;
- }
- }"#
- .replace("intN", &format!("int{width}"));
- let mut vm = build_solidity(&src);
- vm.constructor(&[]);
- let returned_width = (width as u16).next_power_of_two();
- for _ in 0..10 {
- let a = rng.gen_bigint(width - 1);
- let b = rng.gen_bigint(width - 1);
- let add = vm
- .function(
- "add",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().add(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- add,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let sub = vm
- .function(
- "sub",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().sub(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- sub,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let mul = vm
- .function(
- "mul",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().mul(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- mul,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- if b != BigInt::zero() {
- let div = vm
- .function(
- "div",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().div(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- div,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let add = vm
- .function(
- "mod",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().rem(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- add,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- }
- let or = vm
- .function(
- "or",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitor(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- or,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let and = vm
- .function(
- "and",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitand(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- and,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let xor = vm
- .function(
- "xor",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Int {
- width: width as u16,
- value: b.clone(),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().bitxor(&b);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- xor,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let r = rng.gen::<u32>() % (width as u32);
- let shl = vm
- .function(
- "shift_left",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = a.clone().shl(r);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- shl,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- let shr = vm
- .function(
- "shift_right",
- &[
- BorshToken::Int {
- width: width as u16,
- value: a.clone(),
- },
- BorshToken::Uint {
- width: 32,
- value: BigInt::from(r),
- },
- ],
- )
- .unwrap();
- let mut res = a.shr(r);
- truncate_bigint(&mut res, width as usize);
- assert_eq!(
- shr,
- BorshToken::Int {
- width: returned_width,
- value: res,
- }
- );
- }
- }
- }
- fn truncate_bigint(n: &mut BigInt, width: usize) {
- let mut bytes_le = n.to_signed_bytes_le();
- let bytes_width = width / 8;
- if bytes_le.len() < bytes_width {
- return;
- }
- while bytes_le.len() > bytes_width {
- bytes_le.pop();
- }
- *n = BigInt::from_signed_bytes_le(&bytes_le);
- }
- #[test]
- fn bytes_cast() {
- let mut vm = build_solidity(
- r#"
- contract foo {
- function to_bytes(bytes4 b) public returns (bytes) {
- return b;
- }
- function to_bytes5(bytes b) public returns (bytes5) {
- return b;
- }
- }
- "#,
- );
- vm.constructor(&[]);
- let returns = vm
- .function("to_bytes", &[BorshToken::FixedBytes(b"abcd".to_vec())])
- .unwrap();
- assert_eq!(returns, BorshToken::Bytes(b"abcd".to_vec()));
- let returns = vm
- .function("to_bytes5", &[BorshToken::Bytes(b"abcde".to_vec())])
- .unwrap();
- assert_eq!(returns, BorshToken::uint8_fixed_array(b"abcde".to_vec()));
- }
- #[test]
- fn shift_after_load() {
- let mut vm = build_solidity(
- r#"
- contract OneSwapToken {
- function testIt(uint256[] calldata mixedAddrVal) public pure returns (uint256, uint256) {
- uint256 a = mixedAddrVal[0]<<2;
- uint256 b = mixedAddrVal[1]>>2;
- return (a, b);
- }
- }
- "#,
- );
- vm.constructor(&[]);
- let args = BorshToken::Array(vec![
- BorshToken::Uint {
- width: 256,
- value: BigInt::one(),
- },
- BorshToken::Uint {
- width: 256,
- value: BigInt::from(4u8),
- },
- ]);
- let returns = vm.function("testIt", &[args]).unwrap().unwrap_tuple();
- assert_eq!(returns.len(), 2);
- assert_eq!(
- returns[0],
- BorshToken::Uint {
- width: 256,
- value: BigInt::from(4u8)
- }
- );
- assert_eq!(
- returns[1],
- BorshToken::Uint {
- width: 256,
- value: BigInt::one(),
- }
- );
- }
|