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

View File

@ -5,7 +5,7 @@ macro_rules! require {
if !$expr {
return Err($name.into());
}
}
};
}
/// 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 vaa::*;
pub mod chain;
pub mod vaa;
#[macro_use]
pub mod error;
/// 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,
/// while still maintaining the ability to render.

View File

@ -10,37 +10,18 @@
//! parse and verify incoming VAA's securely.
use nom::combinator::rest;
use nom::error::{
Error,
ErrorKind,
};
use nom::multi::{
count,
fill,
};
use nom::number::complete::{
u16,
u32,
u64,
u8,
};
use nom::error::{Error, ErrorKind};
use nom::multi::{count, fill};
use nom::number::complete::{u16, u32, u64, u8};
use nom::number::Endianness;
use nom::{
Err,
Finish,
IResult,
};
use nom::{Err, Finish, IResult};
use std::convert::TryFrom;
use crate::WormholeError::{
InvalidGovernanceAction,
InvalidGovernanceChain,
InvalidGovernanceModule,
};
use crate::{
require,
Chain,
WormholeError,
require, Chain,
WormholeError::{
self, InvalidGovernanceAction, InvalidGovernanceChain, InvalidGovernanceModule,
},
};
// Import Module Specific VAAs.
@ -49,7 +30,6 @@ pub mod core;
pub mod nft;
pub mod token;
/// Signatures are typical ECDSA signatures prefixed with a Guardian position. These have the
/// following byte layout:
/// ```markdown
@ -74,25 +54,25 @@ type ShortUTFString = String;
#[derive(Debug, Default, PartialEq)]
pub struct VAA {
// Header
pub version: u8,
pub version: u8,
pub guardian_set_index: u32,
pub signatures: Vec<Signature>,
pub signatures: Vec<Signature>,
// Body
pub timestamp: u32,
pub nonce: u32,
pub emitter_chain: Chain,
pub emitter_address: ForeignAddress,
pub sequence: u64,
pub timestamp: u32,
pub nonce: u32,
pub emitter_chain: Chain,
pub emitter_address: ForeignAddress,
pub sequence: u64,
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
/// various places in Wormhole codebases.
pub struct VAADigest {
pub digest: Vec<u8>,
pub hash: [u8; 32],
pub hash: [u8; 32],
}
impl VAA {
@ -109,22 +89,17 @@ impl VAA {
/// components for identifying unique VAA's, including the bridge, modules, and core guardian
/// software.
pub fn digest(&self) -> Option<VAADigest> {
use byteorder::{
BigEndian,
WriteBytesExt,
};
use byteorder::{BigEndian, WriteBytesExt};
use sha3::Digest;
use std::io::{
Cursor,
Write,
};
use std::io::{Cursor, Write};
// Hash Deterministic Pieces
let body = {
let mut v = Cursor::new(Vec::new());
v.write_u32::<BigEndian>(self.timestamp).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()?;
v.write_u64::<BigEndian>(self.sequence).ok()?;
v.write_u8(self.consistency_level).ok()?;
@ -141,10 +116,7 @@ impl VAA {
h.finalize().into()
};
Some(VAADigest {
digest: body,
hash,
})
Some(VAADigest { digest: body, hash })
}
}
@ -270,11 +242,7 @@ pub fn parse_governance_header<'i, 'a>(input: &'i [u8]) -> IResult<&'i [u8], Gov
#[cfg(test)]
mod testing {
use super::{
parse_governance_header,
Chain,
VAA,
};
use super::{parse_governance_header, Chain, VAA};
#[test]
fn test_valid_gov_header() {
@ -298,16 +266,13 @@ mod testing {
// Legacy VAA Signature Struct.
#[derive(Default, Clone)]
pub struct VAASignature {
pub signature: Vec<u8>,
pub signature: Vec<u8>,
pub guardian_index: u8,
}
// 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> {
use byteorder::{
BigEndian,
ReadBytesExt,
};
use byteorder::{BigEndian, ReadBytesExt};
use std::convert::TryFrom;
use std::io::Read;
@ -374,6 +339,5 @@ mod testing {
}
#[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
//! expected to require governance to be executed.
use nom::multi::{
count,
fill,
};
use nom::number::complete::{
u32,
u8,
};
use nom::multi::{count, fill};
use nom::number::complete::{u32, u8};
use nom::number::Endianness;
use nom::IResult;
use primitive_types::U256;
use crate::vaa::{
parse_fixed,
GovernanceAction,
};
use crate::vaa::{parse_fixed, GovernanceAction};
pub struct GovernanceContractUpgrade {
pub new_contract: [u8; 32],
@ -37,7 +28,7 @@ impl GovernanceAction for GovernanceContractUpgrade {
pub struct GovernanceGuardianSetChange {
pub new_guardian_set_index: u32,
pub new_guardian_set: Vec<[u8; 20]>,
pub new_guardian_set: Vec<[u8; 20]>,
}
impl GovernanceAction for GovernanceGuardianSetChange {
@ -78,7 +69,7 @@ impl GovernanceAction for GovernanceSetMessageFee {
pub struct GovernanceTransferFees {
pub amount: U256,
pub to: [u8; 32],
pub to: [u8; 32],
}
impl GovernanceAction for GovernanceTransferFees {

View File

@ -6,24 +6,13 @@
use nom::bytes::complete::take;
use nom::combinator::verify;
use nom::number::complete::u8;
use nom::{
Finish,
IResult,
};
use nom::{Finish, IResult};
use primitive_types::U256;
use std::str::from_utf8;
use crate::vaa::{
parse_chain,
parse_fixed,
GovernanceAction,
};
use crate::vaa::ShortUTFString;
use crate::{
Chain,
parse_fixed_utf8,
WormholeError,
};
use crate::vaa::{parse_chain, parse_fixed, GovernanceAction};
use crate::{parse_fixed_utf8, Chain, WormholeError};
/// 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
@ -100,7 +89,7 @@ fn parse_payload_transfer(input: &[u8]) -> IResult<&[u8], Transfer> {
#[derive(PartialEq, Debug)]
pub struct GovernanceRegisterChain {
pub emitter: Chain,
pub emitter: Chain,
pub endpoint_address: [u8; 32],
}

View File

@ -6,23 +6,11 @@
use nom::combinator::verify;
use nom::multi::fill;
use nom::number::complete::u8;
use nom::{
Finish,
IResult,
};
use nom::{Finish, IResult};
use primitive_types::U256;
use crate::vaa::{
GovernanceAction,
parse_chain,
parse_fixed,
ShortUTFString,
};
use crate::{
parse_fixed_utf8,
Chain,
WormholeError,
};
use crate::vaa::{parse_chain, parse_fixed, GovernanceAction, ShortUTFString};
use crate::{parse_fixed_utf8, Chain, WormholeError};
/// 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
@ -138,7 +126,7 @@ fn parse_payload_asset_meta(input: &[u8]) -> IResult<&[u8], AssetMeta> {
#[derive(PartialEq, Debug)]
pub struct GovernanceRegisterChain {
pub emitter: Chain,
pub emitter: Chain,
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.
imports_granularity = "Module"
# imports_granularity = "Module"
# 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.
imports_layout = "Vertical"
# imports_layout = "Vertical"
# Default rustfmt formatting of match arms with branches is awful.
match_arm_leading_pipes = "Preserve"
# Align Fields
enum_discrim_align_threshold = 80
struct_field_align_threshold = 80
# enum_discrim_align_threshold = 80
# struct_field_align_threshold = 80
# 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]| {
VAA::from_bytes(data);
});

View File

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

View File

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

View File

@ -1,20 +1,20 @@
use borsh::BorshDeserialize;
use solana_program::pubkey::Pubkey;
use solana_program::account_info::AccountInfo;
use solana_program::entrypoint::ProgramResult;
use solana_program::program::invoke_signed;
use solana_program::pubkey::Pubkey;
use std::str::FromStr;
// 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::BridgeData;
pub use bridge::MessageData;
pub use bridge::PostVAAData;
pub use bridge::PostedVAAData;
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::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.
pub fn read_vaa(vaa: &AccountInfo) -> Result<PostedVAAData, WormholeError> {
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,
@ -110,11 +110,7 @@ pub fn post_message(
// Pay Fee to the Wormhole
invoke_signed(
&solana_program::system_instruction::transfer(
&payer,
&fee_collector,
config.fee
),
&solana_program::system_instruction::transfer(&payer, &fee_collector, config.fee),
accounts,
&[],
)?;
@ -132,7 +128,7 @@ pub fn post_message(
)
.unwrap(),
accounts,
&seeds
&seeds,
)?;
Ok(())

View File

@ -1,21 +1,9 @@
use cosmwasm_std::{
to_binary,
Addr,
Binary,
CosmosMsg,
DepsMut,
Env,
QueryRequest,
StdResult,
WasmMsg,
WasmQuery,
to_binary, Addr, Binary, CosmosMsg, DepsMut, Env, QueryRequest, StdResult, WasmMsg, WasmQuery,
};
use serde::Serialize;
use wormhole::msg::{
ExecuteMsg,
QueryMsg,
};
use wormhole::msg::{ExecuteMsg, QueryMsg};
use wormhole::state::ParsedVAA;
/// Export Core Mainnet Contract Address
@ -36,12 +24,11 @@ pub fn id() -> Addr {
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 {
contract_addr: id().to_string(),
funds: vec![],
msg: to_binary(&ExecuteMsg::PostMessage {
funds: vec![],
msg: to_binary(&ExecuteMsg::PostMessage {
message: Binary::from(message.as_ref()),
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.
pub fn parse_vaa(
deps: DepsMut,
env: Env,
data: &Binary,
) -> StdResult<ParsedVAA> {
pub fn parse_vaa(deps: DepsMut, env: Env, data: &Binary) -> StdResult<ParsedVAA> {
let vaa: ParsedVAA = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: id().to_string(),
msg: to_binary(&QueryMsg::VerifyVAA {
msg: to_binary(&QueryMsg::VerifyVAA {
vaa: data.clone(),
block_time: env.block.time.seconds(),
})?,

View File

@ -8,14 +8,14 @@
//! Implementations:
//!
//! Runtime | Feature Flag | Version
//! ----------|-------------------------|----------------------------------------------------
//! Solana | --feature=solana | solana-sdk 1.7.1
//! Terra | --feature=terra | cosmos-sdk 0.16.0
//! ----------|-------------------------|----------------------------------------------------
//! Solana | --feature=solana | solana-sdk 1.7.1
//! Terra | --feature=terra | cosmos-sdk 0.16.0
//!
//! Docs specific to each blockchain's runtime can be found in submodules within the chains module
//! at the root of this package.
pub mod chains;
pub use wormhole_core::*;
pub use chains::*;
pub use wormhole_core::*;