primitives.rs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. // SPDX-License-Identifier: Apache-2.0
  2. use crate::{build_solidity, BorshToken};
  3. use num_bigint::{BigInt, BigUint, RandBigInt, ToBigInt};
  4. use num_traits::{One, ToPrimitive, Zero};
  5. use rand::seq::SliceRandom;
  6. use rand::Rng;
  7. use std::ops::BitAnd;
  8. use std::ops::Div;
  9. use std::ops::Mul;
  10. use std::ops::Rem;
  11. use std::ops::Shl;
  12. use std::ops::Shr;
  13. use std::ops::Sub;
  14. use std::ops::{Add, BitOr, BitXor, MulAssign, ShlAssign, ShrAssign, SubAssign};
  15. #[test]
  16. #[should_panic]
  17. fn assert_false() {
  18. // without a working assert, this is not going to work
  19. let mut vm = build_solidity(
  20. r#"
  21. contract foo {
  22. function assert_fails() public {
  23. require(false, "humpty-dumpty");
  24. }
  25. }"#,
  26. );
  27. vm.constructor(&[]);
  28. vm.function("assert_fails", &[]);
  29. }
  30. #[test]
  31. fn assert_true() {
  32. // without a working assert, this is not going to work
  33. let mut vm = build_solidity(
  34. r#"
  35. contract foo {
  36. function assert_fails() public {
  37. require(true, "humpty-dumpty");
  38. }
  39. }"#,
  40. );
  41. vm.constructor(&[]);
  42. vm.function("assert_fails", &[]);
  43. }
  44. #[test]
  45. fn boolean() {
  46. // we need to test: literals
  47. // passing address around
  48. // abi encoding/decoding address
  49. // comparing address to another
  50. let mut vm = build_solidity(
  51. r#"
  52. contract foo {
  53. function return_true() public returns (bool) {
  54. return true;
  55. }
  56. function return_false() public returns (bool) {
  57. return false;
  58. }
  59. function true_arg(bool b) public {
  60. assert(b);
  61. }
  62. function false_arg(bool b) public {
  63. assert(!b);
  64. }
  65. }"#,
  66. );
  67. vm.constructor(&[]);
  68. let returns = vm.function("return_true", &[]).unwrap();
  69. assert_eq!(returns, BorshToken::Bool(true));
  70. let returns = vm.function("return_false", &[]).unwrap();
  71. assert_eq!(returns, BorshToken::Bool(false));
  72. vm.function("true_arg", &[BorshToken::Bool(true)]);
  73. vm.function("false_arg", &[BorshToken::Bool(false)]);
  74. }
  75. #[test]
  76. fn address() {
  77. // we need to test: literals
  78. // passing address around
  79. // abi encoding/decoding address
  80. // comparing address to another
  81. let mut vm = build_solidity(
  82. r#"
  83. contract foo {
  84. function return_address() public returns (address) {
  85. return address'CXQw5tfeRKKzV4hk6PcdyKyANSvFxoZCKwHkVXAhAYSJ';
  86. }
  87. function address_arg(address a) public {
  88. assert(a == address'66Eh1STPJgabub73TP8YbN7VNCwjaVTEJGHRxCLeBJ4A');
  89. }
  90. }"#,
  91. );
  92. vm.constructor(&[]);
  93. let returns = vm.function("return_address", &[]).unwrap();
  94. assert_eq!(
  95. returns,
  96. BorshToken::Address([
  97. 171, 59, 10, 127, 211, 122, 217, 123, 53, 213, 159, 40, 54, 36, 50, 52, 196, 144, 17,
  98. 226, 97, 168, 69, 213, 79, 14, 6, 232, 165, 44, 58, 31
  99. ]),
  100. );
  101. vm.function(
  102. "address_arg",
  103. &[BorshToken::Address([
  104. 75, 161, 209, 89, 47, 84, 50, 13, 23, 127, 94, 21, 50, 249, 250, 185, 117, 49, 186,
  105. 134, 82, 130, 112, 97, 218, 24, 157, 198, 40, 105, 118, 27,
  106. ])],
  107. );
  108. }
  109. #[test]
  110. fn test_enum() {
  111. // we need to test enum literals
  112. // abi encoding/decode literals
  113. // comparing enums
  114. let mut vm = build_solidity(
  115. r#"
  116. contract foo {
  117. enum bar { bar0, bar1, bar2, bar3, bar4, bar5, bar6, bar7, bar8, bar9, bar10 }
  118. function return_enum() public returns (bar) {
  119. return bar.bar9;
  120. }
  121. function enum_arg(bar a) public {
  122. assert(a == bar.bar6);
  123. }
  124. }"#,
  125. );
  126. vm.constructor(&[]);
  127. let returns = vm.function("return_enum", &[]).unwrap();
  128. assert_eq!(
  129. returns,
  130. BorshToken::Uint {
  131. width: 8,
  132. value: BigInt::from(9u8)
  133. }
  134. );
  135. vm.function(
  136. "enum_arg",
  137. &[BorshToken::Uint {
  138. width: 8,
  139. value: BigInt::from(6u8),
  140. }],
  141. );
  142. }
  143. #[test]
  144. fn bytes() {
  145. let mut rng = rand::thread_rng();
  146. for width in 1..32 {
  147. let src = r#"
  148. contract test {
  149. function return_literal() public returns (bytes7) {
  150. return hex"01020304050607";
  151. }
  152. function return_arg(bytes7 x) public returns (bytes7) {
  153. return x;
  154. }
  155. function or(bytesN a, bytesN b) public returns (bytesN) {
  156. return a | b;
  157. }
  158. function and(bytesN a, bytesN b) public returns (bytesN) {
  159. return a & b;
  160. }
  161. function xor(bytesN a, bytesN b) public returns (bytesN) {
  162. return a ^ b;
  163. }
  164. function shift_left(bytesN a, uint32 r) public returns (bytesN) {
  165. return a << r;
  166. }
  167. function shift_right(bytesN a, uint32 r) public returns (bytesN) {
  168. return a >> r;
  169. }
  170. }"#
  171. .replace("bytesN", &format!("bytes{width}"));
  172. let mut vm = build_solidity(&src);
  173. vm.constructor(&[]);
  174. let returns = vm.function("return_literal", &[]).unwrap();
  175. assert_eq!(
  176. returns,
  177. BorshToken::uint8_fixed_array(vec![1, 2, 3, 4, 5, 6, 7])
  178. );
  179. let returns = vm
  180. .function(
  181. "return_arg",
  182. &[BorshToken::FixedBytes(vec![1, 2, 3, 4, 5, 6, 7])],
  183. )
  184. .unwrap();
  185. assert_eq!(
  186. returns,
  187. BorshToken::uint8_fixed_array(vec![1, 2, 3, 4, 5, 6, 7])
  188. );
  189. for _ in 0..10 {
  190. let mut a = Vec::new();
  191. let mut b = Vec::new();
  192. a.resize(width, 0);
  193. b.resize(width, 0);
  194. rng.fill(&mut a[..]);
  195. rng.fill(&mut b[..]);
  196. let or = vm
  197. .function(
  198. "or",
  199. &[
  200. BorshToken::FixedBytes(a.to_vec()),
  201. BorshToken::FixedBytes(b.to_vec()),
  202. ],
  203. )
  204. .unwrap();
  205. let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a | b).collect();
  206. println!(
  207. "{} | {} = {}",
  208. hex::encode(&a),
  209. hex::encode(&b),
  210. hex::encode(&res)
  211. );
  212. assert_eq!(or, BorshToken::uint8_fixed_array(res));
  213. let and = vm
  214. .function(
  215. "and",
  216. &[
  217. BorshToken::FixedBytes(a.to_vec()),
  218. BorshToken::FixedBytes(b.to_vec()),
  219. ],
  220. )
  221. .unwrap();
  222. let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a & b).collect();
  223. assert_eq!(and, BorshToken::uint8_fixed_array(res));
  224. let xor = vm
  225. .function(
  226. "xor",
  227. &[
  228. BorshToken::FixedBytes(a.to_vec()),
  229. BorshToken::FixedBytes(b.to_vec()),
  230. ],
  231. )
  232. .unwrap();
  233. let res: Vec<u8> = a.iter().zip(b.iter()).map(|(a, b)| a ^ b).collect();
  234. assert_eq!(xor, BorshToken::uint8_fixed_array(res));
  235. let r = rng.gen::<u32>() % (width as u32 * 8);
  236. println!("w = {width} r = {r}");
  237. let shl = vm
  238. .function(
  239. "shift_left",
  240. &[
  241. BorshToken::FixedBytes(a.to_vec()),
  242. BorshToken::Uint {
  243. width: 32,
  244. value: BigInt::from(r),
  245. },
  246. ],
  247. )
  248. .unwrap();
  249. let mut res = (BigUint::from_bytes_be(&a) << r).to_bytes_be();
  250. while res.len() > width {
  251. res.remove(0);
  252. }
  253. while res.len() < width {
  254. res.insert(0, 0);
  255. }
  256. assert_eq!(shl, BorshToken::uint8_fixed_array(res));
  257. let shr = vm
  258. .function(
  259. "shift_right",
  260. &[
  261. BorshToken::FixedBytes(a.to_vec()),
  262. BorshToken::Uint {
  263. width: 32,
  264. value: BigInt::from(r),
  265. },
  266. ],
  267. )
  268. .unwrap();
  269. let mut res = (BigUint::from_bytes_be(&a) >> r).to_bytes_be();
  270. while res.len() < width {
  271. res.insert(0, 0);
  272. }
  273. assert_eq!(shr, BorshToken::uint8_fixed_array(res));
  274. }
  275. }
  276. }
  277. #[test]
  278. fn uint() {
  279. let mut rng = rand::thread_rng();
  280. for width in (8u16..=256).step_by(8) {
  281. let src = r#"
  282. contract test {
  283. function pass(uintN a) public returns (uintN) {
  284. print("x:{:x}".format(uint64(a)));
  285. return 0x7f;
  286. }
  287. function add(uintN a, uintN b) public returns (uintN) {
  288. unchecked {
  289. return a + b;
  290. }
  291. }
  292. function sub(uintN a, uintN b) public returns (uintN) {
  293. unchecked {
  294. return a - b;
  295. }
  296. }
  297. function mul(uintN a, uintN b) public returns (uintN) {
  298. unchecked {
  299. return a * b;
  300. }
  301. }
  302. function div(uintN a, uintN b) public returns (uintN) {
  303. unchecked {
  304. return a / b;
  305. }
  306. }
  307. function mod(uintN a, uintN b) public returns (uintN) {
  308. unchecked {
  309. return a % b;
  310. }
  311. }
  312. function pow(uintN a, uintN b) public returns (uintN) {
  313. unchecked {
  314. return a ** b;
  315. }
  316. }
  317. function or(uintN a, uintN b) public returns (uintN) {
  318. return a | b;
  319. }
  320. function and(uintN a, uintN b) public returns (uintN) {
  321. return a & b;
  322. }
  323. function xor(uintN a, uintN b) public returns (uintN) {
  324. return a ^ b;
  325. }
  326. function shift_left(uintN a, uint32 r) public returns (uintN) {
  327. return a << r;
  328. }
  329. function shift_right(uintN a, uint32 r) public returns (uintN) {
  330. return a >> r;
  331. }
  332. }"#
  333. .replace("uintN", &format!("uint{width}"));
  334. let mut vm = build_solidity(&src);
  335. vm.constructor(&[]);
  336. println!("width:{width}");
  337. let returned_width = width.next_power_of_two();
  338. for _ in 0..10 {
  339. let mut a = rng.gen_biguint(width as u64);
  340. let mut b = rng.gen_biguint(width as u64);
  341. if b > a {
  342. std::mem::swap(&mut a, &mut b);
  343. }
  344. let res = vm.function(
  345. "pass",
  346. &[BorshToken::Uint {
  347. width,
  348. value: a.to_bigint().unwrap(),
  349. }],
  350. );
  351. println!("{a:x} = {res:?} o");
  352. let add = vm
  353. .function(
  354. "add",
  355. &[
  356. BorshToken::Uint {
  357. width,
  358. value: a.to_bigint().unwrap(),
  359. },
  360. BorshToken::Uint {
  361. width,
  362. value: b.to_bigint().unwrap(),
  363. },
  364. ],
  365. )
  366. .unwrap();
  367. let mut res = a.clone().add(&b);
  368. truncate_biguint(&mut res, width);
  369. println!("{a:x} + {b:x} = {add:?} or {res:x}");
  370. assert_eq!(
  371. add,
  372. BorshToken::Uint {
  373. width: returned_width,
  374. value: res.to_bigint().unwrap(),
  375. }
  376. );
  377. let sub = vm
  378. .function(
  379. "sub",
  380. &[
  381. BorshToken::Uint {
  382. width,
  383. value: a.to_bigint().unwrap(),
  384. },
  385. BorshToken::Uint {
  386. width,
  387. value: b.to_bigint().unwrap(),
  388. },
  389. ],
  390. )
  391. .unwrap();
  392. let mut res = a.clone().sub(&b);
  393. truncate_biguint(&mut res, width);
  394. assert_eq!(
  395. sub,
  396. BorshToken::Uint {
  397. width: returned_width,
  398. value: res.to_bigint().unwrap(),
  399. }
  400. );
  401. let mul = vm
  402. .function(
  403. "mul",
  404. &[
  405. BorshToken::Uint {
  406. width,
  407. value: a.to_bigint().unwrap(),
  408. },
  409. BorshToken::Uint {
  410. width,
  411. value: b.to_bigint().unwrap(),
  412. },
  413. ],
  414. )
  415. .unwrap();
  416. let mut res = a.clone().mul(&b);
  417. truncate_biguint(&mut res, width);
  418. assert_eq!(
  419. mul,
  420. BorshToken::Uint {
  421. width: returned_width,
  422. value: res.to_bigint().unwrap(),
  423. }
  424. );
  425. if let Some(mut n) = b.to_u32() {
  426. n %= 65536;
  427. let pow = vm
  428. .function(
  429. "pow",
  430. &[
  431. BorshToken::Uint {
  432. width,
  433. value: a.to_bigint().unwrap(),
  434. },
  435. BorshToken::Uint {
  436. width,
  437. value: BigInt::from(n),
  438. },
  439. ],
  440. )
  441. .unwrap();
  442. let mut res = a.clone().pow(n);
  443. truncate_biguint(&mut res, width);
  444. assert_eq!(
  445. pow,
  446. BorshToken::Uint {
  447. width: returned_width,
  448. value: res.to_bigint().unwrap(),
  449. }
  450. );
  451. }
  452. if b != BigUint::zero() {
  453. let div = vm
  454. .function(
  455. "div",
  456. &[
  457. BorshToken::Uint {
  458. width,
  459. value: a.to_bigint().unwrap(),
  460. },
  461. BorshToken::Uint {
  462. width,
  463. value: b.to_bigint().unwrap(),
  464. },
  465. ],
  466. )
  467. .unwrap();
  468. let mut res = a.clone().div(&b);
  469. truncate_biguint(&mut res, width);
  470. assert_eq!(
  471. div,
  472. BorshToken::Uint {
  473. width: returned_width,
  474. value: res.to_bigint().unwrap(),
  475. }
  476. );
  477. let add = vm
  478. .function(
  479. "mod",
  480. &[
  481. BorshToken::Uint {
  482. width,
  483. value: a.to_bigint().unwrap(),
  484. },
  485. BorshToken::Uint {
  486. width,
  487. value: b.to_bigint().unwrap(),
  488. },
  489. ],
  490. )
  491. .unwrap();
  492. let mut res = a.clone().rem(&b);
  493. truncate_biguint(&mut res, width);
  494. assert_eq!(
  495. add,
  496. BorshToken::Uint {
  497. width: returned_width,
  498. value: res.to_bigint().unwrap(),
  499. }
  500. );
  501. }
  502. let or = vm
  503. .function(
  504. "or",
  505. &[
  506. BorshToken::Uint {
  507. width,
  508. value: a.to_bigint().unwrap(),
  509. },
  510. BorshToken::Uint {
  511. width,
  512. value: b.to_bigint().unwrap(),
  513. },
  514. ],
  515. )
  516. .unwrap();
  517. let mut res = a.clone().bitor(&b);
  518. truncate_biguint(&mut res, width);
  519. assert_eq!(
  520. or,
  521. BorshToken::Uint {
  522. width: returned_width,
  523. value: res.to_bigint().unwrap(),
  524. }
  525. );
  526. let and = vm
  527. .function(
  528. "and",
  529. &[
  530. BorshToken::Uint {
  531. width,
  532. value: a.to_bigint().unwrap(),
  533. },
  534. BorshToken::Uint {
  535. width,
  536. value: b.to_bigint().unwrap(),
  537. },
  538. ],
  539. )
  540. .unwrap();
  541. let mut res = a.clone().bitand(&b);
  542. truncate_biguint(&mut res, width);
  543. assert_eq!(
  544. and,
  545. BorshToken::Uint {
  546. width: returned_width,
  547. value: res.to_bigint().unwrap(),
  548. }
  549. );
  550. let xor = vm
  551. .function(
  552. "xor",
  553. &[
  554. BorshToken::Uint {
  555. width,
  556. value: a.to_bigint().unwrap(),
  557. },
  558. BorshToken::Uint {
  559. width,
  560. value: b.to_bigint().unwrap(),
  561. },
  562. ],
  563. )
  564. .unwrap();
  565. let mut res = a.clone().bitxor(&b);
  566. truncate_biguint(&mut res, width);
  567. assert_eq!(
  568. xor,
  569. BorshToken::Uint {
  570. width: returned_width,
  571. value: res.to_bigint().unwrap(),
  572. }
  573. );
  574. let r = rng.gen::<u32>() % (width as u32);
  575. let shl = vm
  576. .function(
  577. "shift_left",
  578. &[
  579. BorshToken::Uint {
  580. width,
  581. value: a.to_bigint().unwrap(),
  582. },
  583. BorshToken::Uint {
  584. width: 32,
  585. value: BigInt::from(r),
  586. },
  587. ],
  588. )
  589. .unwrap();
  590. let mut res = a.clone();
  591. res.shl_assign(r);
  592. truncate_biguint(&mut res, width);
  593. assert_eq!(
  594. shl,
  595. BorshToken::Uint {
  596. width: returned_width,
  597. value: res.to_bigint().unwrap(),
  598. }
  599. );
  600. let shr = vm
  601. .function(
  602. "shift_right",
  603. &[
  604. BorshToken::Uint {
  605. width,
  606. value: a.to_bigint().unwrap(),
  607. },
  608. BorshToken::Uint {
  609. width: 32,
  610. value: BigInt::from(r),
  611. },
  612. ],
  613. )
  614. .unwrap();
  615. let mut res = a.clone();
  616. res.shr_assign(&r);
  617. truncate_biguint(&mut res, width);
  618. assert_eq!(
  619. shr,
  620. BorshToken::Uint {
  621. width: returned_width,
  622. value: res.to_bigint().unwrap(),
  623. }
  624. );
  625. }
  626. }
  627. }
  628. fn truncate_biguint(n: &mut BigUint, width: u16) {
  629. let mut bytes = n.to_bytes_le();
  630. let byte_width = (width / 8) as usize;
  631. if bytes.len() < byte_width {
  632. return;
  633. }
  634. for item in bytes.iter_mut().skip(byte_width) {
  635. *item = 0;
  636. }
  637. *n = BigUint::from_bytes_le(&bytes);
  638. }
  639. #[test]
  640. fn test_power_overflow_boundaries() {
  641. for width in (8u16..=256).step_by(8) {
  642. let src = r#"
  643. contract test {
  644. function pow(uintN a, uintN b) public returns (uintN) {
  645. return a ** b;
  646. }
  647. }"#
  648. .replace("intN", &format!("int{width}"));
  649. let mut contract = build_solidity(&src);
  650. contract.constructor(&[]);
  651. let return_value = contract
  652. .function(
  653. "pow",
  654. &[
  655. BorshToken::Uint {
  656. width,
  657. value: BigInt::from(2u8),
  658. },
  659. BorshToken::Uint {
  660. width,
  661. value: BigInt::from(width - 1),
  662. },
  663. ],
  664. )
  665. .unwrap();
  666. let res = BigUint::from(2_u32).pow((width - 1) as u32);
  667. assert_eq!(
  668. return_value,
  669. BorshToken::Uint {
  670. width: width.next_power_of_two(),
  671. value: res.to_bigint().unwrap(),
  672. }
  673. );
  674. let sesa = contract.function_must_fail(
  675. "pow",
  676. &[
  677. BorshToken::Uint {
  678. width,
  679. value: BigInt::from(2u8),
  680. },
  681. BorshToken::Uint {
  682. width,
  683. value: BigInt::from(width + 1),
  684. },
  685. ],
  686. );
  687. assert_ne!(sesa.unwrap(), 0);
  688. }
  689. }
  690. #[test]
  691. fn test_overflow_boundaries() {
  692. for width in (8..=256).step_by(8) {
  693. let src = r#"
  694. contract test {
  695. function mul(intN a, intN b) public returns (intN) {
  696. return a * b;
  697. }
  698. }"#
  699. .replace("intN", &format!("int{width}"));
  700. let mut contract = build_solidity(&src);
  701. // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1]. We generate these boundaries:
  702. let mut upper_boundary: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  703. upper_boundary.sub_assign(1);
  704. let mut lower_boundary: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  705. lower_boundary.mul_assign(-1);
  706. let second_op = BigInt::from(1_u32);
  707. let returned_width = (width as u16).next_power_of_two();
  708. // Multiply the boundaries by 1.
  709. contract.constructor(&[]);
  710. let return_value = contract
  711. .function(
  712. "mul",
  713. &[
  714. BorshToken::Int {
  715. width: width as u16,
  716. value: upper_boundary.clone(),
  717. },
  718. BorshToken::Int {
  719. width: width as u16,
  720. value: second_op.clone(),
  721. },
  722. ],
  723. )
  724. .unwrap();
  725. assert_eq!(
  726. return_value,
  727. BorshToken::Int {
  728. width: returned_width,
  729. value: upper_boundary.clone(),
  730. }
  731. );
  732. let return_value = contract
  733. .function(
  734. "mul",
  735. &[
  736. BorshToken::Int {
  737. width: width as u16,
  738. value: lower_boundary.clone(),
  739. },
  740. BorshToken::Int {
  741. width: width as u16,
  742. value: second_op.clone(),
  743. },
  744. ],
  745. )
  746. .unwrap();
  747. assert_eq!(
  748. return_value,
  749. BorshToken::Int {
  750. width: returned_width,
  751. value: lower_boundary.clone(),
  752. },
  753. );
  754. let upper_boundary_plus_one: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  755. // We subtract 2 instead of one to make the number even, so that no rounding occurs when we divide by 2 later on.
  756. let mut lower_boundary_minus_two: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  757. lower_boundary_minus_two.mul_assign(-1_i32);
  758. lower_boundary_minus_two.sub_assign(2_i32);
  759. let upper_second_op = upper_boundary_plus_one.div(2);
  760. let lower_second_op = lower_boundary_minus_two.div(2);
  761. let res = contract.function_must_fail(
  762. "mul",
  763. &[
  764. BorshToken::Int {
  765. width: width as u16,
  766. value: upper_second_op,
  767. },
  768. BorshToken::Int {
  769. width: width as u16,
  770. value: BigInt::from(2u8),
  771. },
  772. ],
  773. );
  774. assert_ne!(res.unwrap(), 0);
  775. let res = contract.function_must_fail(
  776. "mul",
  777. &[
  778. BorshToken::Int {
  779. width: width as u16,
  780. value: lower_second_op,
  781. },
  782. BorshToken::Int {
  783. width: width as u16,
  784. value: BigInt::from(2),
  785. },
  786. ],
  787. );
  788. assert_ne!(res.unwrap(), 0);
  789. let res = contract.function_must_fail(
  790. "mul",
  791. &[
  792. BorshToken::Int {
  793. width: width as u16,
  794. value: upper_boundary.clone(),
  795. },
  796. BorshToken::Int {
  797. width: width as u16,
  798. value: upper_boundary.clone(),
  799. },
  800. ],
  801. );
  802. assert_ne!(res.unwrap(), 0);
  803. let res = contract.function_must_fail(
  804. "mul",
  805. &[
  806. BorshToken::Int {
  807. width: width as u16,
  808. value: lower_boundary.clone(),
  809. },
  810. BorshToken::Int {
  811. width: width as u16,
  812. value: lower_boundary.clone(),
  813. },
  814. ],
  815. );
  816. assert_ne!(res.unwrap(), 0);
  817. let res = contract.function_must_fail(
  818. "mul",
  819. &[
  820. BorshToken::Int {
  821. width: width as u16,
  822. value: upper_boundary.clone(),
  823. },
  824. BorshToken::Int {
  825. width: width as u16,
  826. value: lower_boundary.clone(),
  827. },
  828. ],
  829. );
  830. assert_ne!(res.unwrap(), 0);
  831. }
  832. }
  833. #[test]
  834. fn test_mul_within_range_signed() {
  835. let mut rng = rand::thread_rng();
  836. for width in (8..=256).step_by(8) {
  837. let src = r#"
  838. contract test {
  839. function mul(intN a, intN b) public returns (intN) {
  840. print("{}*{}".format(a, b));
  841. return a * b;
  842. }
  843. }"#
  844. .replace("intN", &format!("int{width}"));
  845. let mut contract = build_solidity(&src);
  846. // 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.
  847. let first_operand_rand = rng.gen_bigint(width - 1).sub(1_u32);
  848. println!("First op : {first_operand_rand:?}");
  849. let side = vec![-1, 0, 1];
  850. // -1, 1 or 0
  851. let second_op = BigInt::from(*side.choose(&mut rng).unwrap());
  852. println!("second op : {second_op:?}");
  853. contract.constructor(&[]);
  854. let return_value = contract
  855. .function(
  856. "mul",
  857. &[
  858. BorshToken::Int {
  859. width: width as u16,
  860. value: first_operand_rand.clone(),
  861. },
  862. BorshToken::Int {
  863. width: width as u16,
  864. value: second_op.clone(),
  865. },
  866. ],
  867. )
  868. .unwrap();
  869. let res = first_operand_rand.mul(second_op);
  870. assert_eq!(
  871. return_value,
  872. BorshToken::Int {
  873. width: width.next_power_of_two() as u16,
  874. value: res,
  875. }
  876. );
  877. }
  878. }
  879. #[test]
  880. fn test_mul_within_range() {
  881. let mut rng = rand::thread_rng();
  882. for width in (8..=256).step_by(8) {
  883. let src = r#"
  884. contract test {
  885. function mul(uintN a, uintN b) public returns (uintN) {
  886. return a * b;
  887. }
  888. }"#
  889. .replace("intN", &format!("int{width}"));
  890. let mut contract = build_solidity(&src);
  891. contract.constructor(&[]);
  892. for _ in 0..10 {
  893. // Max number to fit unsigned N bits is (2^N)-1
  894. let mut limit: BigUint = BigUint::from(2_u32).pow(width as u32);
  895. limit.sub_assign(1u8);
  896. // Generate a random number within the the range [0, 2^N -1]
  897. let first_operand_rand = rng.gen_biguint_range(&BigUint::from(1usize), &limit);
  898. // 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).
  899. let second_operand_rand = limit.div(&first_operand_rand);
  900. let return_value = contract
  901. .function(
  902. "mul",
  903. &[
  904. BorshToken::Uint {
  905. width: width as u16,
  906. value: first_operand_rand.to_bigint().unwrap(),
  907. },
  908. BorshToken::Uint {
  909. width: width as u16,
  910. value: second_operand_rand.to_bigint().unwrap(),
  911. },
  912. ],
  913. )
  914. .unwrap();
  915. let res = first_operand_rand * second_operand_rand;
  916. assert_eq!(
  917. return_value,
  918. BorshToken::Uint {
  919. width: (width as u16).next_power_of_two(),
  920. value: res.to_bigint().unwrap(),
  921. }
  922. );
  923. }
  924. }
  925. }
  926. #[test]
  927. fn test_overflow_detect_signed() {
  928. let mut rng = rand::thread_rng();
  929. for width in (8..=256).step_by(8) {
  930. let src = r#"
  931. contract test {
  932. function mul(intN a, intN b) public returns (intN) {
  933. return a * b;
  934. }
  935. }"#
  936. .replace("intN", &format!("int{width}"));
  937. let mut contract = build_solidity(&src);
  938. contract.constructor(&[]);
  939. // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1] .
  940. let mut limit: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  941. limit.sub_assign(1u8);
  942. // Generate a random number within the the range [(2^N-1)/2, (2^N-1) -1]
  943. let first_operand_rand =
  944. rng.gen_bigint_range(&(limit.clone().div(2usize)).add(1usize), &limit);
  945. // Calculate a number that when multiplied by first_operand_rand, the result will overflow N bits
  946. let second_operand_rand = rng.gen_bigint_range(&BigInt::from(2usize), &limit);
  947. let res = contract.function_must_fail(
  948. "mul",
  949. &[
  950. BorshToken::Int {
  951. width: width as u16,
  952. value: first_operand_rand.clone(),
  953. },
  954. BorshToken::Int {
  955. width: width as u16,
  956. value: second_operand_rand.clone(),
  957. },
  958. ],
  959. );
  960. assert_ne!(res.unwrap(), 0);
  961. // The range of values that can be held in signed N bits is [-2^(N-1), 2^(N-1)-1] .
  962. let mut lower_limit: BigInt = BigInt::from(2_u32).pow((width - 1) as u32);
  963. lower_limit.sub_assign(1usize);
  964. lower_limit.mul_assign(-1_i32);
  965. // Generate a random number within the the range [-(2^N-1), -(2^N-1)/2]
  966. let first_operand_rand =
  967. rng.gen_bigint_range(&lower_limit, &(lower_limit.clone().div(2usize)).add(1usize));
  968. let res = contract.function_must_fail(
  969. "mul",
  970. &[
  971. BorshToken::Int {
  972. width: width as u16,
  973. value: first_operand_rand.clone(),
  974. },
  975. BorshToken::Int {
  976. width: width as u16,
  977. value: second_operand_rand.clone(),
  978. },
  979. ],
  980. );
  981. assert_ne!(res.unwrap(), 0);
  982. }
  983. }
  984. #[test]
  985. fn test_overflow_detect_unsigned() {
  986. let mut rng = rand::thread_rng();
  987. for width in (8..=256).step_by(8) {
  988. let src = r#"
  989. contract test {
  990. function mul(uintN a, uintN b) public returns (uintN) {
  991. return a * b;
  992. }
  993. }"#
  994. .replace("intN", &format!("int{width}"));
  995. let mut contract = build_solidity(&src);
  996. contract.constructor(&[]);
  997. for _ in 0..10 {
  998. // N bits can hold the range [0, (2^N)-1]. Generate a value that overflows N bits
  999. let mut limit: BigUint = BigUint::from(2_u32).pow(width as u32);
  1000. limit.sub_assign(1u8);
  1001. // Generate a random number within the the range [(2^N-1)/2, 2^N -1]
  1002. let first_operand_rand =
  1003. rng.gen_biguint_range(&(limit.clone().div(2usize)).add(1usize), &limit);
  1004. // Calculate a number that when multiplied by first_operand_rand, the result will overflow N bits
  1005. let second_operand_rand = rng.gen_biguint_range(&BigUint::from(2usize), &limit);
  1006. let res = contract.function_must_fail(
  1007. "mul",
  1008. &[
  1009. BorshToken::Uint {
  1010. width: width as u16,
  1011. value: first_operand_rand.to_bigint().unwrap(),
  1012. },
  1013. BorshToken::Uint {
  1014. width: width as u16,
  1015. value: second_operand_rand.to_bigint().unwrap(),
  1016. },
  1017. ],
  1018. );
  1019. assert_ne!(res.unwrap(), 0);
  1020. }
  1021. }
  1022. }
  1023. #[test]
  1024. fn int() {
  1025. let mut rng = rand::thread_rng();
  1026. for width in (8..=256).step_by(8) {
  1027. let src = r#"
  1028. contract test {
  1029. function add(intN a, intN b) public returns (intN) {
  1030. unchecked {
  1031. return a + b;
  1032. }
  1033. }
  1034. function sub(intN a, intN b) public returns (intN) {
  1035. unchecked {
  1036. return a - b;
  1037. }
  1038. }
  1039. function mul(intN a, intN b) public returns (intN) {
  1040. unchecked {
  1041. return a * b;
  1042. }
  1043. }
  1044. function div(intN a, intN b) public returns (intN) {
  1045. unchecked {
  1046. return a / b;
  1047. }
  1048. }
  1049. function mod(intN a, intN b) public returns (intN) {
  1050. return a % b;
  1051. }
  1052. function or(intN a, intN b) public returns (intN) {
  1053. return a | b;
  1054. }
  1055. function and(intN a, intN b) public returns (intN) {
  1056. return a & b;
  1057. }
  1058. function xor(intN a, intN b) public returns (intN) {
  1059. return a ^ b;
  1060. }
  1061. function shift_left(intN a, uint32 r) public returns (intN) {
  1062. return a << r;
  1063. }
  1064. function shift_right(intN a, uint32 r) public returns (intN) {
  1065. return a >> r;
  1066. }
  1067. }"#
  1068. .replace("intN", &format!("int{width}"));
  1069. let mut vm = build_solidity(&src);
  1070. vm.constructor(&[]);
  1071. let returned_width = (width as u16).next_power_of_two();
  1072. for _ in 0..10 {
  1073. let a = rng.gen_bigint(width - 1);
  1074. let b = rng.gen_bigint(width - 1);
  1075. let add = vm
  1076. .function(
  1077. "add",
  1078. &[
  1079. BorshToken::Int {
  1080. width: width as u16,
  1081. value: a.clone(),
  1082. },
  1083. BorshToken::Int {
  1084. width: width as u16,
  1085. value: b.clone(),
  1086. },
  1087. ],
  1088. )
  1089. .unwrap();
  1090. let mut res = a.clone().add(&b);
  1091. truncate_bigint(&mut res, width as usize);
  1092. assert_eq!(
  1093. add,
  1094. BorshToken::Int {
  1095. width: returned_width,
  1096. value: res,
  1097. }
  1098. );
  1099. let sub = vm
  1100. .function(
  1101. "sub",
  1102. &[
  1103. BorshToken::Int {
  1104. width: width as u16,
  1105. value: a.clone(),
  1106. },
  1107. BorshToken::Int {
  1108. width: width as u16,
  1109. value: b.clone(),
  1110. },
  1111. ],
  1112. )
  1113. .unwrap();
  1114. let mut res = a.clone().sub(&b);
  1115. truncate_bigint(&mut res, width as usize);
  1116. assert_eq!(
  1117. sub,
  1118. BorshToken::Int {
  1119. width: returned_width,
  1120. value: res,
  1121. }
  1122. );
  1123. let mul = vm
  1124. .function(
  1125. "mul",
  1126. &[
  1127. BorshToken::Int {
  1128. width: width as u16,
  1129. value: a.clone(),
  1130. },
  1131. BorshToken::Int {
  1132. width: width as u16,
  1133. value: b.clone(),
  1134. },
  1135. ],
  1136. )
  1137. .unwrap();
  1138. let mut res = a.clone().mul(&b);
  1139. truncate_bigint(&mut res, width as usize);
  1140. assert_eq!(
  1141. mul,
  1142. BorshToken::Int {
  1143. width: returned_width,
  1144. value: res,
  1145. }
  1146. );
  1147. if b != BigInt::zero() {
  1148. let div = vm
  1149. .function(
  1150. "div",
  1151. &[
  1152. BorshToken::Int {
  1153. width: width as u16,
  1154. value: a.clone(),
  1155. },
  1156. BorshToken::Int {
  1157. width: width as u16,
  1158. value: b.clone(),
  1159. },
  1160. ],
  1161. )
  1162. .unwrap();
  1163. let mut res = a.clone().div(&b);
  1164. truncate_bigint(&mut res, width as usize);
  1165. assert_eq!(
  1166. div,
  1167. BorshToken::Int {
  1168. width: returned_width,
  1169. value: res,
  1170. }
  1171. );
  1172. let add = vm
  1173. .function(
  1174. "mod",
  1175. &[
  1176. BorshToken::Int {
  1177. width: width as u16,
  1178. value: a.clone(),
  1179. },
  1180. BorshToken::Int {
  1181. width: width as u16,
  1182. value: b.clone(),
  1183. },
  1184. ],
  1185. )
  1186. .unwrap();
  1187. let mut res = a.clone().rem(&b);
  1188. truncate_bigint(&mut res, width as usize);
  1189. assert_eq!(
  1190. add,
  1191. BorshToken::Int {
  1192. width: returned_width,
  1193. value: res,
  1194. }
  1195. );
  1196. }
  1197. let or = vm
  1198. .function(
  1199. "or",
  1200. &[
  1201. BorshToken::Int {
  1202. width: width as u16,
  1203. value: a.clone(),
  1204. },
  1205. BorshToken::Int {
  1206. width: width as u16,
  1207. value: b.clone(),
  1208. },
  1209. ],
  1210. )
  1211. .unwrap();
  1212. let mut res = a.clone().bitor(&b);
  1213. truncate_bigint(&mut res, width as usize);
  1214. assert_eq!(
  1215. or,
  1216. BorshToken::Int {
  1217. width: returned_width,
  1218. value: res,
  1219. }
  1220. );
  1221. let and = vm
  1222. .function(
  1223. "and",
  1224. &[
  1225. BorshToken::Int {
  1226. width: width as u16,
  1227. value: a.clone(),
  1228. },
  1229. BorshToken::Int {
  1230. width: width as u16,
  1231. value: b.clone(),
  1232. },
  1233. ],
  1234. )
  1235. .unwrap();
  1236. let mut res = a.clone().bitand(&b);
  1237. truncate_bigint(&mut res, width as usize);
  1238. assert_eq!(
  1239. and,
  1240. BorshToken::Int {
  1241. width: returned_width,
  1242. value: res,
  1243. }
  1244. );
  1245. let xor = vm
  1246. .function(
  1247. "xor",
  1248. &[
  1249. BorshToken::Int {
  1250. width: width as u16,
  1251. value: a.clone(),
  1252. },
  1253. BorshToken::Int {
  1254. width: width as u16,
  1255. value: b.clone(),
  1256. },
  1257. ],
  1258. )
  1259. .unwrap();
  1260. let mut res = a.clone().bitxor(&b);
  1261. truncate_bigint(&mut res, width as usize);
  1262. assert_eq!(
  1263. xor,
  1264. BorshToken::Int {
  1265. width: returned_width,
  1266. value: res,
  1267. }
  1268. );
  1269. let r = rng.gen::<u32>() % (width as u32);
  1270. let shl = vm
  1271. .function(
  1272. "shift_left",
  1273. &[
  1274. BorshToken::Int {
  1275. width: width as u16,
  1276. value: a.clone(),
  1277. },
  1278. BorshToken::Uint {
  1279. width: 32,
  1280. value: BigInt::from(r),
  1281. },
  1282. ],
  1283. )
  1284. .unwrap();
  1285. let mut res = a.clone().shl(r);
  1286. truncate_bigint(&mut res, width as usize);
  1287. assert_eq!(
  1288. shl,
  1289. BorshToken::Int {
  1290. width: returned_width,
  1291. value: res,
  1292. }
  1293. );
  1294. let shr = vm
  1295. .function(
  1296. "shift_right",
  1297. &[
  1298. BorshToken::Int {
  1299. width: width as u16,
  1300. value: a.clone(),
  1301. },
  1302. BorshToken::Uint {
  1303. width: 32,
  1304. value: BigInt::from(r),
  1305. },
  1306. ],
  1307. )
  1308. .unwrap();
  1309. let mut res = a.shr(r);
  1310. truncate_bigint(&mut res, width as usize);
  1311. assert_eq!(
  1312. shr,
  1313. BorshToken::Int {
  1314. width: returned_width,
  1315. value: res,
  1316. }
  1317. );
  1318. }
  1319. }
  1320. }
  1321. fn truncate_bigint(n: &mut BigInt, width: usize) {
  1322. let mut bytes_le = n.to_signed_bytes_le();
  1323. let bytes_width = width / 8;
  1324. if bytes_le.len() < bytes_width {
  1325. return;
  1326. }
  1327. while bytes_le.len() > bytes_width {
  1328. bytes_le.pop();
  1329. }
  1330. *n = BigInt::from_signed_bytes_le(&bytes_le);
  1331. }
  1332. #[test]
  1333. fn bytes_cast() {
  1334. let mut vm = build_solidity(
  1335. r#"
  1336. contract foo {
  1337. function to_bytes(bytes4 b) public returns (bytes) {
  1338. return b;
  1339. }
  1340. function to_bytes5(bytes b) public returns (bytes5) {
  1341. return b;
  1342. }
  1343. }
  1344. "#,
  1345. );
  1346. vm.constructor(&[]);
  1347. let returns = vm
  1348. .function("to_bytes", &[BorshToken::FixedBytes(b"abcd".to_vec())])
  1349. .unwrap();
  1350. assert_eq!(returns, BorshToken::Bytes(b"abcd".to_vec()));
  1351. let returns = vm
  1352. .function("to_bytes5", &[BorshToken::Bytes(b"abcde".to_vec())])
  1353. .unwrap();
  1354. assert_eq!(returns, BorshToken::uint8_fixed_array(b"abcde".to_vec()));
  1355. }
  1356. #[test]
  1357. fn shift_after_load() {
  1358. let mut vm = build_solidity(
  1359. r#"
  1360. contract OneSwapToken {
  1361. function testIt(uint256[] calldata mixedAddrVal) public pure returns (uint256, uint256) {
  1362. uint256 a = mixedAddrVal[0]<<2;
  1363. uint256 b = mixedAddrVal[1]>>2;
  1364. return (a, b);
  1365. }
  1366. }
  1367. "#,
  1368. );
  1369. vm.constructor(&[]);
  1370. let args = BorshToken::Array(vec![
  1371. BorshToken::Uint {
  1372. width: 256,
  1373. value: BigInt::one(),
  1374. },
  1375. BorshToken::Uint {
  1376. width: 256,
  1377. value: BigInt::from(4u8),
  1378. },
  1379. ]);
  1380. let returns = vm.function("testIt", &[args]).unwrap().unwrap_tuple();
  1381. assert_eq!(returns.len(), 2);
  1382. assert_eq!(
  1383. returns[0],
  1384. BorshToken::Uint {
  1385. width: 256,
  1386. value: BigInt::from(4u8)
  1387. }
  1388. );
  1389. assert_eq!(
  1390. returns[1],
  1391. BorshToken::Uint {
  1392. width: 256,
  1393. value: BigInt::one(),
  1394. }
  1395. );
  1396. }