12345678910111213141516171819#![allow(dead_code)]2021#[cfg(not(feature = "std"))]22use alloc::vec::Vec;23use evm_core::ExitError;24use primitive_types::{H160, U256};2526use crate::{27 execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},28 types::*,29};30use crate::execution::Result;3132const ABI_ALIGNMENT: usize = 32;3334trait TypeHelper {35 36 fn is_dynamic() -> bool;3738 39 fn size() -> usize;40}414243#[derive(Clone)]44pub struct AbiReader<'i> {45 buf: &'i [u8],46 subresult_offset: usize,47 offset: usize,48}49impl<'i> AbiReader<'i> {50 51 pub fn new(buf: &'i [u8]) -> Self {52 Self {53 buf,54 subresult_offset: 0,55 offset: 0,56 }57 }58 59 pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {60 if buf.len() < 4 {61 return Err(Error::Error(ExitError::OutOfOffset));62 }63 let mut method_id = [0; 4];64 method_id.copy_from_slice(&buf[0..4]);6566 Ok((67 method_id,68 Self {69 buf,70 subresult_offset: 4,71 offset: 4,72 },73 ))74 }7576 fn read_pad<const S: usize>(77 buf: &[u8],78 offset: usize,79 pad_start: usize,80 pad_size: usize,81 block_start: usize,82 block_size: usize,83 ) -> Result<[u8; S]> {84 if buf.len() - offset < ABI_ALIGNMENT {85 return Err(Error::Error(ExitError::OutOfOffset));86 }87 let mut block = [0; S];88 let is_pad_zeroed = buf[pad_start..pad_size].iter().all(|&v| v == 0);89 if !is_pad_zeroed {90 return Err(Error::Error(ExitError::InvalidRange));91 }92 block.copy_from_slice(&buf[block_start..block_size]);93 Ok(block)94 }9596 fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {97 let offset = self.offset;98 self.offset += ABI_ALIGNMENT;99 Self::read_pad(100 self.buf,101 offset,102 offset,103 offset + ABI_ALIGNMENT - S,104 offset + ABI_ALIGNMENT - S,105 offset + ABI_ALIGNMENT,106 )107 }108109 fn read_padright<const S: usize>(&mut self) -> Result<[u8; S]> {110 let offset = self.offset;111 self.offset += ABI_ALIGNMENT;112 Self::read_pad(113 self.buf,114 offset,115 offset + S,116 offset + ABI_ALIGNMENT,117 offset,118 offset + S,119 )120 }121122 123 pub fn address(&mut self) -> Result<H160> {124 Ok(H160(self.read_padleft()?))125 }126127 128 pub fn bool(&mut self) -> Result<bool> {129 let data: [u8; 1] = self.read_padleft()?;130 match data[0] {131 0 => Ok(false),132 1 => Ok(true),133 _ => Err(Error::Error(ExitError::InvalidRange)),134 }135 }136137 138 pub fn bytes4(&mut self) -> Result<[u8; 4]> {139 self.read_padright()140 }141142 143 pub fn bytes(&mut self) -> Result<Vec<u8>> {144 let mut subresult = self.subresult(None)?;145 let length = subresult.uint32()? as usize;146 if subresult.buf.len() < subresult.offset + length {147 return Err(Error::Error(ExitError::OutOfOffset));148 }149 Ok(subresult.buf[subresult.offset..subresult.offset + length].into())150 }151152 153 pub fn string(&mut self) -> Result<string> {154 string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))155 }156157 158 pub fn uint8(&mut self) -> Result<u8> {159 Ok(self.read_padleft::<1>()?[0])160 }161162 163 pub fn uint32(&mut self) -> Result<u32> {164 Ok(u32::from_be_bytes(self.read_padleft()?))165 }166167 168 pub fn uint128(&mut self) -> Result<u128> {169 Ok(u128::from_be_bytes(self.read_padleft()?))170 }171172 173 pub fn uint256(&mut self) -> Result<U256> {174 let buf: [u8; 32] = self.read_padleft()?;175 Ok(U256::from_big_endian(&buf))176 }177178 179 pub fn uint64(&mut self) -> Result<u64> {180 Ok(u64::from_be_bytes(self.read_padleft()?))181 }182183 184 #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]185 pub fn read_usize(&mut self) -> Result<usize> {186 Ok(usize::from_be_bytes(self.read_padleft()?))187 }188189 190 191 fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {192 let subresult_offset = self.subresult_offset;193 let offset = if let Some(size) = size {194 self.offset += size;195 self.subresult_offset += size;196 0197 } else {198 self.uint32()? as usize199 };200201 if offset + self.subresult_offset > self.buf.len() {202 return Err(Error::Error(ExitError::InvalidRange));203 }204205 let new_offset = offset + subresult_offset;206 Ok(AbiReader {207 buf: self.buf,208 subresult_offset: new_offset,209 offset: new_offset,210 })211 }212213 214 pub fn is_finished(&self) -> bool {215 self.buf.len() == self.offset216 }217}218219220#[derive(Default)]221pub struct AbiWriter {222 static_part: Vec<u8>,223 dynamic_part: Vec<(usize, AbiWriter)>,224 had_call: bool,225 is_dynamic: bool,226}227impl AbiWriter {228 229 pub fn new() -> Self {230 Self::default()231 }232233 234 pub fn new_dynamic(is_dynamic: bool) -> Self {235 Self {236 is_dynamic,237 ..Default::default()238 }239 }240 241 pub fn new_call(method_id: u32) -> Self {242 let mut val = Self::new();243 val.static_part.extend(&method_id.to_be_bytes());244 val.had_call = true;245 val246 }247248 fn write_padleft(&mut self, block: &[u8]) {249 assert!(block.len() <= ABI_ALIGNMENT);250 self.static_part251 .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);252 self.static_part.extend(block);253 }254255 fn write_padright(&mut self, block: &[u8]) {256 assert!(block.len() <= ABI_ALIGNMENT);257 self.static_part.extend(block);258 self.static_part259 .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);260 }261262 263 pub fn address(&mut self, address: &H160) {264 self.write_padleft(&address.0)265 }266267 268 pub fn bool(&mut self, value: &bool) {269 self.write_padleft(&[if *value { 1 } else { 0 }])270 }271272 273 pub fn uint8(&mut self, value: &u8) {274 self.write_padleft(&[*value])275 }276277 278 pub fn uint32(&mut self, value: &u32) {279 self.write_padleft(&u32::to_be_bytes(*value))280 }281282 283 pub fn uint128(&mut self, value: &u128) {284 self.write_padleft(&u128::to_be_bytes(*value))285 }286287 288 pub fn uint256(&mut self, value: &U256) {289 let mut out = [0; 32];290 value.to_big_endian(&mut out);291 self.write_padleft(&out)292 }293294 295 #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]296 pub fn write_usize(&mut self, value: &usize) {297 self.write_padleft(&usize::to_be_bytes(*value))298 }299300 301 pub fn write_subresult(&mut self, result: Self) {302 self.dynamic_part.push((self.static_part.len(), result));303 304 self.write_padleft(&[]);305 }306307 fn memory(&mut self, value: &[u8]) {308 let mut sub = Self::new();309 sub.uint32(&(value.len() as u32));310 for chunk in value.chunks(ABI_ALIGNMENT) {311 sub.write_padright(chunk);312 }313 self.write_subresult(sub);314 }315316 317 pub fn string(&mut self, value: &str) {318 self.memory(value.as_bytes())319 }320321 322 pub fn bytes(&mut self, value: &[u8]) {323 self.memory(value)324 }325326 327 pub fn finish(mut self) -> Vec<u8> {328 for (static_offset, part) in self.dynamic_part {329 let part_offset = self.static_part.len()330 - if self.had_call { 4 } else { 0 }331 - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };332333 let encoded_dynamic_offset = usize::to_be_bytes(part_offset);334 let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();335 let stop = static_offset + ABI_ALIGNMENT;336 self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);337 self.static_part.extend(part.finish())338 }339 self.static_part340 }341}342343344345346347348pub trait AbiRead<T> {349 350 fn abi_read(&mut self) -> Result<T>;351}352353macro_rules! impl_abi_readable {354 ($ty:ty, $method:ident, $dynamic:literal) => {355 impl TypeHelper for $ty {356 fn is_dynamic() -> bool {357 $dynamic358 }359360 fn size() -> usize {361 ABI_ALIGNMENT362 }363 }364 impl AbiRead<$ty> for AbiReader<'_> {365 fn abi_read(&mut self) -> Result<$ty> {366 self.$method()367 }368 }369 };370}371372impl_abi_readable!(bool, bool, false);373impl_abi_readable!(uint8, uint8, false);374impl_abi_readable!(uint32, uint32, false);375impl_abi_readable!(uint64, uint64, false);376impl_abi_readable!(uint128, uint128, false);377impl_abi_readable!(uint256, uint256, false);378impl_abi_readable!(bytes4, bytes4, false);379impl_abi_readable!(address, address, false);380impl_abi_readable!(string, string, true);381382383impl TypeHelper for bytes {384 fn is_dynamic() -> bool {385 true386 }387 fn size() -> usize {388 ABI_ALIGNMENT389 }390}391impl AbiRead<bytes> for AbiReader<'_> {392 fn abi_read(&mut self) -> Result<bytes> {393 Ok(bytes(self.bytes()?))394 }395}396397mod sealed {398 399 pub trait CanBePlacedInVec {}400}401402impl sealed::CanBePlacedInVec for U256 {}403impl sealed::CanBePlacedInVec for string {}404impl sealed::CanBePlacedInVec for H160 {}405406impl<R: sealed::CanBePlacedInVec> AbiRead<Vec<R>> for AbiReader<'_>407where408 Self: AbiRead<R>,409{410 fn abi_read(&mut self) -> Result<Vec<R>> {411 let mut sub = self.subresult(None)?;412 let size = sub.uint32()? as usize;413 sub.subresult_offset = sub.offset;414 let mut out = Vec::with_capacity(size);415 for _ in 0..size {416 out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);417 }418 Ok(out)419 }420}421422macro_rules! impl_tuples {423 ($($ident:ident)+) => {424 impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+)425 where426 $(427 $ident: TypeHelper,428 )+429 {430 fn is_dynamic() -> bool {431 false432 $(433 || <$ident>::is_dynamic()434 )*435 }436437 fn size() -> usize {438 0 $(+ <$ident>::size())+439 }440 }441 impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}442 impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>443 where444 $(445 Self: AbiRead<$ident>,446 )+447 ($($ident,)+): TypeHelper,448 {449 fn abi_read(&mut self) -> Result<($($ident,)+)> {450 let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };451 let mut subresult = self.subresult(size)?;452 Ok((453 $(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+454 ))455 }456 }457 #[allow(non_snake_case)]458 impl<$($ident),+> AbiWrite for ($($ident,)+)459 where460 $($ident: AbiWrite,)+461 {462 fn abi_write(&self, writer: &mut AbiWriter) {463 let ($($ident,)+) = self;464 if writer.is_dynamic {465 let mut sub = AbiWriter::new();466 $($ident.abi_write(&mut sub);)+467 writer.write_subresult(sub);468 } else {469 $($ident.abi_write(writer);)+470 }471 }472 }473 };474}475476impl_tuples! {A}477impl_tuples! {A B}478impl_tuples! {A B C}479impl_tuples! {A B C D}480impl_tuples! {A B C D E}481impl_tuples! {A B C D E F}482impl_tuples! {A B C D E F G}483impl_tuples! {A B C D E F G H}484impl_tuples! {A B C D E F G H I}485impl_tuples! {A B C D E F G H I J}486487488489pub trait AbiWrite {490 491 fn abi_write(&self, writer: &mut AbiWriter);492 493 494 fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {495 let mut writer = AbiWriter::new();496 self.abi_write(&mut writer);497 Ok(writer.into())498 }499}500501502503504505impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {506 fn abi_write(&self, _writer: &mut AbiWriter) {507 debug_assert!(false, "shouldn't be called, see comment")508 }509 fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {510 match self {511 Ok(v) => Ok(WithPostDispatchInfo {512 post_info: v.post_info.clone(),513 data: {514 let mut out = AbiWriter::new();515 v.data.abi_write(&mut out);516 out517 },518 }),519 Err(e) => Err(e.clone()),520 }521 }522}523524macro_rules! impl_abi_writeable {525 ($ty:ty, $method:ident) => {526 impl AbiWrite for $ty {527 fn abi_write(&self, writer: &mut AbiWriter) {528 writer.$method(&self)529 }530 }531 };532}533534impl_abi_writeable!(u8, uint8);535impl_abi_writeable!(u32, uint32);536impl_abi_writeable!(u128, uint128);537impl_abi_writeable!(U256, uint256);538impl_abi_writeable!(H160, address);539impl_abi_writeable!(bool, bool);540impl_abi_writeable!(&str, string);541542impl AbiWrite for string {543 fn abi_write(&self, writer: &mut AbiWriter) {544 writer.string(self)545 }546}547548impl AbiWrite for bytes {549 fn abi_write(&self, writer: &mut AbiWriter) {550 writer.bytes(self.0.as_slice())551 }552}553554impl<T: AbiWrite + TypeHelper> AbiWrite for Vec<T> {555 fn abi_write(&self, writer: &mut AbiWriter) {556 let is_dynamic = T::is_dynamic();557 let mut sub = if is_dynamic {558 AbiWriter::new_dynamic(is_dynamic)559 } else {560 AbiWriter::new()561 };562563 564 (self.len() as u32).abi_write(&mut sub);565566 for item in self {567 item.abi_write(&mut sub);568 }569 writer.write_subresult(sub);570 }571}572573impl AbiWrite for () {574 fn abi_write(&self, _writer: &mut AbiWriter) {}575}576577578#[deprecated]579#[macro_export]580macro_rules! abi_decode {581 ($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {582 $(583 let $name = $reader.$typ()?;584 )+585 }586}587588589#[deprecated]590#[macro_export]591macro_rules! abi_encode {592 ($($typ:ident($value:expr)),* $(,)?) => {{593 #[allow(unused_mut)]594 let mut writer = ::evm_coder::abi::AbiWriter::new();595 $(596 writer.$typ($value);597 )*598 writer599 }};600 (call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{601 #[allow(unused_mut)]602 let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);603 $(604 writer.$typ($value);605 )*606 writer607 }}608}609610#[cfg(test)]611pub mod test {612 use crate::{613 abi::{AbiRead, AbiWrite},614 types::*,615 };616617 use super::{AbiReader, AbiWriter};618 use hex_literal::hex;619 use primitive_types::{H160, U256};620 use concat_idents::concat_idents;621622 macro_rules! test_impl {623 ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {624 concat_idents!(test_name = encode_decode_, $name {625 #[test]626 fn test_name() {627 let function_identifier: u32 = $function_identifier;628 let decoded_data = $decoded_data;629 let encoded_data = $encoded_data;630631 let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();632 assert_eq!(call, u32::to_be_bytes(function_identifier));633 let data = <AbiReader<'_> as AbiRead<$type>>::abi_read(&mut decoder).unwrap();634 assert_eq!(data, decoded_data);635636 let mut writer = AbiWriter::new_call(function_identifier);637 decoded_data.abi_write(&mut writer);638 let ed = writer.finish();639 similar_asserts::assert_eq!(encoded_data, ed.as_slice());640 }641 });642 };643 }644645 macro_rules! test_impl_uint {646 ($type:ident) => {647 test_impl!(648 $type,649 $type,650 0xdeadbeef,651 255 as $type,652 &hex!(653 "654 deadbeef655 00000000000000000000000000000000000000000000000000000000000000ff656 "657 )658 );659 };660 }661662 test_impl_uint!(uint8);663 test_impl_uint!(uint32);664 test_impl_uint!(uint128);665666 test_impl!(667 uint256,668 uint256,669 0xdeadbeef,670 U256([255, 0, 0, 0]),671 &hex!(672 "673 deadbeef674 00000000000000000000000000000000000000000000000000000000000000ff675 "676 )677 );678679 test_impl!(680 vec_tuple_address_uint256,681 Vec<(address, uint256)>,682 0x1ACF2D55,683 vec![684 (685 H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),686 U256([10, 0, 0, 0]),687 ),688 (689 H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),690 U256([20, 0, 0, 0]),691 ),692 (693 H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),694 U256([30, 0, 0, 0]),695 ),696 ],697 &hex!(698 "699 1ACF2D55700 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]701 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]702 703 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address704 000000000000000000000000000000000000000000000000000000000000000A // uint256705 706 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address707 0000000000000000000000000000000000000000000000000000000000000014 // uint256708 709 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address710 000000000000000000000000000000000000000000000000000000000000001E // uint256711 "712 )713 );714715 test_impl!(716 vec_tuple_uint256_string,717 Vec<(uint256, string)>,718 0xdeadbeef,719 vec![720 (1.into(), "Test URI 0".to_string()),721 (11.into(), "Test URI 1".to_string()),722 (12.into(), "Test URI 2".to_string()),723 ],724 &hex!(725 "726 deadbeef727 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]728 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]729730 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem731 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem732 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem733734 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60735 0000000000000000000000000000000000000000000000000000000000000040 // offset of string736 000000000000000000000000000000000000000000000000000000000000000a // size of string737 5465737420555249203000000000000000000000000000000000000000000000 // string738739 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0740 0000000000000000000000000000000000000000000000000000000000000040 // offset of string741 000000000000000000000000000000000000000000000000000000000000000a // size of string742 5465737420555249203100000000000000000000000000000000000000000000 // string743744 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160745 0000000000000000000000000000000000000000000000000000000000000040 // offset of string746 000000000000000000000000000000000000000000000000000000000000000a // size of string747 5465737420555249203200000000000000000000000000000000000000000000 // string748 "749 )750 );751752 #[test]753 fn dynamic_after_static() {754 let mut encoder = AbiWriter::new();755 encoder.bool(&true);756 encoder.string("test");757 let encoded = encoder.finish();758759 let mut encoder = AbiWriter::new();760 encoder.bool(&true);761 762 encoder.uint32(&(32 * 2));763 764 encoder.uint32(&4);765 encoder.write_padright(&[b't', b'e', b's', b't']);766 let alternative_encoded = encoder.finish();767768 assert_eq!(encoded, alternative_encoded);769770 let mut decoder = AbiReader::new(&encoded);771 assert!(decoder.bool().unwrap());772 assert_eq!(decoder.string().unwrap(), "test");773 }774775 #[test]776 fn mint_sample() {777 let (call, mut decoder) = AbiReader::new_call(&hex!(778 "779 50bb4e7f780 000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374781 0000000000000000000000000000000000000000000000000000000000000001782 0000000000000000000000000000000000000000000000000000000000000060783 0000000000000000000000000000000000000000000000000000000000000008784 5465737420555249000000000000000000000000000000000000000000000000785 "786 ))787 .unwrap();788 assert_eq!(call, u32::to_be_bytes(0x50bb4e7f));789 assert_eq!(790 format!("{:?}", decoder.address().unwrap()),791 "0xad2c0954693c2b5404b7e50967d3481bea432374"792 );793 assert_eq!(decoder.uint32().unwrap(), 1);794 assert_eq!(decoder.string().unwrap(), "Test URI");795 }796797 #[test]798 fn parse_vec_with_dynamic_type() {799 let decoded_data = (800 0x36543006,801 vec![802 (1.into(), "Test URI 0".to_string()),803 (11.into(), "Test URI 1".to_string()),804 (12.into(), "Test URI 2".to_string()),805 ],806 );807808 let encoded_data = &hex!(809 "810 36543006811 00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address812 0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]813 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]814815 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem816 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem817 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem818819 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60820 0000000000000000000000000000000000000000000000000000000000000040 // offset of string821 000000000000000000000000000000000000000000000000000000000000000a // size of string822 5465737420555249203000000000000000000000000000000000000000000000 // string823824 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0825 0000000000000000000000000000000000000000000000000000000000000040 // offset of string826 000000000000000000000000000000000000000000000000000000000000000a // size of string827 5465737420555249203100000000000000000000000000000000000000000000 // string828829 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160830 0000000000000000000000000000000000000000000000000000000000000040 // offset of string831 000000000000000000000000000000000000000000000000000000000000000a // size of string832 5465737420555249203200000000000000000000000000000000000000000000 // string833 "834 );835836 let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();837 assert_eq!(call, u32::to_be_bytes(decoded_data.0));838 let address = decoder.address().unwrap();839 let data =840 <AbiReader<'_> as AbiRead<Vec<(uint256, string)>>>::abi_read(&mut decoder).unwrap();841 assert_eq!(data, decoded_data.1);842843 let mut writer = AbiWriter::new_call(decoded_data.0);844 address.abi_write(&mut writer);845 decoded_data.1.abi_write(&mut writer);846 let ed = writer.finish();847 similar_asserts::assert_eq!(encoded_data, ed.as_slice());848 }849}