Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Miscellaneous code improvements for Orchestrator #364

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions orchestrator/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 30 additions & 30 deletions orchestrator/cosmos_gravity/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ use tonic::transport::Channel;
pub async fn get_gravity_params(
client: &mut GravityQueryClient<Channel>,
) -> Result<Params, GravityError> {
let request = client.params(QueryParamsRequest {}).await?.into_inner();
Ok(request.params.unwrap())
let response = client.params(QueryParamsRequest {}).await?.into_inner();
Ok(response.params.unwrap())
}

/// get the valset for a given nonce (block) height
pub async fn get_valset(
client: &mut GravityQueryClient<Channel>,
nonce: u64,
) -> Result<Option<Valset>, GravityError> {
let request = client
let response = client
.valset_request(QueryValsetRequestRequest { nonce })
.await?;
let valset = request.into_inner().valset;
let valset = response.into_inner().valset;
let valset = valset.map(|v| v.into());
Ok(valset)
}
Expand All @@ -54,8 +54,8 @@ pub async fn get_valset(
pub async fn get_current_valset(
client: &mut GravityQueryClient<Channel>,
) -> Result<Valset, GravityError> {
let request = client.current_valset(QueryCurrentValsetRequest {}).await?;
let valset = request.into_inner().valset;
let response = client.current_valset(QueryCurrentValsetRequest {}).await?;
let valset = response.into_inner().valset;
if let Some(valset) = valset {
Ok(valset.into())
} else {
Expand All @@ -73,12 +73,12 @@ pub async fn get_oldest_unsigned_valsets(
address: Address,
prefix: String,
) -> Result<Vec<Valset>, GravityError> {
let request = client
let response = client
.last_pending_valset_request_by_addr(QueryLastPendingValsetRequestByAddrRequest {
address: address.to_bech32(prefix).unwrap(),
})
.await?;
let valsets = request.into_inner().valsets;
let valsets = response.into_inner().valsets;
// convert from proto valset type to rust valset type
let valsets = valsets.iter().map(|v| v.into()).collect();
Ok(valsets)
Expand All @@ -89,10 +89,10 @@ pub async fn get_oldest_unsigned_valsets(
pub async fn get_latest_valsets(
client: &mut GravityQueryClient<Channel>,
) -> Result<Vec<Valset>, GravityError> {
let request = client
let response = client
.last_valset_requests(QueryLastValsetRequestsRequest {})
.await?;
let valsets = request.into_inner().valsets;
let valsets = response.into_inner().valsets;
Ok(valsets.iter().map(|v| v.into()).collect())
}

Expand All @@ -101,10 +101,10 @@ pub async fn get_all_valset_confirms(
client: &mut GravityQueryClient<Channel>,
nonce: u64,
) -> Result<Vec<ValsetConfirmResponse>, GravityError> {
let request = client
let response = client
.valset_confirms_by_nonce(QueryValsetConfirmsByNonceRequest { nonce })
.await?;
let confirms = request.into_inner().confirms;
let confirms = response.into_inner().confirms;
let mut parsed_confirms = Vec::new();
for item in confirms {
let v: ValsetConfirmResponse = ValsetConfirmResponse::try_from(&item)?;
Expand All @@ -118,12 +118,12 @@ pub async fn get_oldest_unsigned_transaction_batch(
address: Address,
prefix: String,
) -> Result<Option<TransactionBatch>, GravityError> {
let request = client
let response = client
.last_pending_batch_request_by_addr(QueryLastPendingBatchRequestByAddrRequest {
address: address.to_bech32(prefix).unwrap(),
})
.await?;
let batch = request.into_inner().batch;
let batch = response.into_inner().batch;
match batch {
Some(batch) => Ok(Some(TransactionBatch::try_from(batch)?)),
None => Ok(None),
Expand All @@ -135,10 +135,10 @@ pub async fn get_oldest_unsigned_transaction_batch(
pub async fn get_latest_transaction_batches(
client: &mut GravityQueryClient<Channel>,
) -> Result<Vec<TransactionBatch>, GravityError> {
let request = client
let response = client
.outgoing_tx_batches(QueryOutgoingTxBatchesRequest {})
.await?;
let batches = request.into_inner().batches;
let batches = response.into_inner().batches;
let mut out = Vec::new();
for batch in batches {
out.push(TransactionBatch::try_from(batch)?)
Expand All @@ -152,13 +152,13 @@ pub async fn get_transaction_batch_signatures(
nonce: u64,
contract_address: EthAddress,
) -> Result<Vec<BatchConfirmResponse>, GravityError> {
let request = client
let response = client
.batch_confirms(QueryBatchConfirmsRequest {
nonce,
contract_address: contract_address.to_string(),
})
.await?;
let batch_confirms = request.into_inner().confirms;
let batch_confirms = response.into_inner().confirms;
let mut out = Vec::new();
for confirm in batch_confirms {
out.push(BatchConfirmResponse::try_from(confirm)?)
Expand All @@ -173,22 +173,22 @@ pub async fn get_last_event_nonce_for_validator(
address: Address,
prefix: String,
) -> Result<u64, GravityError> {
let request = client
let response = client
.last_event_nonce_by_addr(QueryLastEventNonceByAddrRequest {
address: address.to_bech32(prefix).unwrap(),
})
.await?;
Ok(request.into_inner().event_nonce)
Ok(response.into_inner().event_nonce)
}

/// Gets the 100 latest logic calls for a relayer to consider relaying
pub async fn get_latest_logic_calls(
client: &mut GravityQueryClient<Channel>,
) -> Result<Vec<LogicCall>, GravityError> {
let request = client
let response = client
.outgoing_logic_calls(QueryOutgoingLogicCallsRequest {})
.await?;
let calls = request.into_inner().calls;
let calls = response.into_inner().calls;
let mut out = Vec::new();
for call in calls {
out.push(LogicCall::try_from(call)?);
Expand All @@ -201,13 +201,13 @@ pub async fn get_logic_call_signatures(
invalidation_id: Vec<u8>,
invalidation_nonce: u64,
) -> Result<Vec<LogicCallConfirmResponse>, GravityError> {
let request = client
let response = client
.logic_confirms(QueryLogicConfirmsRequest {
invalidation_id,
invalidation_nonce,
})
.await?;
let call_confirms = request.into_inner().confirms;
let call_confirms = response.into_inner().confirms;
let mut out = Vec::new();
for confirm in call_confirms {
out.push(LogicCallConfirmResponse::try_from(confirm)?)
Expand All @@ -220,12 +220,12 @@ pub async fn get_oldest_unsigned_logic_call(
address: Address,
prefix: String,
) -> Result<Option<LogicCall>, GravityError> {
let request = client
let response = client
.last_pending_logic_call_by_addr(QueryLastPendingLogicCallByAddrRequest {
address: address.to_bech32(prefix).unwrap(),
})
.await?;
let call = request.into_inner().call;
let call = response.into_inner().call;
match call {
Some(call) => Ok(Some(LogicCall::try_from(call)?)),
None => Ok(None),
Expand All @@ -236,12 +236,12 @@ pub async fn get_attestations(
client: &mut GravityQueryClient<Channel>,
limit: Option<u64>,
) -> Result<Vec<Attestation>, GravityError> {
let request = client
let response = client
.get_attestations(QueryAttestationsRequest {
limit: limit.or(Some(1000u64)).unwrap(),
})
.await?;
let attestations = request.into_inner().attestations;
let attestations = response.into_inner().attestations;
Ok(attestations)
}

Expand All @@ -250,10 +250,10 @@ pub async fn get_pending_send_to_eth(
client: &mut GravityQueryClient<Channel>,
sender_address: Address,
) -> Result<QueryPendingSendToEthResponse, GravityError> {
let request = client
let response = client
.get_pending_send_to_eth(QueryPendingSendToEth {
sender_address: sender_address.to_string(),
})
.await?;
Ok(request.into_inner())
Ok(response.into_inner())
}
27 changes: 10 additions & 17 deletions orchestrator/cosmos_gravity/src/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ use gravity_proto::gravity::MsgValsetUpdatedClaim;
use gravity_proto::gravity::{MsgBatchSendToEthClaim, MsgSubmitBadSignatureEvidence};
use gravity_proto::gravity::{MsgCancelSendToEth, MsgConfirmBatch};
use gravity_utils::types::*;
use std::{collections::HashMap, time::Duration};
use std::collections::BTreeMap;
use std::time::Duration;

use crate::utils::BadSignatureEvidence;

Expand Down Expand Up @@ -262,8 +263,8 @@ pub async fn send_ethereum_claims(
// would require a truly horrendous (nearly 100 line) match statement to deal with all combinations. That match statement
// could be reduced by adding two traits to sort against but really this is the easiest option.
//
// We index the events by event nonce in an unordered hashmap and then play them back in order into a vec
let mut unordered_msgs = HashMap::new();
// We index the events by event nonce in a sorted hashmap, skipping the need to sort it later
let mut ordered_msgs = BTreeMap::new();
for deposit in deposits {
let claim = MsgSendToCosmosClaim {
event_nonce: deposit.event_nonce,
Expand All @@ -275,7 +276,7 @@ pub async fn send_ethereum_claims(
orchestrator: our_address.to_string(),
};
let msg = Msg::new("/gravity.v1.MsgSendToCosmosClaim", claim);
unordered_msgs.insert(deposit.event_nonce, msg);
ordered_msgs.insert(deposit.event_nonce, msg);
}
for withdraw in withdraws {
let claim = MsgBatchSendToEthClaim {
Expand All @@ -286,7 +287,7 @@ pub async fn send_ethereum_claims(
orchestrator: our_address.to_string(),
};
let msg = Msg::new("/gravity.v1.MsgBatchSendToEthClaim", claim);
unordered_msgs.insert(withdraw.event_nonce, msg);
ordered_msgs.insert(withdraw.event_nonce, msg);
}
for deploy in erc20_deploys {
let claim = MsgErc20DeployedClaim {
Expand All @@ -300,7 +301,7 @@ pub async fn send_ethereum_claims(
orchestrator: our_address.to_string(),
};
let msg = Msg::new("/gravity.v1.MsgERC20DeployedClaim", claim);
unordered_msgs.insert(deploy.event_nonce, msg);
ordered_msgs.insert(deploy.event_nonce, msg);
}
for call in logic_calls {
let claim = MsgLogicCallExecutedClaim {
Expand All @@ -311,7 +312,7 @@ pub async fn send_ethereum_claims(
orchestrator: our_address.to_string(),
};
let msg = Msg::new("/gravity.v1.MsgLogicCallExecutedClaim", claim);
unordered_msgs.insert(call.event_nonce, msg);
ordered_msgs.insert(call.event_nonce, msg);
}
for valset in valsets {
let claim = MsgValsetUpdatedClaim {
Expand All @@ -327,18 +328,10 @@ pub async fn send_ethereum_claims(
orchestrator: our_address.to_string(),
};
let msg = Msg::new("/gravity.v1.MsgValsetUpdatedClaim", claim);
unordered_msgs.insert(valset.event_nonce, msg);
ordered_msgs.insert(valset.event_nonce, msg);
}
let mut keys = Vec::new();
for (key, _) in unordered_msgs.iter() {
keys.push(*key);
}
keys.sort_unstable();

let mut msgs = Vec::new();
for i in keys {
msgs.push(unordered_msgs.remove_entry(&i).unwrap().1);
}
let msgs: Vec<Msg> = ordered_msgs.into_iter().map(|(_, v)| v).collect();

let fee = Fee {
amount: vec![fee],
Expand Down
20 changes: 8 additions & 12 deletions orchestrator/ethereum_gravity/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ pub fn downcast_uint256(input: Uint256) -> Option<u64> {
if input >= U64MAX.into() {
None
} else {
let mut val = input.to_bytes_be();
// pad to 8 bytes
while val.len() < 8 {
val.insert(0, 0);
}
let val = input.to_bytes_be();
let mut lower_bytes: [u8; 8] = [0; 8];
// get the start index after the trailing zeros
let start_index = 8 - val.len();

// get the 'lowest' 8 bytes from a 256 bit integer
lower_bytes.copy_from_slice(&val[0..val.len()]);
lower_bytes[start_index..].copy_from_slice(val.as_slice());
Some(u64::from_be_bytes(lower_bytes))
}
}
Expand All @@ -27,14 +26,11 @@ pub fn downcast_to_u128(input: Uint256) -> Option<u128> {
if input >= U128MAX.into() {
None
} else {
let mut val = input.to_bytes_be();
// pad to 8 bytes
while val.len() < 16 {
val.insert(0, 0);
}
let val = input.to_bytes_be();
let mut lower_bytes: [u8; 16] = [0; 16];
let start_index = 16 - val.len();
// get the 'lowest' 16 bytes from a 256 bit integer
lower_bytes.copy_from_slice(&val[0..val.len()]);
lower_bytes[start_index..].copy_from_slice(val.as_slice());
Some(u128::from_be_bytes(lower_bytes))
}
}
Expand Down
Loading