reformat and fix client

Change-Id: Ie99d2b7cc2ed9890432c38661f1035a473cc5ac1
This commit is contained in:
Hendrik Hofstadt 2021-07-02 13:32:45 +02:00
parent 0ee2ef4348
commit cc08a9753c
12 changed files with 60 additions and 62 deletions

View File

@ -3,16 +3,23 @@
use std::{ use std::{
pin::Pin, pin::Pin,
task::{Context, Poll}, task::{
Context,
Poll,
},
}; };
use tokio::io::{AsyncRead, AsyncWrite}; use tokio::io::{
AsyncRead,
AsyncWrite,
};
use tonic::transport::server::Connected; use tonic::transport::server::Connected;
#[derive(Debug)] #[derive(Debug)]
pub struct UnixStream(pub tokio::net::UnixStream); pub struct UnixStream(pub tokio::net::UnixStream);
impl Connected for UnixStream {} impl Connected for UnixStream {
}
impl AsyncRead for UnixStream { impl AsyncRead for UnixStream {
fn poll_read( fn poll_read(
@ -37,10 +44,7 @@ impl AsyncWrite for UnixStream {
Pin::new(&mut self.0).poll_flush(cx) Pin::new(&mut self.0).poll_flush(cx)
} }
fn poll_shutdown( fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.0).poll_shutdown(cx) Pin::new(&mut self.0).poll_shutdown(cx)
} }
} }

View File

