git.delta.rocks / unique-network / refs/commits / 73e89cc4a2f1

difftreelog

source

crates/evm-coder/src/abi.rs7.1 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 primitive_types::{H160, U256};1213use crate::types::string;1415const ABI_ALIGNMENT: usize = 32;1617pub type Result<T> = core::result::Result<T, &'static str>;1819#[derive(Clone)]20pub struct AbiReader<'i> {21	buf: &'i [u8],22	offset: usize,23}24impl<'i> AbiReader<'i> {25	pub fn new(buf: &'i [u8]) -> Self {26		Self { buf, offset: 0 }27	}28	pub fn new_call(buf: &'i [u8]) -> Result<(u32, Self)> {29		if buf.len() < 4 {30			return Err("missing method id");31		}32		let mut method_id = [0; 4];33		method_id.copy_from_slice(&buf[0..4]);3435		Ok((u32::from_be_bytes(method_id), Self { buf, offset: 4 }))36	}3738	fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {39		if self.buf.len() - self.offset < 32 {40			return Err("missing padding");41		}42		let mut block = [0; S];43		// Verify padding is empty44		if !self.buf[self.offset..self.offset + ABI_ALIGNMENT - S]45			.iter()46			.all(|&v| v == 0)47		{48			return Err("non zero padding (wrong types?)");49		}50		block.copy_from_slice(51			&self.buf[self.offset + ABI_ALIGNMENT - S..self.offset + ABI_ALIGNMENT],52		);53		self.offset += ABI_ALIGNMENT;54		Ok(block)55	}5657	pub fn address(&mut self) -> Result<H160> {58		Ok(H160(self.read_padleft()?))59	}6061	pub fn bool(&mut self) -> Result<bool> {62		let data: [u8; 1] = self.read_padleft()?;63		match data[0] {64			0 => Ok(false),65			1 => Ok(true),66			_ => Err("wrong bool value"),67		}68	}6970	pub fn bytes4(&mut self) -> Result<[u8; 4]> {71		self.read_padleft()72	}7374	pub fn bytes(&mut self) -> Result<Vec<u8>> {75		let mut subresult = self.subresult()?;76		let length = subresult.read_usize()?;77		if subresult.buf.len() <= subresult.offset + length {78			return Err("bytes out of bounds");79		}80		Ok(subresult.buf[subresult.offset..subresult.offset + length].into())81	}8283	pub fn uint32(&mut self) -> Result<u32> {84		Ok(u32::from_be_bytes(self.read_padleft()?))85	}8687	pub fn uint128(&mut self) -> Result<u128> {88		Ok(u128::from_be_bytes(self.read_padleft()?))89	}9091	pub fn uint256(&mut self) -> Result<U256> {92		let buf: [u8; 32] = self.read_padleft()?;93		Ok(U256::from_big_endian(&buf))94	}9596	pub fn uint64(&mut self) -> Result<u64> {97		Ok(u64::from_be_bytes(self.read_padleft()?))98	}99100	pub fn read_usize(&mut self) -> Result<usize> {101		Ok(usize::from_be_bytes(self.read_padleft()?))102	}103104	fn subresult(&mut self) -> Result<AbiReader<'i>> {105		let offset = self.read_usize()?;106		Ok(AbiReader {107			buf: &self.buf,108			offset: offset + self.offset,109		})110	}111112	pub fn is_finished(&self) -> bool {113		self.buf.len() == self.offset114	}115}116117#[derive(Default)]118pub struct AbiWriter {119	static_part: Vec<u8>,120	dynamic_part: Vec<(usize, AbiWriter)>,121}122impl AbiWriter {123	pub fn new() -> Self {124		Self::default()125	}126	pub fn new_call(method_id: u32) -> Self {127		let mut val = Self::new();128		val.static_part.extend(&method_id.to_be_bytes());129		val130	}131132	fn write_padleft(&mut self, block: &[u8]) {133		assert!(block.len() <= ABI_ALIGNMENT);134		self.static_part135			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);136		self.static_part.extend(block);137	}138139	fn write_padright(&mut self, bytes: &[u8]) {140		assert!(bytes.len() <= ABI_ALIGNMENT);141		self.static_part.extend(bytes);142		self.static_part143			.extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);144	}145146	pub fn address(&mut self, address: &H160) {147		self.write_padleft(&address.0)148	}149150	pub fn bool(&mut self, value: &bool) {151		self.write_padleft(&[if *value { 1 } else { 0 }])152	}153154	pub fn uint8(&mut self, value: &u8) {155		self.write_padleft(&[*value])156	}157158	pub fn uint32(&mut self, value: &u32) {159		self.write_padleft(&u32::to_be_bytes(*value))160	}161162	pub fn uint128(&mut self, value: &u128) {163		self.write_padleft(&u128::to_be_bytes(*value))164	}165166	/// This method writes u128, and exists only for convenience, because there is167	/// no u256 support in rust168	pub fn uint256(&mut self, value: &U256) {169		let mut out = [0; 32];170		value.to_big_endian(&mut out);171		self.write_padleft(&out)172	}173174	pub fn write_usize(&mut self, value: &usize) {175		self.write_padleft(&usize::to_be_bytes(*value))176	}177178	pub fn write_subresult(&mut self, result: Self) {179		self.dynamic_part.push((self.static_part.len(), result));180		// Empty block, to be filled later181		self.write_padleft(&[]);182	}183184	pub fn memory(&mut self, value: &[u8]) {185		let mut sub = Self::new();186		sub.write_usize(&value.len());187		for chunk in value.chunks(ABI_ALIGNMENT) {188			sub.write_padright(chunk);189		}190		self.write_subresult(sub);191	}192193	pub fn string(&mut self, value: &str) {194		self.memory(value.as_bytes())195	}196197	pub fn finish(mut self) -> Vec<u8> {198		for (static_offset, part) in self.dynamic_part {199			let part_offset = self.static_part.len();200201			let encoded_dynamic_offset = usize::to_be_bytes(part_offset - static_offset);202			self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()203				..static_offset + ABI_ALIGNMENT]204				.copy_from_slice(&encoded_dynamic_offset);205			self.static_part.extend(part.finish())206		}207		self.static_part208	}209}210211pub trait AbiRead<T> {212	fn abi_read(&mut self) -> Result<T>;213}214215macro_rules! impl_abi_readable {216	($ty:ty, $method:ident) => {217		impl AbiRead<$ty> for AbiReader<'_> {218			fn abi_read(&mut self) -> Result<$ty> {219				self.$method()220			}221		}222	};223}224225impl_abi_readable!(u32, uint32);226impl_abi_readable!(u128, uint128);227impl_abi_readable!(U256, uint256);228impl_abi_readable!(H160, address);229impl_abi_readable!(Vec<u8>, bytes);230impl_abi_readable!(bool, bool);231232pub trait AbiWrite {233	fn abi_write(&self, writer: &mut AbiWriter);234}235236macro_rules! impl_abi_writeable {237	($ty:ty, $method:ident) => {238		impl AbiWrite for $ty {239			fn abi_write(&self, writer: &mut AbiWriter) {240				writer.$method(&self)241			}242		}243	};244}245246impl_abi_writeable!(u8, uint8);247impl_abi_writeable!(u32, uint32);248impl_abi_writeable!(u128, uint128);249impl_abi_writeable!(U256, uint256);250impl_abi_writeable!(H160, address);251impl_abi_writeable!(bool, bool);252impl_abi_writeable!(&str, string);253impl AbiWrite for &string {254	fn abi_write(&self, writer: &mut AbiWriter) {255		writer.string(&self)256	}257}258259impl AbiWrite for () {260	fn abi_write(&self, _writer: &mut AbiWriter) {}261}262263/// Error, which can be constructed from any ToString type264/// Encoded to Abi as Error(string)265#[derive(Debug)]266pub struct StringError(String);267268impl<E> From<E> for StringError269where270	E: ToString,271{272	fn from(e: E) -> Self {273		Self(e.to_string())274	}275}276277impl From<StringError> for AbiWriter {278	fn from(v: StringError) -> Self {279		let mut out = AbiWriter::new_call(crate::fn_selector!(Error(string)));280		out.string(&v.0);281		out282	}283}284285#[macro_export]286macro_rules! abi_decode {287	($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {288		$(289			let $name = $reader.$typ()?;290		)+291	}292}293#[macro_export]294macro_rules! abi_encode {295	($($typ:ident($value:expr)),* $(,)?) => {{296		#[allow(unused_mut)]297		let mut writer = ::evm_coder::abi::AbiWriter::new();298		$(299			writer.$typ($value);300		)*301		writer302	}};303	(call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{304		#[allow(unused_mut)]305		let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);306		$(307			writer.$typ($value);308		)*309		writer310	}}311}