sdk/rust: Remove `*_with_payload` methods

The RawMessage type provides a more flexible way to handle trailing
payloads so replace all usage of the `*_with_payload` functions to use
`RawMessage` instead.

There should be no functional change.
This commit is contained in:
Chirantan Ekbote 2023-01-13 18:26:15 +09:00 committed by Chirantan Ekbote
parent 3c6702b6f7
commit 421a030dca
4 changed files with 30 additions and 50 deletions

View File

@ -14,6 +14,7 @@ use cosmwasm_std::{
}; };
use cw2::set_contract_version; use cw2::set_contract_version;
use cw_storage_plus::Bound; use cw_storage_plus::Bound;
use serde_wormhole::RawMessage;
use tinyvec::{Array, TinyVec}; use tinyvec::{Array, TinyVec};
use wormhole::{ use wormhole::{
token::{Action, GovernancePacket, Message}, token::{Action, GovernancePacket, Message},
@ -183,7 +184,7 @@ fn handle_observation(
return Ok(None); return Ok(None);
} }
let (msg, _) = serde_wormhole::from_slice_with_payload(&o.payload) let (msg, _) = serde_wormhole::from_slice::<(Message, &RawMessage)>(&o.payload)
.context("failed to parse observation payload")?; .context("failed to parse observation payload")?;
let tx_data = match msg { let tx_data = match msg {
Message::Transfer { Message::Transfer {
@ -322,7 +323,7 @@ fn submit_vaas(
} }
fn handle_vaa(mut deps: DepsMut<WormholeQuery>, vaa: Binary) -> anyhow::Result<Event> { fn handle_vaa(mut deps: DepsMut<WormholeQuery>, vaa: Binary) -> anyhow::Result<Event> {
let (header, data) = serde_wormhole::from_slice_with_payload::<Header>(&vaa) let (header, data) = serde_wormhole::from_slice::<(Header, &RawMessage)>(&vaa)
.context("failed to parse VAA header")?; .context("failed to parse VAA header")?;
ensure!(header.version == 1, "unsupported VAA version"); ensure!(header.version == 1, "unsupported VAA version");
@ -342,7 +343,7 @@ fn handle_vaa(mut deps: DepsMut<WormholeQuery>, vaa: Binary) -> anyhow::Result<E
.map(|d| d.secp256k_hash.to_vec().into()) .map(|d| d.secp256k_hash.to_vec().into())
.context("failed to calculate digest for VAA body")?; .context("failed to calculate digest for VAA body")?;
let (body, payload) = serde_wormhole::from_slice_with_payload::<Body<()>>(data) let body = serde_wormhole::from_slice::<Body<&RawMessage>>(data)
.context("failed to parse VAA body")?; .context("failed to parse VAA body")?;
let digest_key = DIGESTS.key(( let digest_key = DIGESTS.key((
@ -365,11 +366,11 @@ fn handle_vaa(mut deps: DepsMut<WormholeQuery>, vaa: Binary) -> anyhow::Result<E
let evt = if body.emitter_chain == Chain::Solana let evt = if body.emitter_chain == Chain::Solana
&& body.emitter_address == wormhole::GOVERNANCE_EMITTER && body.emitter_address == wormhole::GOVERNANCE_EMITTER
{ {
let govpacket = let govpacket = serde_wormhole::from_slice(body.payload)
serde_wormhole::from_slice(payload).context("failed to parse governance packet")?; .context("failed to parse governance packet")?;
handle_governance_vaa(deps.branch(), body.with_payload(govpacket))? handle_governance_vaa(deps.branch(), body.with_payload(govpacket))?
} else { } else {
let (msg, _) = serde_wormhole::from_slice_with_payload(payload) let (msg, _) = serde_wormhole::from_slice::<(_, &RawMessage)>(body.payload)
.context("failed to parse tokenbridge message")?; .context("failed to parse tokenbridge message")?;
handle_tokenbridge_vaa(deps.branch(), body.with_payload(msg))? handle_tokenbridge_vaa(deps.branch(), body.with_payload(msg))?
}; };

View File

@ -68,7 +68,6 @@ pub enum Message {
/// ``` /// ```
/// # fn example() -> anyhow::Result<()> { /// # fn example() -> anyhow::Result<()> {
/// # use wormhole::{Address, Amount, Chain, vaa::Signature, GOVERNANCE_EMITTER}; /// # use wormhole::{Address, Amount, Chain, vaa::Signature, GOVERNANCE_EMITTER};
/// use wormhole::{token::Message, Vaa};
/// # /// #
/// # let data = [ /// # let data = [
/// # 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xb0, 0x72, 0x50, 0x5b, 0x5b, 0x99, 0x9c, 0x1d, /// # 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xb0, 0x72, 0x50, 0x5b, 0x5b, 0x99, 0x9c, 0x1d,
@ -94,10 +93,12 @@ pub enum Message {
/// # 0xfa, 0x5e, 0x70, 0xea, 0x36, 0xa2, 0x82, 0x37, 0x1d, 0x46, 0x81, 0x94, 0x10, 0x34, 0xb1, /// # 0xfa, 0x5e, 0x70, 0xea, 0x36, 0xa2, 0x82, 0x37, 0x1d, 0x46, 0x81, 0x94, 0x10, 0x34, 0xb1,
/// # 0xad, 0x0f, 0x4b, 0xc9, 0x17, 0x1e, 0x91, 0x25, 0x11, /// # 0xad, 0x0f, 0x4b, 0xc9, 0x17, 0x1e, 0x91, 0x25, 0x11,
/// # ]; /// # ];
/// use serde_wormhole::RawMessage;
/// use wormhole::{token::Message, Vaa};
/// ///
/// let (msg, payload) = serde_wormhole::from_slice_with_payload::<Vaa<Message>>(&data)?; /// let (msg, payload) = serde_wormhole::from_slice::<(Vaa<Message>, &RawMessage)>(&data)?;
/// assert!(matches!(msg.payload, Message::TransferWithPayload { .. })); /// assert!(matches!(msg.payload, Message::TransferWithPayload { .. }));
/// assert_eq!(&data[256..], payload); /// assert_eq!(&data[256..], payload.get());
/// # /// #
/// # Ok(()) /// # Ok(())
/// # } /// # }
@ -458,6 +459,8 @@ mod governance_packet_impl {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use serde_wormhole::RawMessage;
use crate::{vaa::Signature, Vaa, GOVERNANCE_EMITTER}; use crate::{vaa::Signature, Vaa, GOVERNANCE_EMITTER};
use super::*; use super::*;
@ -585,9 +588,9 @@ mod test {
}; };
assert_eq!(&payload[..133], &serde_wormhole::to_vec(&msg).unwrap()); assert_eq!(&payload[..133], &serde_wormhole::to_vec(&msg).unwrap());
let (actual, data) = serde_wormhole::from_slice_with_payload(&payload).unwrap(); let (actual, data) = serde_wormhole::from_slice::<(_, &RawMessage)>(&payload).unwrap();
assert_eq!(msg, actual); assert_eq!(msg, actual);
assert_eq!(&payload[133..], data); assert_eq!(&payload[133..], data.get());
let mut encoded = serde_json::to_vec(&msg).unwrap(); let mut encoded = serde_json::to_vec(&msg).unwrap();
encoded.extend_from_slice(&payload[133..]); encoded.extend_from_slice(&payload[133..]);

View File

@ -277,6 +277,8 @@ impl<P: Serialize> Body<P> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use serde_wormhole::RawMessage;
use super::*; use super::*;
#[test] #[test]
@ -318,14 +320,11 @@ mod test {
]), ]),
sequence: 0, sequence: 0,
consistency_level: 1, consistency_level: 1,
payload: (), payload: RawMessage::new(&buf[123..]),
}; };
let (actual, payload) = serde_wormhole::from_slice_with_payload(&buf).unwrap(); assert_eq!(vaa, serde_wormhole::from_slice(&buf).unwrap());
assert_eq!(vaa, actual); assert_eq!(&buf[..], &serde_wormhole::to_vec(&vaa).unwrap());
assert_eq!(bstr::B("From: evm0\\nMsg: Hello World!"), payload);
assert_eq!(&buf[..123], &serde_wormhole::to_vec(&vaa).unwrap());
} }
#[test] #[test]
@ -351,9 +350,8 @@ mod test {
assert_eq!(d1, d2); assert_eq!(d1, d2);
let (partial, payload) = let partial = serde_wormhole::from_slice::<Body<&RawMessage>>(&data).unwrap();
serde_wormhole::from_slice_with_payload::<Body<()>>(&data).unwrap(); let d3 = partial.digest().unwrap();
let d3 = partial.digest_with_payload(payload).unwrap();
assert_eq!(d1, d3); assert_eq!(d1, d3);
} }

View File

@ -143,19 +143,6 @@ pub fn from_reader<R: Read, T: DeserializeOwned>(mut r: R) -> Result<T, Error> {
from_slice(&buf) from_slice(&buf)
} }
/// Like `from_reader` but also returns any trailing data in the input buffer after
/// deserialization.
pub fn from_reader_with_payload<R: Read, T: DeserializeOwned>(
mut r: R,
) -> Result<(T, Vec<u8>), Error> {
// We can do something smarter here by making the deserializer generic over the reader (see
// serde_json::Deserializer) but for now this is probably good enough.
let mut buf = Vec::with_capacity(128);
r.read_to_end(&mut buf)?;
from_slice_with_payload(&buf).map(|(v, p)| (v, p.to_vec()))
}
/// Deserialize an instance of type `T` from a byte slice. /// Deserialize an instance of type `T` from a byte slice.
pub fn from_slice<'a, T: Deserialize<'a>>(buf: &'a [u8]) -> Result<T, Error> { pub fn from_slice<'a, T: Deserialize<'a>>(buf: &'a [u8]) -> Result<T, Error> {
let mut deserializer = de::Deserializer::new(buf); let mut deserializer = de::Deserializer::new(buf);
@ -169,15 +156,6 @@ pub fn from_slice<'a, T: Deserialize<'a>>(buf: &'a [u8]) -> Result<T, Error> {
} }
} }
/// Like `from_slice` but also returns any trailing data in the input buffer after deserialization.
pub fn from_slice_with_payload<'a, T: Deserialize<'a>>(
buf: &'a [u8],
) -> Result<(T, &'a [u8]), Error> {
let mut deserializer = de::Deserializer::new(buf);
T::deserialize(&mut deserializer).map(|v| (v, deserializer.end()))
}
/// Serialize `T` into a byte vector. /// Serialize `T` into a byte vector.
pub fn to_vec<T: ?Sized + Serialize>(val: &T) -> Result<Vec<u8>, Error> { pub fn to_vec<T: ?Sized + Serialize>(val: &T) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(128); let mut buf = Vec::with_capacity(128);
@ -286,7 +264,7 @@ mod tests {
} }
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct Vaa<'s> { struct Vaa<'s, P> {
header: Header, header: Header,
#[serde(borrow)] #[serde(borrow)]
signatures: Cow<'s, [Signature]>, signatures: Cow<'s, [Signature]>,
@ -297,7 +275,7 @@ mod tests {
sequence: u64, sequence: u64,
consistency_level: u8, consistency_level: u8,
map: BTreeMap<u32, u32>, map: BTreeMap<u32, u32>,
payload: GovernancePacket, payload: P,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@ -348,10 +326,11 @@ mod tests {
} }
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct GovernancePacket { struct GovernancePacket<P> {
module: [u8; 32], module: [u8; 32],
action: Action, action: Action,
chain: Chain, chain: Chain,
payload: P,
} }
#[test] #[test]
@ -404,21 +383,20 @@ mod tests {
], ],
action: Action::ContractUpgrade, action: Action::ContractUpgrade,
chain: Chain::Solana, chain: Chain::Solana,
payload: RawMessage::new(&[0x3d, 0xab, 0x45, 0xaf, 0x7a, 0x6e, 0x9f, 0x7b]),
}, },
}; };
let payload = &[0x3d, 0xab, 0x45, 0xaf, 0x7a, 0x6e, 0x9f, 0x7b];
let mut buf = to_vec(&vaa).unwrap(); let buf = to_vec(&vaa).unwrap();
buf.extend_from_slice(payload);
let (actual, governance_payload) = from_slice_with_payload(&buf).unwrap(); let actual = from_slice(&buf).unwrap();
assert_eq!(vaa, actual); assert_eq!(vaa, actual);
match actual.payload.action { match actual.payload.action {
Action::ContractUpgrade => { Action::ContractUpgrade => {
let expected = 0x3dab_45af_7a6e_9f7b; let expected = 0x3dab_45af_7a6e_9f7b;
let msg: ContractUpgrade = from_slice(governance_payload).unwrap(); let msg: ContractUpgrade = from_slice(actual.payload.payload).unwrap();
assert_eq!(expected, msg.new_contract); assert_eq!(expected, msg.new_contract);
} }
_ => panic!("Unexpected action: {:?}", actual.payload.action), _ => panic!("Unexpected action: {:?}", actual.payload.action),