git.delta.rocks / unique-network / refs/commits / 8fee3684a030

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::vec::Vec;8use evm_core::ExitError;9use primitive_types::{H160, U256};1011use crate::{12	execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},13	types::string,14};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!(u64, uint64);248impl_abi_readable!(u128, uint128);249impl_abi_readable!(U256, uint256);250impl_abi_readable!(H160, address);251impl_abi_readable!(Vec<u8>, bytes);252impl_abi_readable!(bool, bool);253impl_abi_readable!(string, string);254255mod sealed {256	/// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead257	pub trait CanBePlacedInVec {}258}259260impl sealed::CanBePlacedInVec for U256 {}261impl sealed::CanBePlacedInVec for string {}262impl sealed::CanBePlacedInVec for H160 {}263264impl<R: sealed::CanBePlacedInVec> AbiRead<Vec<R>> for AbiReader<'_>265where266	Self: AbiRead<R>,267{268	fn abi_read(&mut self) -> Result<Vec<R>> {269		let mut sub = self.subresult()?;270		let size = sub.read_usize()?;271		sub.subresult_offset = sub.offset;272		let mut out = Vec::with_capacity(size);273		for _ in 0..size {274			out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);275		}276		Ok(out)277	}278}279280macro_rules! impl_tuples {281	($($ident:ident)+) => {282		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}283		impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>284		where285			$(Self: AbiRead<$ident>),+286		{287			fn abi_read(&mut self) -> Result<($($ident,)+)> {288				let mut subresult = self.subresult()?;289				Ok((290					$(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+291				))292			}293		}294	};295}296297impl_tuples! {A}298impl_tuples! {A B}299impl_tuples! {A B C}300impl_tuples! {A B C D}301impl_tuples! {A B C D E}302impl_tuples! {A B C D E F}303impl_tuples! {A B C D E F G}304impl_tuples! {A B C D E F G H}305impl_tuples! {A B C D E F G H I}306impl_tuples! {A B C D E F G H I J}307308pub trait AbiWrite {309	fn abi_write(&self, writer: &mut AbiWriter);310	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {311		let mut writer = AbiWriter::new();312		self.abi_write(&mut writer);313		Ok(writer.into())314	}315}316317impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {318	// this particular AbiWrite implementation should be split to another trait,319	// which only implements [`to_result`]320	//321	// But due to lack of specialization feature in stable Rust, we can't have322	// blanket impl of this trait `for T where T: AbiWrite`, so here we abusing323	// default trait methods for it324	fn abi_write(&self, _writer: &mut AbiWriter) {325		debug_assert!(false, "shouldn't be called, see comment")326	}327	fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {328		match self {329			Ok(v) => Ok(WithPostDispatchInfo {330				post_info: v.post_info.clone(),331				data: {332					let mut out = AbiWriter::new();333					v.data.abi_write(&mut out);334					out335				},336			}),337			Err(e) => Err(e.clone()),338		}339	}340}341342macro_rules! impl_abi_writeable {343	($ty:ty, $method:ident) => {344		impl AbiWrite for $ty {345			fn abi_write(&self, writer: &mut AbiWriter) {346				writer.$method(&self)347			}348		}349	};350}351352impl_abi_writeable!(u8, uint8);353impl_abi_writeable!(u32, uint32);354impl_abi_writeable!(u128, uint128);355impl_abi_writeable!(U256, uint256);356impl_abi_writeable!(H160, address);357impl_abi_writeable!(bool, bool);358impl_abi_writeable!(&str, string);359impl AbiWrite for &string {360	fn abi_write(&self, writer: &mut AbiWriter) {361		writer.string(self)362	}363}364impl AbiWrite for &Vec<u8> {365	fn abi_write(&self, writer: &mut AbiWriter) {366		writer.bytes(self)367	}368}369370impl AbiWrite for () {371	fn abi_write(&self, _writer: &mut AbiWriter) {}372}373374#[macro_export]375macro_rules! abi_decode {376	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {377		$(378			let $name = $reader.$typ()?;379		)+380	}381}382#[macro_export]383macro_rules! abi_encode {384	($($typ:ident($value:expr)),* $(,)?) => {{385		#[allow(unused_mut)]386		let mut writer = ::evm_coder::abi::AbiWriter::new();387		$(388			writer.$typ($value);389		)*390		writer391	}};392	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{393		#[allow(unused_mut)]394		let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);395		$(396			writer.$typ($value);397		)*398		writer399	}}400}401402#[cfg(test)]403pub mod test {404	use crate::{405		abi::AbiRead,406		types::{string, uint256},407	};408409	use super::{AbiReader, AbiWriter};410	use hex_literal::hex;411412	#[test]413	fn dynamic_after_static() {414		let mut encoder = AbiWriter::new();415		encoder.bool(&true);416		encoder.string("test");417		let encoded = encoder.finish();418419		let mut encoder = AbiWriter::new();420		encoder.bool(&true);421		// Offset to subresult422		encoder.uint32(&(32 * 2));423		// Len of "test"424		encoder.uint32(&4);425		encoder.write_padright(&[b't', b'e', b's', b't']);426		let alternative_encoded = encoder.finish();427428		assert_eq!(encoded, alternative_encoded);429430		let mut decoder = AbiReader::new(&encoded);431		assert_eq!(decoder.bool().unwrap(), true);432		assert_eq!(decoder.string().unwrap(), "test");433	}434435	#[test]436	fn mint_sample() {437		let (call, mut decoder) = AbiReader::new_call(&hex!(438			"439				50bb4e7f440				000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374441				0000000000000000000000000000000000000000000000000000000000000001442				0000000000000000000000000000000000000000000000000000000000000060443				0000000000000000000000000000000000000000000000000000000000000008444				5465737420555249000000000000000000000000000000000000000000000000445			"446		))447		.unwrap();448		assert_eq!(call, 0x50bb4e7f);449		assert_eq!(450			format!("{:?}", decoder.address().unwrap()),451			"0xad2c0954693c2b5404b7e50967d3481bea432374"452		);453		assert_eq!(decoder.uint32().unwrap(), 1);454		assert_eq!(decoder.string().unwrap(), "Test URI");455	}456457	#[test]458	fn mint_bulk() {459		let (call, mut decoder) = AbiReader::new_call(&hex!(460			"461				36543006462				00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address463				0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]464				0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]465466				0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem467				00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem468				0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem469470				0000000000000000000000000000000000000000000000000000000000000001 // first token id?   					#60471				0000000000000000000000000000000000000000000000000000000000000040 // offset of string472				000000000000000000000000000000000000000000000000000000000000000a // size of string473				5465737420555249203000000000000000000000000000000000000000000000 // string474475				000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11?			#e0476				0000000000000000000000000000000000000000000000000000000000000040 // offset of string477				000000000000000000000000000000000000000000000000000000000000000a // size of string478				5465737420555249203100000000000000000000000000000000000000000000 // string479480				000000000000000000000000000000000000000000000000000000000000000c // third token id?  Why ==12?			#160481				0000000000000000000000000000000000000000000000000000000000000040 // offset of string482				000000000000000000000000000000000000000000000000000000000000000a // size of string483				5465737420555249203200000000000000000000000000000000000000000000 // string484			"485		))486		.unwrap();487		assert_eq!(call, 0x36543006);488		let _ = decoder.address().unwrap();489		let data =490			<AbiReader<'_> as AbiRead<Vec<(uint256, string)>>>::abi_read(&mut decoder).unwrap();491		assert_eq!(492			data,493			vec![494				(1.into(), "Test URI 0".to_string()),495				(11.into(), "Test URI 1".to_string()),496				(12.into(), "Test URI 2".to_string())497			]498		);499	}500}