git.delta.rocks / unique-network / refs/commits / 4eb90d8b0eec

difftreelog

source

crates/evm-coder/src/abi.rs12.0 KiBsourcehistory
1//! TODO: I misunterstood therminology, abi IS rlp encoded, so2//! this module should be replaced with rlp crate34#![allow(dead_code)]56#[cfg(not(feature = "std"))]7use alloc::{8	string::{String, ToString},9	vec::Vec,10};11use evm_core::ExitError;12use primitive_types::{H160, U256};1314use crate::{execution::Error, types::string};15use crate::execution::Result;1617const ABI_ALIGNMENT: usize = 32;1819#[derive(Clone)]20pub struct AbiReader<'i> {21	buf: &'i [u8],22	subresult_offset: usize,23	offset: usize,24}25impl<'i> AbiReader<'i> {26	pub fn new(buf: &'i [u8]) -> Self {27		Self {28			buf,29			subresult_offset: 0,30			offset: 0,31		}32	}33	pub fn new_call(buf: &'i [u8]) -> Result<(u32, Self)> {34		if buf.len() < 4 {35			return Err(Error::Error(ExitError::OutOfOffset));36		}37		let mut method_id = [0; 4];38		method_id.copy_from_slice(&buf[0..4]);3940		Ok((41			u32::from_be_bytes(method_id),42			Self {43				buf,44				subresult_offset: 4,45				offset: 4,46			},47		))48	}4950	fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {51		if self.buf.len() - self.offset < ABI_ALIGNMENT {52			return Err(Error::Error(ExitError::OutOfOffset));53		}54		let mut block = [0; S];55		// Verify padding is empty56		if !self.buf[self.offset..self.offset + ABI_ALIGNMENT - S]57			.iter()58			.all(|&v| v == 0)59		{60			return Err(Error::Error(ExitError::InvalidRange));61		}62		block.copy_from_slice(63			&self.buf[self.offset + ABI_ALIGNMENT - S..self.offset + ABI_ALIGNMENT],64		);65		self.offset += ABI_ALIGNMENT;66		Ok(block)67	}6869	pub fn address(&mut self) -> Result<H160> {70		Ok(H160(self.read_padleft()?))71	}7273	pub fn bool(&mut self) -> Result<bool> {74		let data: [u8; 1] = self.read_padleft()?;75		match data[0] {76			0 => Ok(false),77			1 => Ok(true),78			_ => Err(Error::Error(ExitError::InvalidRange)),79		}80	}8182	pub fn bytes4(&mut self) -> Result<[u8; 4]> {83		self.read_padleft()84	}8586	pub fn bytes(&mut self) -> Result<Vec<u8>> {87		let mut subresult = self.subresult()?;88		let length = subresult.read_usize()?;89		if subresult.buf.len() <= subresult.offset + length {90			return Err(Error::Error(ExitError::OutOfOffset));91		}92		Ok(subresult.buf[subresult.offset..subresult.offset + length].into())93	}94	pub fn string(&mut self) -> Result<string> {95		string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))96	}9798	pub fn uint32(&mut self) -> Result<u32> {99		Ok(u32::from_be_bytes(self.read_padleft()?))100	}101102	pub fn uint128(&mut self) -> Result<u128> {103		Ok(u128::from_be_bytes(self.read_padleft()?))104	}105106	pub fn uint256(&mut self) -> Result<U256> {107		let buf: [u8; 32] = self.read_padleft()?;108		Ok(U256::from_big_endian(&buf))109	}110111	pub fn uint64(&mut self) -> Result<u64> {112		Ok(u64::from_be_bytes(self.read_padleft()?))113	}114115	pub fn read_usize(&mut self) -> Result<usize> {116		Ok(usize::from_be_bytes(self.read_padleft()?))117	}118119	fn subresult(&mut self) -> Result<AbiReader<'i>> {120		let offset = self.read_usize()?;121		if offset + self.subresult_offset > self.buf.len() {122			return Err(Error::Error(ExitError::InvalidRange));123		}124		Ok(AbiReader {125			buf: self.buf,126			subresult_offset: offset + self.subresult_offset,127			offset: offset + self.subresult_offset,128		})129	}130131	pub fn is_finished(&self) -> bool {132		self.buf.len() == self.offset133	}134}135136#[derive(Default)]137pub struct AbiWriter {138	static_part: Vec<u8>,139	dynamic_part: Vec<(usize, AbiWriter)>,140}141impl AbiWriter {142	pub fn new() -> Self {143		Self::default()144	}145	pub fn new_call(method_id: u32) -> Self {146		let mut val = Self::new();147		val.static_part.extend(&method_id.to_be_bytes());148		val149	}150151	fn write_padleft(&mut self, block: &[u8]) {152		assert!(block.len() <= ABI_ALIGNMENT);153		self.static_part154			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);155		self.static_part.extend(block);156	}157158	fn write_padright(&mut self, bytes: &[u8]) {159		assert!(bytes.len() <= ABI_ALIGNMENT);160		self.static_part.extend(bytes);161		self.static_part162			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);163	}164165	pub fn address(&mut self, address: &H160) {166		self.write_padleft(&address.0)167	}168169	pub fn bool(&mut self, value: &bool) {170		self.write_padleft(&[if *value { 1 } else { 0 }])171	}172173	pub fn uint8(&mut self, value: &u8) {174		self.write_padleft(&[*value])175	}176177	pub fn uint32(&mut self, value: &u32) {178		self.write_padleft(&u32::to_be_bytes(*value))179	}180181	pub fn uint128(&mut self, value: &u128) {182		self.write_padleft(&u128::to_be_bytes(*value))183	}184185	pub fn uint256(&mut self, value: &U256) {186		let mut out = [0; 32];187		value.to_big_endian(&mut out);188		self.write_padleft(&out)189	}190191	pub fn write_usize(&mut self, value: &usize) {192		self.write_padleft(&usize::to_be_bytes(*value))193	}194195	pub fn write_subresult(&mut self, result: Self) {196		self.dynamic_part.push((self.static_part.len(), result));197		// Empty block, to be filled later198		self.write_padleft(&[]);199	}200201	pub fn memory(&mut self, value: &[u8]) {202		let mut sub = Self::new();203		sub.write_usize(&value.len());204		for chunk in value.chunks(ABI_ALIGNMENT) {205			sub.write_padright(chunk);206		}207		self.write_subresult(sub);208	}209210	pub fn string(&mut self, value: &str) {211		self.memory(value.as_bytes())212	}213214	pub fn bytes(&mut self, value: &[u8]) {215		self.memory(value)216	}217218	pub fn finish(mut self) -> Vec<u8> {219		for (static_offset, part) in self.dynamic_part {220			let part_offset = self.static_part.len();221222			let encoded_dynamic_offset = usize::to_be_bytes(part_offset);223			self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()224				..static_offset + ABI_ALIGNMENT]225				.copy_from_slice(&encoded_dynamic_offset);226			self.static_part.extend(part.finish())227		}228		self.static_part229	}230}231232pub trait AbiRead<T> {233	fn abi_read(&mut self) -> Result<T>;234}235236macro_rules! impl_abi_readable {237	($ty:ty, $method:ident) => {238		impl AbiRead<$ty> for AbiReader<'_> {239			fn abi_read(&mut self) -> Result<$ty> {240				self.$method()241			}242		}243	};244}245246impl_abi_readable!(u32, uint32);247impl_abi_readable!(u128, uint128);248impl_abi_readable!(U256, uint256);249impl_abi_readable!(H160, address);250impl_abi_readable!(Vec<u8>, bytes);251impl_abi_readable!(bool, bool);252impl_abi_readable!(string, string);253254mod sealed {255	/// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead256	pub trait CanBePlacedInVec {}257}258259impl sealed::CanBePlacedInVec for U256 {}260impl sealed::CanBePlacedInVec for string {}261impl sealed::CanBePlacedInVec for H160 {}262263impl<R: sealed::CanBePlacedInVec> AbiRead<Vec<R>> for AbiReader<'_>264where265	Self: AbiRead<R>,266{267	fn abi_read(&mut self) -> Result<Vec<R>> {268		let mut sub = self.subresult()?;269		let size = sub.read_usize()?;270		sub.subresult_offset = sub.offset;271		let mut out = Vec::with_capacity(size);272		for _ in 0..size {273			out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);274		}275		Ok(out)276	}277}278279macro_rules! impl_tuples {280	($($ident:ident)+) => {281		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}282		impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>283		where284			$(Self: AbiRead<$ident>),+285		{286			fn abi_read(&mut self) -> Result<($($ident,)+)> {287				let mut subresult = self.subresult()?;288				Ok((289					$(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+290				))291			}292		}293	};294}295296impl_tuples! {A}297impl_tuples! {A B}298impl_tuples! {A B C}299impl_tuples! {A B C D}300impl_tuples! {A B C D E}301impl_tuples! {A B C D E F}302impl_tuples! {A B C D E F G}303impl_tuples! {A B C D E F G H}304impl_tuples! {A B C D E F G H I}305impl_tuples! {A B C D E F G H I J}306307pub trait AbiWrite {308	fn abi_write(&self, writer: &mut AbiWriter);309}310311macro_rules! impl_abi_writeable {312	($ty:ty, $method:ident) => {313		impl AbiWrite for $ty {314			fn abi_write(&self, writer: &mut AbiWriter) {315				writer.$method(&self)316			}317		}318	};319}320321impl_abi_writeable!(u8, uint8);322impl_abi_writeable!(u32, uint32);323impl_abi_writeable!(u128, uint128);324impl_abi_writeable!(U256, uint256);325impl_abi_writeable!(H160, address);326impl_abi_writeable!(bool, bool);327impl_abi_writeable!(&str, string);328impl AbiWrite for &string {329	fn abi_write(&self, writer: &mut AbiWriter) {330		writer.string(self)331	}332}333impl AbiWrite for &Vec<u8> {334	fn abi_write(&self, writer: &mut AbiWriter) {335		writer.bytes(self)336	}337}338339impl AbiWrite for () {340	fn abi_write(&self, _writer: &mut AbiWriter) {}341}342343#[macro_export]344macro_rules! abi_decode {345	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {346		$(347			let $name = $reader.$typ()?;348		)+349	}350}351#[macro_export]352macro_rules! abi_encode {353	($($typ:ident($value:expr)),* $(,)?) => {{354		#[allow(unused_mut)]355		let mut writer = ::evm_coder::abi::AbiWriter::new();356		$(357			writer.$typ($value);358		)*359		writer360	}};361	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{362		#[allow(unused_mut)]363		let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);364		$(365			writer.$typ($value);366		)*367		writer368	}}369}370371#[cfg(test)]372pub mod test {373	use crate::{374		abi::AbiRead,375		types::{string, uint256},376	};377378	use super::{AbiReader, AbiWriter};379	use hex_literal::hex;380381	#[test]382	fn dynamic_after_static() {383		let mut encoder = AbiWriter::new();384		encoder.bool(&true);385		encoder.string("test");386		let encoded = encoder.finish();387388		let mut encoder = AbiWriter::new();389		encoder.bool(&true);390		// Offset to subresult391		encoder.uint32(&(32 * 2));392		// Len of "test"393		encoder.uint32(&4);394		encoder.write_padright(&[b't', b'e', b's', b't']);395		let alternative_encoded = encoder.finish();396397		assert_eq!(encoded, alternative_encoded);398399		let mut decoder = AbiReader::new(&encoded);400		assert_eq!(decoder.bool().unwrap(), true);401		assert_eq!(decoder.string().unwrap(), "test");402	}403404	#[test]405	fn mint_sample() {406		let (call, mut decoder) = AbiReader::new_call(&hex!(407			"408				50bb4e7f409				000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374410				0000000000000000000000000000000000000000000000000000000000000001411				0000000000000000000000000000000000000000000000000000000000000060412				0000000000000000000000000000000000000000000000000000000000000008413				5465737420555249000000000000000000000000000000000000000000000000414			"415		))416		.unwrap();417		assert_eq!(call, 0x50bb4e7f);418		assert_eq!(419			format!("{:?}", decoder.address().unwrap()),420			"0xad2c0954693c2b5404b7e50967d3481bea432374"421		);422		assert_eq!(decoder.uint32().unwrap(), 1);423		assert_eq!(decoder.string().unwrap(), "Test URI");424	}425426	#[test]427	fn mint_bulk() {428		let (call, mut decoder) = AbiReader::new_call(&hex!(429			"430				36543006431				00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address432				0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]433				0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]434435				0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem436				00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem437				0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem438439				0000000000000000000000000000000000000000000000000000000000000001 // first token id?   					#60440				0000000000000000000000000000000000000000000000000000000000000040 // offset of string441				000000000000000000000000000000000000000000000000000000000000000a // size of string442				5465737420555249203000000000000000000000000000000000000000000000 // string443444				000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11?			#e0445				0000000000000000000000000000000000000000000000000000000000000040 // offset of string446				000000000000000000000000000000000000000000000000000000000000000a // size of string447				5465737420555249203100000000000000000000000000000000000000000000 // string448449				000000000000000000000000000000000000000000000000000000000000000c // third token id?  Why ==12?			#160450				0000000000000000000000000000000000000000000000000000000000000040 // offset of string451				000000000000000000000000000000000000000000000000000000000000000a // size of string452				5465737420555249203200000000000000000000000000000000000000000000 // string453			"454		))455		.unwrap();456		assert_eq!(call, 0x36543006);457		let _ = decoder.address().unwrap();458		let data =459			<AbiReader<'_> as AbiRead<Vec<(uint256, string)>>>::abi_read(&mut decoder).unwrap();460		assert_eq!(461			data,462			vec![463				(1.into(), "Test URI 0".to_string()),464				(11.into(), "Test URI 1".to_string()),465				(12.into(), "Test URI 2".to_string())466			]467		);468	}469}