@ -76,7 +76,7 @@ type CommmandResult = Result<Option<Transaction>, Error>;
fn command_deploy_bridge( fn command_deploy_bridge(
config: &Config, config: &Config,
bridge: &Pubkey, bridge: &Pubkey,
_initial_guardian: Vec<[u8; 20]>, initial_guardians: Vec<[u8; 20]>,
guardian_expiration: u32, guardian_expiration: u32,
message_fee: u64, message_fee: u64,
) -> CommmandResult { ) -> CommmandResult {
@ -86,11 +86,12 @@ fn command_deploy_bridge(
.rpc_client .rpc_client
.get_minimum_balance_for_rent_exemption(size_of::<BridgeData>())?; .get_minimum_balance_for_rent_exemption(size_of::<BridgeData>())?;
let ix = bridge::client_instructions::initialize( let ix = bridge::instructions::initialize(
*bridge, *bridge,
config.owner.pubkey(), config.owner.pubkey(),
message_fee, message_fee,
guardian_expiration, guardian_expiration,
initial_guardians.as_slice(),
) )
.unwrap(); .unwrap();
println!("config account: {}, ", ix.accounts[0].pubkey.to_string()); println!("config account: {}, ", ix.accounts[0].pubkey.to_string());
@ -127,7 +128,7 @@ fn command_post_message(
&FeeCollector::key(None, bridge), &FeeCollector::key(None, bridge),
bridge_config.config.fee, bridge_config.config.fee,
); );
let ix = bridge::client_instructions::post_message( let (_, ix) = bridge::instructions::post_message(
*bridge, *bridge,
config.owner.pubkey(), config.owner.pubkey(),
config.fee_payer.pubkey(), config.fee_payer.pubkey(),

View File

@ -30,7 +30,7 @@ impl<'b, const State: AccountState> Seeded<&GuardianSetDerivationData>
fn seeds(data: &GuardianSetDerivationData) -> Vec<Vec<u8>> { fn seeds(data: &GuardianSetDerivationData) -> Vec<Vec<u8>> {
vec![ vec![
"GuardianSet".as_bytes().to_vec(), "GuardianSet".as_bytes().to_vec(),
data.index.to_be_bytes().to_vec() data.index.to_be_bytes().to_vec(),
] ]
} }
} }

View File

@ -6,6 +6,7 @@ use crate::{
GuardianSetDerivationData, GuardianSetDerivationData,
}, },
types::*, types::*,
Error::TooManyGuardians,
MAX_LEN_GUARDIAN_KEYS, MAX_LEN_GUARDIAN_KEYS,
}; };
use solitaire::{ use solitaire::{
@ -47,6 +48,10 @@ pub fn initialize(
) -> Result<()> { ) -> Result<()> {
let index = 0; let index = 0;
if data.initial_guardians.len() > MAX_LEN_GUARDIAN_KEYS {
return Err(TooManyGuardians.into());
}
// Allocate a default guardian set, with zeroed keys. // Allocate a default guardian set, with zeroed keys.
accs.guardian_set.index = index; accs.guardian_set.index = index;
accs.guardian_set.creation_time = 0; accs.guardian_set.creation_time = 0;

View File

@ -118,8 +118,10 @@ pub fn post_vaa(ctx: &ExecutionContext, accs: &mut PostVAA, vaa: PostVAAData) ->
payload: vaa.payload.clone(), payload: vaa.payload.clone(),
}; };
accs.message.verify_derivation(ctx.program_id, &msg_derivation)?; accs.message
accs.guardian_set.verify_derivation(ctx.program_id, &(&vaa).into())?; .verify_derivation(ctx.program_id, &msg_derivation)?;
accs.guardian_set
.verify_derivation(ctx.program_id, &(&vaa).into())?;
// Verify any required invariants before we process the instruction. // Verify any required invariants before we process the instruction.
check_active(&accs.guardian_set, &accs.clock)?; check_active(&accs.guardian_set, &accs.clock)?;

View File

@ -52,9 +52,7 @@ impl From<&VerifySignatures<'_>> for GuardianSetDerivationData {
impl From<[u8; 32]> for SignatureSetDerivationData { impl From<[u8; 32]> for SignatureSetDerivationData {
fn from(hash: [u8; 32]) -> Self { fn from(hash: [u8; 32]) -> Self {
SignatureSetDerivationData { SignatureSetDerivationData { hash }
hash
}
} }
} }
@ -196,16 +194,15 @@ pub fn verify_signatures(
// Confirm at this point that the derivation succeeds, we didn't have a signature set with the // Confirm at this point that the derivation succeeds, we didn't have a signature set with the
// correct hash until this point. // correct hash until this point.
accs.signature_set.verify_derivation( accs.signature_set
ctx.program_id, .verify_derivation(ctx.program_id, &msg_hash.into())?;
&msg_hash.into(),
)?;
if !accs.signature_set.is_initialized() { if !accs.signature_set.is_initialized() {
accs.signature_set.signatures = vec![[0u8; 65]; 19]; accs.signature_set.signatures = vec![[0u8; 65]; 19];
accs.signature_set.guardian_set_index = accs.guardian_set.index; accs.signature_set.guardian_set_index = accs.guardian_set.index;
accs.signature_set.hash = data.hash; accs.signature_set.hash = data.hash;
accs.signature_set.create(&msg_hash.into(), ctx, accs.payer.key, Exempt)?; accs.signature_set
.create(&msg_hash.into(), ctx, accs.payer.key, Exempt)?;
} else { } else {
// If the account already existed, check that the parameters match // If the account already existed, check that the parameters match
if accs.signature_set.guardian_set_index != accs.guardian_set.index { if accs.signature_set.guardian_set_index != accs.guardian_set.index {

View File

@ -32,7 +32,6 @@ use crate::{
GovernancePayloadUpgrade, GovernancePayloadUpgrade,
PostedMessage, PostedMessage,
}, },
BridgeConfig,
InitializeData, InitializeData,
PayloadMessage, PayloadMessage,
PostMessageData, PostMessageData,
@ -104,27 +103,30 @@ pub fn post_message(
&program_id, &program_id,
); );
Ok((message, Instruction { Ok((
program_id, message,
Instruction {
program_id,
accounts: vec![ accounts: vec![
AccountMeta::new(bridge, false), AccountMeta::new(bridge, false),
AccountMeta::new(message, false), AccountMeta::new(message, false),
AccountMeta::new(emitter, true), AccountMeta::new(emitter, true),
AccountMeta::new(sequence, false), AccountMeta::new(sequence, false),
AccountMeta::new(payer, true), AccountMeta::new(payer, true),
AccountMeta::new(fee_collector, false), AccountMeta::new(fee_collector, false),
AccountMeta::new_readonly(sysvar::clock::id(), false), AccountMeta::new_readonly(sysvar::clock::id(), false),
AccountMeta::new_readonly(sysvar::rent::id(), false), AccountMeta::new_readonly(sysvar::rent::id(), false),
AccountMeta::new_readonly(solana_program::system_program::id(), false), AccountMeta::new_readonly(solana_program::system_program::id(), false),
], ],
data: crate::instruction::Instruction::PostMessage(PostMessageData { data: crate::instruction::Instruction::PostMessage(PostMessageData {
nonce, nonce,
payload: payload.clone(), payload: payload.clone(),
}) })
.try_to_vec()?, .try_to_vec()?,
})) },
))
} }
pub fn verify_signatures( pub fn verify_signatures(

View File

@ -49,9 +49,6 @@ pub use vaa::{
SerializePayload, SerializePayload,
}; };
// BridgeConfig is the type of the main state the program maintains for itself.
use types::BridgeConfig;
const MAX_LEN_GUARDIAN_KEYS: usize = 19; const MAX_LEN_GUARDIAN_KEYS: usize = 19;
#[derive(Debug)] #[derive(Debug)]
@ -70,6 +67,7 @@ enum Error {
PostVAAConsensusFailed, PostVAAConsensusFailed,
PostVAAGuardianSetExpired, PostVAAGuardianSetExpired,
VAAAlreadyExecuted, VAAAlreadyExecuted,
TooManyGuardians,
} }
/// Translate from program specific errors to Solitaire framework errors. Log the error on the way /// Translate from program specific errors to Solitaire framework errors. Log the error on the way

View File

@ -47,12 +47,12 @@ use std::time::{
SystemTime, SystemTime,
}; };
use sha3::Digest;
use hex_literal::hex; use hex_literal::hex;
use secp256k1::{ use secp256k1::{
PublicKey, PublicKey,
SecretKey, SecretKey,
}; };
use sha3::Digest;
use bridge::{ use bridge::{
accounts::GuardianSetDerivationData, accounts::GuardianSetDerivationData,
@ -67,8 +67,8 @@ use bridge::{
}, },
Initialize, Initialize,
PostVAAData, PostVAAData,
Signature,
SerializePayload, SerializePayload,
Signature,
}; };
mod common; mod common;
@ -134,21 +134,10 @@ fn test_bridge_messages() {
let data = update_guardian_set(1, &public_keys); let data = update_guardian_set(1, &public_keys);
let message_key = common::post_message(client, program, payer, &emitter, nonce, data.clone()); let message_key = common::post_message(client, program, payer, &emitter, nonce, data.clone());
common::upgrade_guardian_set( common::upgrade_guardian_set(client, program, payer, message_key, emitter.pubkey(), 0, 1);
client,
program,
payer,
message_key,
emitter.pubkey(),
0,
1,
);
} }
fn update_guardian_set( fn update_guardian_set(index: u32, keys: &[[u8; 20]]) -> Vec<u8> {
index: u32,
keys: &[[u8; 20]],
) -> Vec<u8> {
let mut v = Cursor::new(Vec::new()); let mut v = Cursor::new(Vec::new());
v.write_u32::<BigEndian>(index).unwrap(); v.write_u32::<BigEndian>(index).unwrap();
v.write_u8(keys.len() as u8).unwrap(); v.write_u8(keys.len() as u8).unwrap();

View File

@ -19,7 +19,7 @@ macro_rules! trace_impl {
#[cfg(not(feature = "trace"))] #[cfg(not(feature = "trace"))]
#[macro_export] #[macro_export]
macro_rules! trace_impl { macro_rules! trace_impl {
( $($arg:tt)* ) => {} ( $($arg:tt)* ) => {};
} }
/// This is our main codegen macro. It takes as input a list of enum-like variants mapping field /// This is our main codegen macro. It takes as input a list of enum-like variants mapping field

View File

@ -24,9 +24,9 @@ use borsh::{
use solana_program::{ use solana_program::{
entrypoint::ProgramResult, entrypoint::ProgramResult,
instruction::Instruction, instruction::Instruction,
msg,
program::invoke_signed, program::invoke_signed,
pubkey::Pubkey, pubkey::Pubkey,
msg,
}; };
pub trait AccountSize { pub trait AccountSize {

View File

@ -1,3 +1,4 @@
use crate::trace;
use solana_program::{ use solana_program::{
account_info::{ account_info::{
next_account_info, next_account_info,
@ -6,7 +7,6 @@ use solana_program::{
pubkey::Pubkey, pubkey::Pubkey,
}; };
use std::slice::Iter; use std::slice::Iter;
use crate::trace;
/// The context is threaded through each check. Include anything within this structure that you /// The context is threaded through each check. Include anything within this structure that you
/// would like to have access to as each layer of dependency is peeled off. /// would like to have access to as each layer of dependency is peeled off.