git.delta.rocks / unique-network / refs/commits / a5075eaae1f3

difftreelog

source

crates/evm-coder/src/abi.rs13.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::{15	execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},16	types::string,17};18use crate::execution::Result;1920const ABI_ALIGNMENT: usize = 32;2122#[derive(Clone)]23pub struct AbiReader<'i> {24	buf: &'i [u8],25	subresult_offset: usize,26	offset: usize,27}28impl<'i> AbiReader<'i> {29	pub fn new(buf: &'i [u8]) -> Self {30		Self {31			buf,32			subresult_offset: 0,33			offset: 0,34		}35	}36	pub fn new_call(buf: &'i [u8]) -> Result<(u32, Self)> {37		if buf.len() < 4 {38			return Err(Error::Error(ExitError::OutOfOffset));39		}40		let mut method_id = [0; 4];41		method_id.copy_from_slice(&buf[0..4]);4243		Ok((44			u32::from_be_bytes(method_id),45			Self {46				buf,47				subresult_offset: 4,48				offset: 4,49			},50		))51	}5253	fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {54		if self.buf.len() - self.offset < ABI_ALIGNMENT {55			return Err(Error::Error(ExitError::OutOfOffset));56		}57		let mut block = [0; S];58		// Verify padding is empty59		if !self.buf[self.offset..self.offset + ABI_ALIGNMENT - S]60			.iter()61			.all(|&v| v == 0)62		{63			return Err(Error::Error(ExitError::InvalidRange));64		}65		block.copy_from_slice(66			&self.buf[self.offset + ABI_ALIGNMENT - S..self.offset + ABI_ALIGNMENT],67		);68		self.offset += ABI_ALIGNMENT;69		Ok(block)70	}7172	pub fn address(&mut self) -> Result<H160> {73		Ok(H160(self.read_padleft()?))74	}7576	pub fn bool(&mut self) -> Result<bool> {77		let data: [u8; 1] = self.read_padleft()?;78		match data[0] {79			0 => Ok(false),80			1 => Ok(true),81			_ => Err(Error::Error(ExitError::InvalidRange)),82		}83	}8485	pub fn bytes4(&mut self) -> Result<[u8; 4]> {86		self.read_padleft()87	}8889	pub fn bytes(&mut self) -> Result<Vec<u8>> {90		let mut subresult = self.subresult()?;91		let length = subresult.read_usize()?;92		if subresult.buf.len() <= subresult.offset + length {93			return Err(Error::Error(ExitError::OutOfOffset));94		}95		Ok(subresult.buf[subresult.offset..subresult.offset + length].into())96	}97	pub fn string(&mut self) -> Result<string> {98		string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))99	}100101	pub fn uint32(&mut self) -> Result<u32> {102		Ok(u32::from_be_bytes(self.read_padleft()?))103	}104105	pub fn uint128(&mut self) -> Result<u128> {106		Ok(u128::from_be_bytes(self.read_padleft()?))107	}108109	pub fn uint256(&mut self) -> Result<U256> {110		let buf: [u8; 32] = self.read_padleft()?;111		Ok(U256::from_big_endian(&buf))112	}113114	pub fn uint64(&mut self) -> Result<u64> {115		Ok(u64::from_be_bytes(self.read_padleft()?))116	}117118	pub fn read_usize(&mut self) -> Result<usize> {119		Ok(usize::from_be_bytes(self.read_padleft()?))120	}121122	fn subresult(&mut self) -> Result<AbiReader<'i>> {123		let offset = self.read_usize()?;124		if offset + self.subresult_offset > self.buf.len() {125			return Err(Error::Error(ExitError::InvalidRange));126		}127		Ok(AbiReader {128			buf: self.buf,129			subresult_offset: offset + self.subresult_offset,130			offset: offset + self.subresult_offset,131		})132	}133134	pub fn is_finished(&self) -> bool {135		self.buf.len() == self.offset136	}137}138139#[derive(Default)]140pub struct AbiWriter {141	static_part: Vec<u8>,142	dynamic_part: Vec<(usize, AbiWriter)>,143}144impl AbiWriter {145	pub fn new() -> Self {146		Self::default()147	}148	pub fn new_call(method_id: u32) -> Self {149		let mut val = Self::new();150		val.static_part.extend(&method_id.to_be_bytes());151		val152	}153154	fn write_padleft(&mut self, block: &[u8]) {155		assert!(block.len() <= ABI_ALIGNMENT);156		self.static_part157			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);158		self.static_part.extend(block);159	}160161	fn write_padright(&mut self, bytes: &[u8]) {162		assert!(bytes.len() <= ABI_ALIGNMENT);163		self.static_part.extend(bytes);164		self.static_part165			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);166	}167168	pub fn address(&mut self, address: &H160) {169		self.write_padleft(&address.0)170	}171172	pub fn bool(&mut self, value: &bool) {173		self.write_padleft(&[if *value { 1 } else { 0 }])174	}175176	pub fn uint8(&mut self, value: &u8) {177		self.write_padleft(&[*value])178	}179180	pub fn uint32(&mut self, value: &u32) {181		self.write_padleft(&u32::to_be_bytes(*value))182	}183184	pub fn uint128(&mut self, value: &u128) {185		self.write_padleft(&u128::to_be_bytes(*value))186	}187188	pub fn uint256(&mut self, value: &U256) {189		let mut out = [0; 32];190		value.to_big_endian(&mut out);191		self.write_padleft(&out)192	}193194	pub fn write_usize(&mut self, value: &usize) {195		self.write_padleft(&usize::to_be_bytes(*value))196	}197198	pub fn write_subresult(&mut self, result: Self) {199		self.dynamic_part.push((self.static_part.len(), result));200		// Empty block, to be filled later201		self.write_padleft(&[]);202	}203204	pub fn memory(&mut self, value: &[u8]) {205		let mut sub = Self::new();206		sub.write_usize(&value.len());207		for chunk in value.chunks(ABI_ALIGNMENT) {208			sub.write_padright(chunk);209		}210		self.write_subresult(sub);211	}212213	pub fn string(&mut self, value: &str) {214		self.memory(value.as_bytes())215	}216217	pub fn bytes(&mut self, value: &[u8]) {218		self.memory(value)219	}220221	pub fn finish(mut self) -> Vec<u8> {222		for (static_offset, part) in self.dynamic_part {223			let part_offset = self.static_part.len();224225			let encoded_dynamic_offset = usize::to_be_bytes(part_offset);226			self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()227				..static_offset + ABI_ALIGNMENT]228				.copy_from_slice(&encoded_dynamic_offset);229			self.static_part.extend(part.finish())230		}231		self.static_part232	}233}234235pub trait AbiRead<T> {236	fn abi_read(&mut self) -> Result<T>;237}238239macro_rules! impl_abi_readable {240	($ty:ty, $method:ident) => {241		impl AbiRead<$ty> for AbiReader<'_> {242			fn abi_read(&mut self) -> Result<$ty> {243				self.$method()244			}245		}246	};247}248249impl_abi_readable!(u32, uint32);250impl_abi_readable!(u64, uint64);251impl_abi_readable!(u128, uint128);252impl_abi_readable!(U256, uint256);253impl_abi_readable!(H160, address);254impl_abi_readable!(Vec<u8>, bytes);255impl_abi_readable!(bool, bool);256impl_abi_readable!(string, string);257258mod sealed {259	/// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead260	pub trait CanBePlacedInVec {}261}262263impl sealed::CanBePlacedInVec for U256 {}264impl sealed::CanBePlacedInVec for string {}265impl sealed::CanBePlacedInVec for H160 {}266267impl<R: sealed::CanBePlacedInVec> AbiRead<Vec<R>> for AbiReader<'_>268where269	Self: AbiRead<R>,270{271	fn abi_read(&mut self) -> Result<Vec<R>> {272		let mut sub = self.subresult()?;273		let size = sub.read_usize()?;274		sub.subresult_offset = sub.offset;275		let mut out = Vec::with_capacity(size);276		for _ in 0..size {277			out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);278		}279		Ok(out)280	}281}282283macro_rules! impl_tuples {284	($($ident:ident)+) => {285		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}286		impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>287		where288			$(Self: AbiRead<$ident>),+289		{290			fn abi_read(&mut self) -> Result<($($ident,)+)> {291				let mut subresult = self.subresult()?;292				Ok((293					$(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+294				))295			}296		}297	};298}299300impl_tuples! {A}301impl_tuples! {A B}302impl_tuples! {A B C}303impl_tuples! {A B C D}304impl_tuples! {A B C D E}305impl_tuples! {A B C D E F}306impl_tuples! {A B C D E F G}307impl_tuples! {A B C D E F G H}308impl_tuples! {A B C D E F G H I}309impl_tuples! {A B C D E F G H I J}310311pub trait AbiWrite {312	fn abi_write(&self, writer: &mut AbiWriter);313	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {314		let mut writer = AbiWriter::new();315		self.abi_write(&mut writer);316		Ok(writer.into())317	}318}319320impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {321	// this particular AbiWrite implementation should be split to another trait,322	// which only implements [`to_result`]323	//324	// But due to lack of specialization feature in stable Rust, we can't have325	// blanket impl of this trait `for T where T: AbiWrite`, so here we abusing326	// default trait methods for it327	fn abi_write(&self, _writer: &mut AbiWriter) {328		debug_assert!(false, "shouldn't be called, see comment")329	}330	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {331		match self {332			Ok(v) => Ok(WithPostDispatchInfo {333				post_info: v.post_info.clone(),334				data: {335					let mut out = AbiWriter::new();336					v.data.abi_write(&mut out);337					out338				},339			}),340			Err(e) => Err(e.clone()),341		}342	}343}344345macro_rules! impl_abi_writeable {346	($ty:ty, $method:ident) => {347		impl AbiWrite for $ty {348			fn abi_write(&self, writer: &mut AbiWriter) {349				writer.$method(&self)350			}351		}352	};353}354355impl_abi_writeable!(u8, uint8);356impl_abi_writeable!(u32, uint32);357impl_abi_writeable!(u128, uint128);358impl_abi_writeable!(U256, uint256);359impl_abi_writeable!(H160, address);360impl_abi_writeable!(bool, bool);361impl_abi_writeable!(&str, string);362impl AbiWrite for &string {363	fn abi_write(&self, writer: &mut AbiWriter) {364		writer.string(self)365	}366}367impl AbiWrite for &Vec<u8> {368	fn abi_write(&self, writer: &mut AbiWriter) {369		writer.bytes(self)370	}371}372373impl AbiWrite for () {374	fn abi_write(&self, _writer: &mut AbiWriter) {}375}376377#[macro_export]378macro_rules! abi_decode {379	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {380		$(381			let $name = $reader.$typ()?;382		)+383	}384}385#[macro_export]386macro_rules! abi_encode {387	($($typ:ident($value:expr)),* $(,)?) => {{388		#[allow(unused_mut)]389		let mut writer = ::evm_coder::abi::AbiWriter::new();390		$(391			writer.$typ($value);392		)*393		writer394	}};395	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{396		#[allow(unused_mut)]397		let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);398		$(399			writer.$typ($value);400		)*401		writer402	}}403}404405#[cfg(test)]406pub mod test {407	use crate::{408		abi::AbiRead,409		types::{string, uint256},410	};411412	use super::{AbiReader, AbiWriter};413	use hex_literal::hex;414415	#[test]416	fn dynamic_after_static() {417		let mut encoder = AbiWriter::new();418		encoder.bool(&true);419		encoder.string("test");420		let encoded = encoder.finish();421422		let mut encoder = AbiWriter::new();423		encoder.bool(&true);424		// Offset to subresult425		encoder.uint32(&(32 * 2));426		// Len of "test"427		encoder.uint32(&4);428		encoder.write_padright(&[b't', b'e', b's', b't']);429		let alternative_encoded = encoder.finish();430431		assert_eq!(encoded, alternative_encoded);432433		let mut decoder = AbiReader::new(&encoded);434		assert_eq!(decoder.bool().unwrap(), true);435		assert_eq!(decoder.string().unwrap(), "test");436	}437438	#[test]439	fn mint_sample() {440		let (call, mut decoder) = AbiReader::new_call(&hex!(441			"442				50bb4e7f443				000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374444				0000000000000000000000000000000000000000000000000000000000000001445				0000000000000000000000000000000000000000000000000000000000000060446				0000000000000000000000000000000000000000000000000000000000000008447				5465737420555249000000000000000000000000000000000000000000000000448			"449		))450		.unwrap();451		assert_eq!(call, 0x50bb4e7f);452		assert_eq!(453			format!("{:?}", decoder.address().unwrap()),454			"0xad2c0954693c2b5404b7e50967d3481bea432374"455		);456		assert_eq!(decoder.uint32().unwrap(), 1);457		assert_eq!(decoder.string().unwrap(), "Test URI");458	}459460	#[test]461	fn mint_bulk() {462		let (call, mut decoder) = AbiReader::new_call(&hex!(463			"464				36543006465				00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address466				0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]467				0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]468469				0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem470				00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem471				0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem472473				0000000000000000000000000000000000000000000000000000000000000001 // first token id?   					#60474				0000000000000000000000000000000000000000000000000000000000000040 // offset of string475				000000000000000000000000000000000000000000000000000000000000000a // size of string476				5465737420555249203000000000000000000000000000000000000000000000 // string477478				000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11?			#e0479				0000000000000000000000000000000000000000000000000000000000000040 // offset of string480				000000000000000000000000000000000000000000000000000000000000000a // size of string481				5465737420555249203100000000000000000000000000000000000000000000 // string482483				000000000000000000000000000000000000000000000000000000000000000c // third token id?  Why ==12?			#160484				0000000000000000000000000000000000000000000000000000000000000040 // offset of string485				000000000000000000000000000000000000000000000000000000000000000a // size of string486				5465737420555249203200000000000000000000000000000000000000000000 // string487			"488		))489		.unwrap();490		assert_eq!(call, 0x36543006);491		let _ = decoder.address().unwrap();492		let data =493			<AbiReader<'_> as AbiRead<Vec<(uint256, string)>>>::abi_read(&mut decoder).unwrap();494		assert_eq!(495			data,496			vec![497				(1.into(), "Test URI 0".to_string()),498				(11.into(), "Test URI 1".to_string()),499				(12.into(), "Test URI 2".to_string())500			]501		);502	}503}