sdk/rust: Fix formatting

Also disable unstable options in the rustfmt.toml
This commit is contained in:
Chirantan Ekbote 2022-09-30 16:28:48 +09:00 committed by Evan Gray
parent f7cc16aa91
commit cb20d47835
14 changed files with 73 additions and 167 deletions

View File

@ -2,20 +2,19 @@
//! library. Check submodules for chain runtime specific documentation. //! library. Check submodules for chain runtime specific documentation.
use std::convert::TryFrom; // Remove in 2021 use std::convert::TryFrom; // Remove in 2021
/// Chain contains a mapping of Wormhole supported chains to their u16 representation. These are /// Chain contains a mapping of Wormhole supported chains to their u16 representation. These are
/// universally defined among all Wormhole contracts. /// universally defined among all Wormhole contracts.
#[repr(u16)] #[repr(u16)]
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum Chain { pub enum Chain {
All = 0, All = 0,
Solana = 1, Solana = 1,
Ethereum = 2, Ethereum = 2,
Terra = 3, Terra = 3,
Binance = 4, Binance = 4,
Polygon = 5, Polygon = 5,
AVAX = 6, AVAX = 6,
Oasis = 7, Oasis = 7,
} }
impl TryFrom<u16> for Chain { impl TryFrom<u16> for Chain {

View File

@ -5,7 +5,7 @@ macro_rules! require {
if !$expr { if !$expr {
return Err($name.into()); return Err($name.into());
} }
} };
} }
/// This ErrorCode maps to the nom ParseError, we use an integer because the library is deprecating /// This ErrorCode maps to the nom ParseError, we use an integer because the library is deprecating

View File

@ -4,14 +4,12 @@ pub use chain::*;
pub use error::*; pub use error::*;
pub use vaa::*; pub use vaa::*;
pub mod chain; pub mod chain;
pub mod vaa; pub mod vaa;
#[macro_use] #[macro_use]
pub mod error; pub mod error;
/// Helper method that attempts to parse and truncate UTF-8 from a byte stream. This is useful when /// Helper method that attempts to parse and truncate UTF-8 from a byte stream. This is useful when
/// the wire data is expected to contain UTF-8 that is either already truncated, or needs to be, /// the wire data is expected to contain UTF-8 that is either already truncated, or needs to be,
/// while still maintaining the ability to render. /// while still maintaining the ability to render.

View File

