Skip to content

Commit

Permalink
417 Fix 4FC-05 commented out code (#486)
Browse files Browse the repository at this point in the history
* first iteration

* cleanup more todo's

* cleanup txsets todos

* interlay/interbtc-clients@622f36b

* fix #417 (comment)

* cleanup is_public_network() method
and the testchain runtime cfg-if

* implement the faucet_url todo

* is_transaction_already_submitted

* 2nd iteration to improve is_transaction_already_submitted()

* revert changes of the `fn is_transaction_already_submitted()`

* test prepush-hook

* update `fn is_transaction_already_submitted()`

* remove unnecessary files

* fix resources

* fix check_bump_sequence_number_and_submit() test case;

update the configs

* just allow it

* cleanup the comments

* clippy cleanup

* #277 and #486 (comment),
#486 (comment)

* rebase and #486 (comment)

* rename file for stellar_secretkey_testnet

* update function `get_mainnet_secret_key` to `get_secret_key` that accepts 2 params

* clippy fix

* Update Cargo.lock

update cargo lock
  • Loading branch information
b-yap authored Feb 26, 2024
1 parent ddb4f2b commit dc69aa1
Show file tree
Hide file tree
Showing 43 changed files with 573 additions and 379 deletions.
3 changes: 2 additions & 1 deletion Cargo.lock

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

4 changes: 2 additions & 2 deletions clients/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ testing-utils = [
"tempdir",
"rand",
"testchain",
"testchain-runtime",
"testchain-runtime/testing-utils",
"subxt-client",
"oracle"
"oracle/testing-utils"
]

[dependencies]
Expand Down
15 changes: 11 additions & 4 deletions clients/runtime/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1437,17 +1437,24 @@ impl ReplacePallet for SpacewalkParachain {

#[async_trait]
pub trait StellarRelayPallet {
async fn is_public_network(&self) -> Result<bool, Error>;
async fn is_public_network(&self) -> bool;
}

#[async_trait]
impl StellarRelayPallet for SpacewalkParachain {
async fn is_public_network(&self) -> Result<bool, Error> {
async fn is_public_network(&self) -> bool {
let address = metadata::constants().stellar_relay().is_public_network();
let result = self.api.constants().at(&address);
match result {
Ok(result) => Ok(result),
Err(_) => Err(Error::ConstantNotFound("is_public_network".to_string())),
Ok(result) => result,
Err(e) => {
// Sometimes the fetch fails with 'StorageItemNotFound' error.
// We assume public network by default
log::warn!(
"Failed to fetch public network status from parachain: {e:?}. Assuming public network."
);
true
},
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions clients/runtime/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,9 +330,9 @@ mod dispatch_error {
DispatchError::Arithmetic(arithmetic_error.into()),
RichDispatchError::Transactional(transactional_error) =>
DispatchError::Transactional(transactional_error.into()),
RichDispatchError::Exhausted |
sp_runtime::DispatchError::Corruption |
sp_runtime::DispatchError::Unavailable => todo!(),
RichDispatchError::Exhausted => DispatchError::Exhausted,
sp_runtime::DispatchError::Corruption => DispatchError::Corruption,
sp_runtime::DispatchError::Unavailable => DispatchError::Unavailable,
}
}
}
Expand Down
2 changes: 0 additions & 2 deletions clients/stellar-relay-lib/src/connection/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#![allow(dead_code)] //todo: remove after being tested and implemented

use crate::{connection::xdr_converter::Error as XDRError, helper::error_to_string};
use substrate_stellar_sdk::{types::ErrorCode, StellarSdkError};
use tokio::sync;
Expand Down
76 changes: 25 additions & 51 deletions clients/stellar-relay-lib/src/connection/xdr_converter.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#![allow(dead_code)] //todo: remove after being tested and implemented

use crate::sdk::types::{
AuthenticatedMessage, AuthenticatedMessageV0, HmacSha256Mac, MessageType, StellarMessage,
};
use std::fmt::Debug;
use substrate_stellar_sdk::XdrCodec;
use substrate_stellar_sdk::{parse_stellar_type, StellarSdkError, XdrCodec};

#[derive(Debug, Eq, PartialEq, err_derive::Error)]
pub enum Error {
Expand All @@ -14,10 +12,19 @@ pub enum Error {
#[error(display = "Message Version: Unsupported")]
UnsupportedMessageVersion,

#[error(display = "Sdk Error: {}", _0)]
SdkError(String),

#[error(display = "Decode Error: {}", _0)]
DecodeError(String),
}

impl From<StellarSdkError> for Error {
fn from(value: StellarSdkError) -> Self {
Error::SdkError(format!("{value:#?}"))
}
}

/// The 1st 4 bytes determines the byte length of the next stellar message.
/// Returns 0 if the array of u8 is less than 4 bytes, or exceeds the max of u32.
pub(crate) fn get_xdr_message_length(data: &[u8]) -> usize {
Expand All @@ -37,36 +44,6 @@ pub(crate) fn from_authenticated_message(message: &AuthenticatedMessage) -> Resu
message_to_bytes(message)
}

// todo: move to substrate-stellar-sdk
/// To easily convert any bytes to a Stellar type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use substrate_stellar_sdk::types::Auth;
/// use stellar_relay_lib::parse_stellar_type;
/// let auth_xdr = [0, 0, 0, 1];
/// let result = parse_stellar_type!(auth_xdr,Auth);
/// assert_eq!(result, Ok(Auth { flags: 1 }))
/// ```
#[macro_export]
macro_rules! parse_stellar_type {
($ref:ident, $struct_str:ident) => {{
use $crate::{
sdk::{types::$struct_str, XdrCodec},
xdr_converter::Error,
};

let ret: Result<$struct_str, Error> = $struct_str::from_xdr($ref).map_err(|e| {
log::error!("decode error: {:?}", e);
Error::DecodeError(stringify!($struct_str).to_string())
});
ret
}};
}

/// Parses the xdr message into `AuthenticatedMessageV0`.
/// When successful, returns a tuple of the message and the `MessageType`.
pub(crate) fn parse_authenticated_message(
Expand All @@ -92,7 +69,7 @@ pub(crate) fn parse_authenticated_message(
}

fn parse_stellar_message(xdr_message: &[u8]) -> Result<StellarMessage, Error> {
parse_stellar_type!(xdr_message, StellarMessage)
parse_stellar_type!(xdr_message, StellarMessage).map_err(|e| e.into())
}

fn parse_message_version(xdr_message: &[u8]) -> Result<u32, Error> {
Expand All @@ -104,11 +81,11 @@ fn parse_sequence(xdr_message: &[u8]) -> Result<u64, Error> {
}

fn parse_hmac(xdr_message: &[u8]) -> Result<HmacSha256Mac, Error> {
parse_stellar_type!(xdr_message, HmacSha256Mac)
parse_stellar_type!(xdr_message, HmacSha256Mac).map_err(|e| e.into())
}

fn parse_message_type(xdr_message: &[u8]) -> Result<MessageType, Error> {
parse_stellar_type!(xdr_message, MessageType)
parse_stellar_type!(xdr_message, MessageType).map_err(|e| e.into())
}

/// Returns XDR format of the message or
Expand All @@ -135,21 +112,19 @@ pub fn log_decode_error<T: Debug>(source: &str, error: T) -> Error {
Error::DecodeError(source.to_string())
}

// extra function.
fn is_xdr_complete_message(data: &[u8], message_len: usize) -> bool {
data.len() - 4 >= message_len
}

// extra function
fn get_message(data: &[u8], message_len: usize) -> (Vec<u8>, Vec<u8>) {
(data[4..(message_len + 4)].to_owned(), data[0..(message_len + 4)].to_owned())
}

#[cfg(test)]
mod test {
use crate::connection::xdr_converter::{
get_message, get_xdr_message_length, is_xdr_complete_message, parse_authenticated_message,
};
use crate::connection::xdr_converter::{get_xdr_message_length, parse_authenticated_message};

// extra function.
fn is_xdr_complete_message(data: &[u8], message_len: usize) -> bool {
data.len() - 4 >= message_len
}

// extra function
fn get_message(data: &[u8], message_len: usize) -> (Vec<u8>, Vec<u8>) {
(data[4..(message_len + 4)].to_owned(), data[0..(message_len + 4)].to_owned())
}

#[test]
fn get_xdr_message_length_success() {
Expand All @@ -165,8 +140,7 @@ mod test {
base64::STANDARD
).expect("should be able to decode to bytes");

//todo: once the authenticatedmessagev0 type is solved, continue the test
let _ = parse_authenticated_message(&msg);
assert!(parse_authenticated_message(&msg).is_ok());
}

#[test]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SDNQJEIRSA6YF5JNS6LQLCBF2XVWZ2NJV3YLC322RGIBJIJRIRGWKLEF
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SDNQJEIRSA6YF5JNS6LQLCBF2XVWZ2NJV3YLC322RGIBJIJRIRGWKLEF
Binary file added clients/vault/resources/test/tx_sets/92886_92900
Binary file not shown.
Binary file added clients/vault/resources/test/tx_sets/92901_92915
Binary file not shown.
Binary file not shown.
Binary file not shown.
6 changes: 1 addition & 5 deletions clients/vault/src/issue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ use wallet::{
types::FilterWith, LedgerTxEnvMap, Slot, SlotTask, SlotTaskStatus, TransactionResponse,
};

use crate::{
oracle::{types::Slot as OracleSlot, OracleAgent},
ArcRwLock, Error, Event,
};
use crate::{oracle::OracleAgent, ArcRwLock, Error, Event};

fn is_vault(p1: &PublicKey, p2_raw: [u8; 32]) -> bool {
return *p1.as_binary() == p2_raw
Expand Down Expand Up @@ -307,7 +304,6 @@ pub async fn execute_issue(
slot: Slot,
sender: tokio::sync::oneshot::Sender<SlotTaskStatus>,
) {
let slot = OracleSlot::from(slot);
// Get the proof of the given slot
let proof =
match oracle_agent.get_proof(slot).await {
Expand Down
14 changes: 6 additions & 8 deletions clients/vault/src/oracle/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ use stellar_relay_lib::{
};

use crate::oracle::{
collector::ScpMessageCollector,
errors::Error,
types::{Slot, StellarMessageSender},
AddTxSet, Proof,
collector::ScpMessageCollector, errors::Error, types::StellarMessageSender, AddTxSet, Proof,
};
use wallet::Slot;

pub struct OracleAgent {
collector: Arc<RwLock<ScpMessageCollector>>,
Expand Down Expand Up @@ -207,7 +205,7 @@ impl OracleAgent {
#[cfg(test)]
mod tests {
use crate::oracle::{
get_random_secret_key, get_test_secret_key, specific_stellar_relay_config,
get_random_secret_key, get_secret_key, specific_stellar_relay_config,
traits::ArchiveStorage, ScpArchiveStorage, TransactionsArchiveStorage,
};

Expand Down Expand Up @@ -259,7 +257,7 @@ mod tests {
let shutdown_sender = ShutdownSender::new();
let agent = start_oracle_agent(
specific_stellar_relay_config(true, 1),
&get_test_secret_key(true),
&get_secret_key(true, true),
shutdown_sender,
)
.await
Expand Down Expand Up @@ -299,7 +297,7 @@ mod tests {

let shutdown_sender = ShutdownSender::new();
let agent =
start_oracle_agent(modified_config, &get_test_secret_key(true), shutdown_sender)
start_oracle_agent(modified_config, &get_secret_key(true, true), shutdown_sender)
.await
.expect("Failed to start agent");

Expand All @@ -326,7 +324,7 @@ mod tests {
StellarOverlayConfig { stellar_history_archive_urls: vec![], ..base_config };

let shutdown = ShutdownSender::new();
let agent = start_oracle_agent(modified_config, &get_test_secret_key(true), shutdown)
let agent = start_oracle_agent(modified_config, &get_secret_key(true, true), shutdown)
.await
.expect("Failed to start agent");

Expand Down
Loading

0 comments on commit dc69aa1

Please sign in to comment.