@ -10,37 +10,18 @@
//! parse and verify incoming VAA's securely. //! parse and verify incoming VAA's securely.
use nom::combinator::rest; use nom::combinator::rest;
use nom::error::{ use nom::error::{Error, ErrorKind};
Error, use nom::multi::{count, fill};
ErrorKind, use nom::number::complete::{u16, u32, u64, u8};
};
use nom::multi::{
count,
fill,
};
use nom::number::complete::{
u16,
u32,
u64,
u8,
};
use nom::number::Endianness; use nom::number::Endianness;
use nom::{ use nom::{Err, Finish, IResult};
Err,
Finish,
IResult,
};
use std::convert::TryFrom; use std::convert::TryFrom;
use crate::WormholeError::{
InvalidGovernanceAction,
InvalidGovernanceChain,
InvalidGovernanceModule,
};
use crate::{ use crate::{
require, require, Chain,
Chain, WormholeError::{
WormholeError, self, InvalidGovernanceAction, InvalidGovernanceChain, InvalidGovernanceModule,
},
}; };
// Import Module Specific VAAs. // Import Module Specific VAAs.
@ -49,7 +30,6 @@ pub mod core;
pub mod nft; pub mod nft;
pub mod token; pub mod token;
/// Signatures are typical ECDSA signatures prefixed with a Guardian position. These have the /// Signatures are typical ECDSA signatures prefixed with a Guardian position. These have the
/// following byte layout: /// following byte layout:
/// ```markdown /// ```markdown
@ -74,25 +54,25 @@ type ShortUTFString = String;
#[derive(Debug, Default, PartialEq)] #[derive(Debug, Default, PartialEq)]
pub struct VAA { pub struct VAA {
// Header // Header
pub version: u8, pub version: u8,
pub guardian_set_index: u32, pub guardian_set_index: u32,
pub signatures: Vec<Signature>, pub signatures: Vec<Signature>,
// Body // Body
pub timestamp: u32, pub timestamp: u32,
pub nonce: u32, pub nonce: u32,
pub emitter_chain: Chain, pub emitter_chain: Chain,
pub emitter_address: ForeignAddress, pub emitter_address: ForeignAddress,
pub sequence: u64, pub sequence: u64,
pub consistency_level: u8, pub consistency_level: u8,
pub payload: Vec<u8>, pub payload: Vec<u8>,
} }
/// Contains the hash, secp256k1 payload, and serialized digest of the VAA. These are used in /// Contains the hash, secp256k1 payload, and serialized digest of the VAA. These are used in
/// various places in Wormhole codebases. /// various places in Wormhole codebases.
pub struct VAADigest { pub struct VAADigest {
pub digest: Vec<u8>, pub digest: Vec<u8>,
pub hash: [u8; 32], pub hash: [u8; 32],
} }
impl VAA { impl VAA {
@ -109,22 +89,17 @@ impl VAA {
/// components for identifying unique VAA's, including the bridge, modules, and core guardian /// components for identifying unique VAA's, including the bridge, modules, and core guardian
/// software. /// software.
pub fn digest(&self) -> Option<VAADigest> { pub fn digest(&self) -> Option<VAADigest> {
use byteorder::{ use byteorder::{BigEndian, WriteBytesExt};
BigEndian,
WriteBytesExt,
};
use sha3::Digest; use sha3::Digest;
use std::io::{ use std::io::{Cursor, Write};
Cursor,
Write,
};
// Hash Deterministic Pieces // Hash Deterministic Pieces
let body = { let body = {
let mut v = Cursor::new(Vec::new()); let mut v = Cursor::new(Vec::new());
v.write_u32::<BigEndian>(self.timestamp).ok()?; v.write_u32::<BigEndian>(self.timestamp).ok()?;
v.write_u32::<BigEndian>(self.nonce).ok()?; v.write_u32::<BigEndian>(self.nonce).ok()?;
v.write_u16::<BigEndian>(self.emitter_chain.clone() as u16).ok()?; v.write_u16::<BigEndian>(self.emitter_chain.clone() as u16)
.ok()?;
let _ = v.write(&self.emitter_address).ok()?; let _ = v.write(&self.emitter_address).ok()?;
v.write_u64::<BigEndian>(self.sequence).ok()?; v.write_u64::<BigEndian>(self.sequence).ok()?;
v.write_u8(self.consistency_level).ok()?; v.write_u8(self.consistency_level).ok()?;
@ -141,10 +116,7 @@ impl VAA {
h.finalize().into() h.finalize().into()
}; };
Some(VAADigest { Some(VAADigest { digest: body, hash })
digest: body,
hash,
})
} }
} }
@ -270,11 +242,7 @@ pub fn parse_governance_header<'i, 'a>(input: &'i [u8]) -> IResult<&'i [u8], Gov
#[cfg(test)] #[cfg(test)]
mod testing { mod testing {
use super::{ use super::{parse_governance_header, Chain, VAA};
parse_governance_header,
Chain,
VAA,
};
#[test] #[test]
fn test_valid_gov_header() { fn test_valid_gov_header() {
@ -298,16 +266,13 @@ mod testing {
// Legacy VAA Signature Struct. // Legacy VAA Signature Struct.
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub struct VAASignature { pub struct VAASignature {
pub signature: Vec<u8>, pub signature: Vec<u8>,
pub guardian_index: u8, pub guardian_index: u8,
} }
// Original VAA Parsing Code. Used to compare current code to old for parity. // Original VAA Parsing Code. Used to compare current code to old for parity.
pub fn legacy_deserialize(data: &[u8]) -> std::result::Result<VAA, std::io::Error> { pub fn legacy_deserialize(data: &[u8]) -> std::result::Result<VAA, std::io::Error> {
use byteorder::{ use byteorder::{BigEndian, ReadBytesExt};
BigEndian,
ReadBytesExt,
};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::io::Read; use std::io::Read;
@ -374,6 +339,5 @@ mod testing {
} }
#[test] #[test]
fn test_invalid_vaa() { fn test_invalid_vaa() {}
}
} }

View File

@ -5,22 +5,13 @@
//! The core bridge does not define any general VAA's, thus all the payloads in this file are //! The core bridge does not define any general VAA's, thus all the payloads in this file are
//! expected to require governance to be executed. //! expected to require governance to be executed.
use nom::multi::{ use nom::multi::{count, fill};
count, use nom::number::complete::{u32, u8};
fill,
};
use nom::number::complete::{
u32,
u8,
};
use nom::number::Endianness; use nom::number::Endianness;
use nom::IResult; use nom::IResult;
use primitive_types::U256; use primitive_types::U256;
use crate::vaa::{ use crate::vaa::{parse_fixed, GovernanceAction};
parse_fixed,
GovernanceAction,
};
pub struct GovernanceContractUpgrade { pub struct GovernanceContractUpgrade {
pub new_contract: [u8; 32], pub new_contract: [u8; 32],
@ -37,7 +28,7 @@ impl GovernanceAction for GovernanceContractUpgrade {
pub struct GovernanceGuardianSetChange { pub struct GovernanceGuardianSetChange {
pub new_guardian_set_index: u32, pub new_guardian_set_index: u32,
pub new_guardian_set: Vec<[u8; 20]>, pub new_guardian_set: Vec<[u8; 20]>,
} }
impl GovernanceAction for GovernanceGuardianSetChange { impl GovernanceAction for GovernanceGuardianSetChange {
@ -78,7 +69,7 @@ impl GovernanceAction for GovernanceSetMessageFee {
pub struct GovernanceTransferFees { pub struct GovernanceTransferFees {
pub amount: U256, pub amount: U256,
pub to: [u8; 32], pub to: [u8; 32],
} }
impl GovernanceAction for GovernanceTransferFees { impl GovernanceAction for GovernanceTransferFees {

View File

@ -6,24 +6,13 @@
use nom::bytes::complete::take; use nom::bytes::complete::take;
use nom::combinator::verify; use nom::combinator::verify;
use nom::number::complete::u8; use nom::number::complete::u8;
use nom::{ use nom::{Finish, IResult};
Finish,
IResult,
};
use primitive_types::U256; use primitive_types::U256;
use std::str::from_utf8; use std::str::from_utf8;
use crate::vaa::{
parse_chain,
parse_fixed,
GovernanceAction,
};
use crate::vaa::ShortUTFString; use crate::vaa::ShortUTFString;
use crate::{ use crate::vaa::{parse_chain, parse_fixed, GovernanceAction};
Chain, use crate::{parse_fixed_utf8, Chain, WormholeError};
parse_fixed_utf8,
WormholeError,
};
/// Transfer is a message containing specifics detailing a token lock up on a sending chain. Chains /// Transfer is a message containing specifics detailing a token lock up on a sending chain. Chains
/// that are attempting to initiate a transfer must lock up tokens in some manner, such as in a /// that are attempting to initiate a transfer must lock up tokens in some manner, such as in a
@ -100,7 +89,7 @@ fn parse_payload_transfer(input: &[u8]) -> IResult<&[u8], Transfer> {
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub struct GovernanceRegisterChain { pub struct GovernanceRegisterChain {
pub emitter: Chain, pub emitter: Chain,
pub endpoint_address: [u8; 32], pub endpoint_address: [u8; 32],
} }

View File

@ -6,23 +6,11 @@
use nom::combinator::verify; use nom::combinator::verify;
use nom::multi::fill; use nom::multi::fill;
use nom::number::complete::u8; use nom::number::complete::u8;
use nom::{ use nom::{Finish, IResult};
Finish,
IResult,
};
use primitive_types::U256; use primitive_types::U256;
use crate::vaa::{ use crate::vaa::{parse_chain, parse_fixed, GovernanceAction, ShortUTFString};
GovernanceAction, use crate::{parse_fixed_utf8, Chain, WormholeError};
parse_chain,
parse_fixed,
ShortUTFString,
};
use crate::{
parse_fixed_utf8,
Chain,
WormholeError,
};
/// Transfer is a message containing specifics detailing a token lock up on a sending chain. Chains /// Transfer is a message containing specifics detailing a token lock up on a sending chain. Chains
/// that are attempting to initiate a transfer must lock up tokens in some manner, such as in a /// that are attempting to initiate a transfer must lock up tokens in some manner, such as in a
@ -138,7 +126,7 @@ fn parse_payload_asset_meta(input: &[u8]) -> IResult<&[u8], AssetMeta> {
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub struct GovernanceRegisterChain { pub struct GovernanceRegisterChain {
pub emitter: Chain, pub emitter: Chain,
pub endpoint_address: [u8; 32], pub endpoint_address: [u8; 32],
} }

View File

@ -1,18 +1,20 @@
# Unstable options are commented out below. We should re-enable them once they are stabilized.
# Merge similar crates together to avoid multiple use statements. # Merge similar crates together to avoid multiple use statements.
imports_granularity = "Module" # imports_granularity = "Module"
# Consistency in formatting makes tool based searching/editing better. # Consistency in formatting makes tool based searching/editing better.
empty_item_single_line = false # empty_item_single_line = false
# Easier editing when arbitrary mixed use statements do not collapse. # Easier editing when arbitrary mixed use statements do not collapse.
imports_layout = "Vertical" # imports_layout = "Vertical"
# Default rustfmt formatting of match arms with branches is awful. # Default rustfmt formatting of match arms with branches is awful.
match_arm_leading_pipes = "Preserve" match_arm_leading_pipes = "Preserve"
# Align Fields # Align Fields
enum_discrim_align_threshold = 80 # enum_discrim_align_threshold = 80
struct_field_align_threshold = 80 # struct_field_align_threshold = 80
# Allow up to two blank lines for grouping. # Allow up to two blank lines for grouping.
blank_lines_upper_bound = 2 # blank_lines_upper_bound = 2

View File

@ -5,4 +5,3 @@ use wormhole_sdk::VAA;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
VAA::from_bytes(data); VAA::from_bytes(data);
}); });

View File

@ -5,4 +5,3 @@ use wormhole_sdk::vaa::VAA;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
VAA::from_bytes(data); VAA::from_bytes(data);
}); });

View File

@ -1,13 +1,11 @@
//! Exposes an API implementation depending on which feature flags have been toggled for the //! Exposes an API implementation depending on which feature flags have been toggled for the
//! library. Check submodules for chain runtime specific documentation. //! library. Check submodules for chain runtime specific documentation.
#[cfg(feature = "solana")] #[cfg(feature = "solana")]
pub mod solana; pub mod solana;
#[cfg(feature = "solana")] #[cfg(feature = "solana")]
pub use solana::*; pub use solana::*;
#[cfg(feature = "terra")] #[cfg(feature = "terra")]
pub mod terra; pub mod terra;
#[cfg(feature = "terra")] #[cfg(feature = "terra")]

View File

@ -1,20 +1,20 @@
use borsh::BorshDeserialize; use borsh::BorshDeserialize;
use solana_program::pubkey::Pubkey;
use solana_program::account_info::AccountInfo; use solana_program::account_info::AccountInfo;
use solana_program::entrypoint::ProgramResult; use solana_program::entrypoint::ProgramResult;
use solana_program::program::invoke_signed; use solana_program::program::invoke_signed;
use solana_program::pubkey::Pubkey;
use std::str::FromStr; use std::str::FromStr;
// Export Bridge API // Export Bridge API
pub use bridge::instructions;
pub use bridge::solitaire as bridge_entrypoint;
pub use bridge::types::ConsistencyLevel;
pub use bridge::BridgeConfig; pub use bridge::BridgeConfig;
pub use bridge::BridgeData; pub use bridge::BridgeData;
pub use bridge::MessageData; pub use bridge::MessageData;
pub use bridge::PostVAAData; pub use bridge::PostVAAData;
pub use bridge::PostedVAAData; pub use bridge::PostedVAAData;
pub use bridge::VerifySignaturesData; pub use bridge::VerifySignaturesData;
pub use bridge::instructions;
pub use bridge::solitaire as bridge_entrypoint;
pub use bridge::types::ConsistencyLevel;
use wormhole_core::WormholeError; use wormhole_core::WormholeError;
use wormhole_core::VAA; use wormhole_core::VAA;
@ -74,7 +74,7 @@ pub fn read_config(config: &AccountInfo) -> Result<BridgeConfig, WormholeError>
/// Deserialize helper for parsing from Borsh encoded VAA's from Solana accounts. /// Deserialize helper for parsing from Borsh encoded VAA's from Solana accounts.
pub fn read_vaa(vaa: &AccountInfo) -> Result<PostedVAAData, WormholeError> { pub fn read_vaa(vaa: &AccountInfo) -> Result<PostedVAAData, WormholeError> {
Ok(PostedVAAData::try_from_slice(&vaa.data.borrow()) Ok(PostedVAAData::try_from_slice(&vaa.data.borrow())
.map_err(|_| WormholeError::DeserializeFailed)?) .map_err(|_| WormholeError::DeserializeFailed)?)
} }
/// This helper method wraps the steps required to invoke Wormhole, it takes care of fee payment, /// This helper method wraps the steps required to invoke Wormhole, it takes care of fee payment,
@ -110,11 +110,7 @@ pub fn post_message(
// Pay Fee to the Wormhole // Pay Fee to the Wormhole
invoke_signed( invoke_signed(
&solana_program::system_instruction::transfer( &solana_program::system_instruction::transfer(&payer, &fee_collector, config.fee),
&payer,
&fee_collector,
config.fee
),
accounts, accounts,
&[], &[],
)?; )?;
@ -132,7 +128,7 @@ pub fn post_message(
) )
.unwrap(), .unwrap(),
accounts, accounts,
&seeds &seeds,
)?; )?;
Ok(()) Ok(())

View File

@ -1,21 +1,9 @@
use cosmwasm_std::{ use cosmwasm_std::{
to_binary, to_binary, Addr, Binary, CosmosMsg, DepsMut, Env, QueryRequest, StdResult, WasmMsg, WasmQuery,
Addr,
Binary,
CosmosMsg,
DepsMut,
Env,
QueryRequest,
StdResult,
WasmMsg,
WasmQuery,
}; };
use serde::Serialize; use serde::Serialize;
use wormhole::msg::{ use wormhole::msg::{ExecuteMsg, QueryMsg};
ExecuteMsg,
QueryMsg,
};
use wormhole::state::ParsedVAA; use wormhole::state::ParsedVAA;
/// Export Core Mainnet Contract Address /// Export Core Mainnet Contract Address
@ -36,12 +24,11 @@ pub fn id() -> Addr {
Addr::unchecked("terra18vd8fpwxzck93qlwghaj6arh4p7c5n896xzem5") Addr::unchecked("terra18vd8fpwxzck93qlwghaj6arh4p7c5n896xzem5")
} }
pub fn post_message(nonce: u32, message: impl AsRef<[u8]>) -> StdResult<CosmosMsg> pub fn post_message(nonce: u32, message: impl AsRef<[u8]>) -> StdResult<CosmosMsg> {
{
Ok(CosmosMsg::Wasm(WasmMsg::Execute { Ok(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: id().to_string(), contract_addr: id().to_string(),
funds: vec![], funds: vec![],
msg: to_binary(&ExecuteMsg::PostMessage { msg: to_binary(&ExecuteMsg::PostMessage {
message: Binary::from(message.as_ref()), message: Binary::from(message.as_ref()),
nonce, nonce,
})?, })?,
@ -49,14 +36,10 @@ pub fn post_message(nonce: u32, message: impl AsRef<[u8]>) -> StdResult<CosmosMs
} }
/// Parse a VAA using the Wormhole contract Query interface. /// Parse a VAA using the Wormhole contract Query interface.
pub fn parse_vaa( pub fn parse_vaa(deps: DepsMut, env: Env, data: &Binary) -> StdResult<ParsedVAA> {
deps: DepsMut,
env: Env,
data: &Binary,
) -> StdResult<ParsedVAA> {
let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: id().to_string(), contract_addr: id().to_string(),
msg: to_binary(&QueryMsg::VerifyVAA { msg: to_binary(&QueryMsg::VerifyVAA {
vaa: data.clone(), vaa: data.clone(),
block_time: env.block.time.seconds(), block_time: env.block.time.seconds(),
})?, })?,

View File

@ -17,5 +17,5 @@
pub mod chains; pub mod chains;
pub use wormhole_core::*;
pub use chains::*; pub use chains::*;
pub use wormhole_core::*;