Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Salka1988 committed Feb 12, 2025
1 parent 95aaa27 commit db5dd0a
Show file tree
Hide file tree
Showing 11 changed files with 438 additions and 722 deletions.
3 changes: 3 additions & 0 deletions e2e/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ fuel-core-chain-config = { workspace = true, features = [
"std",
"test-helpers",
] }
fuels-accounts = { workspace = true, features = ["test-helpers"] }

fuel-core-types = { workspace = true, features = [
"da-compression",
Expand All @@ -46,10 +47,12 @@ fuel-core-client = { workspace = true }




[build-dependencies]
anyhow = { workspace = true, features = ["std"] }
flate2 = { workspace = true, features = ["zlib"] }
fuels-accounts = { workspace = true, features = ["std"] }

reqwest = { workspace = true, features = ["blocking", "default-tls"] }
semver = { workspace = true }
tar = { workspace = true }
Expand Down
30 changes: 1 addition & 29 deletions e2e/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
use url::Url;

use fuel_core_client::client::types::CoinType;
use fuel_core_client::client::{types::Block, FuelClient};
use fuel_core_types::fuel_tx::Transaction;
use fuel_core_types::fuel_types::{Address, AssetId};
use fuels::types::coin::Coin;
use fuel_core_client::client::FuelClient;
use fuels::types::errors::Error;
use fuels::types::errors::Result;
#[derive(Clone)]
Expand All @@ -28,30 +24,6 @@ impl HttpClient {
Ok(())
}

pub async fn send_tx(&self, tx: &Transaction) -> Result<()> {
self.client
.submit_and_await_commit(tx)
.await
.map_err(|e| Error::Other(e.to_string()))?;

Ok(())
}

pub async fn get_coin(&self, address: Address, asset_id: AssetId) -> Result<Coin> {
let coin_type = self
.client
.coins_to_spend(&address, vec![(asset_id, 1, None)], None)
.await
.map_err(|e| Error::Other(e.to_string()))?[0][0];

let coin = match coin_type {
CoinType::Coin(c) => Ok(c),
_ => Err(Error::Other("Couldn't get coin".to_string())),
}?;

Ok(Coin::from(coin))
}

pub async fn health(&self) -> Result<bool> {
match self.client.health().await {
Ok(healthy) => Ok(healthy),
Expand Down
22 changes: 22 additions & 0 deletions e2e/src/e2e_helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use crate::{
fuel_node::{FuelNode, FuelNodeProcess},
kms::{Kms, KmsKey, KmsProcess},
};

pub async fn start_kms(logs: bool) -> anyhow::Result<KmsProcess> {
Kms::default().with_show_logs(logs).start().await
}
pub async fn create_and_fund_kms_keys(
kms: &KmsProcess,
fuel_node: &FuelNodeProcess,
) -> anyhow::Result<KmsKey> {
let amount = 5_000_000_000;
let key = kms.create_key().await?;
let address = key.kms_data.address.clone();
fuel_node.fund(address, amount).await?;

Ok(key)
}
pub async fn start_fuel_node(logs: bool) -> anyhow::Result<FuelNodeProcess> {
FuelNode::default().with_show_logs(logs).start().await
}
128 changes: 15 additions & 113 deletions e2e/src/fuel_node.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,13 @@
use crate::client::HttpClient;
use fuel_core_chain_config::{
ChainConfig, CoinConfig, ConsensusConfig, SnapshotWriter, StateConfig,
};
use anyhow::Context;
use fuel_core_types::{
fuel_crypto::SecretKey as FuelSecretKey,
fuel_tx::{AssetId, Finalizable, Input, Output, TransactionBuilder, TxPointer},
fuel_types::Address,
fuel_tx::AssetId,
};
use fuels::crypto::{PublicKey, SecretKey};
use fuels::accounts::Account;
use fuels::crypto::SecretKey;
use fuels::prelude::{Bech32Address, Provider, TxPolicies, WalletUnlocked};
use itertools::Itertools;
use rand::Rng;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::Context;
use url::Url;
use fuels::accounts::Account;
use fuels::accounts::aws_signer::AwsWallet;
use fuels::types::U256;

#[derive(Default, Debug)]
pub struct FuelNode {
Expand All @@ -30,52 +20,6 @@ pub struct FuelNodeProcess {
}

impl FuelNode {
fn create_state_config(
path: impl Into<PathBuf>,
consensus_key: &PublicKey,
num_wallets: usize,
) -> anyhow::Result<Vec<FuelSecretKey>> {
let chain_config = ChainConfig {
consensus: ConsensusConfig::PoA {
signing_key: Input::owner(consensus_key),
},
..ChainConfig::local_testnet()
};

let mut rng = &mut rand::thread_rng();
let keys = std::iter::repeat_with(|| FuelSecretKey::random(&mut rng))
.take(num_wallets)
.collect_vec();

let coins = keys
.iter()
.flat_map(|key| {
std::iter::repeat_with(|| CoinConfig {
owner: Input::owner(&key.public_key()),
amount: u64::MAX,
asset_id: AssetId::zeroed(),
tx_id: rng.gen(),
output_index: rng.gen(),
..Default::default()
})
.take(10)
.collect_vec()
})
.collect_vec();

let state_config = StateConfig {
coins,
..StateConfig::local_testnet()
};

let snapshot = SnapshotWriter::json(path);
snapshot
.write_state_config(state_config, &chain_config)
.map_err(|_| anyhow::anyhow!("Failed to write state config"))?;

Ok(keys)
}

pub async fn start(&self) -> anyhow::Result<FuelNodeProcess> {
let unused_port = portpicker::pick_unused_port()
.ok_or_else(|| anyhow::anyhow!("No free port to start fuel-core"))?;
Expand Down Expand Up @@ -120,45 +64,6 @@ impl FuelNodeProcess {
HttpClient::new(&self.url)
}

async fn send_transfer_tx(client: HttpClient, key: FuelSecretKey) -> anyhow::Result<()> {
let mut tx = TransactionBuilder::script(vec![], vec![]);

tx.script_gas_limit(1_000_000);

let secret_key = key;
let address = Input::owner(&secret_key.public_key());

let base_asset = AssetId::zeroed();
let coin = client.get_coin(address, base_asset).await?;

tx.add_unsigned_coin_input(
secret_key,
coin.utxo_id,
coin.amount,
coin.asset_id,
TxPointer::default(),
);

const AMOUNT: u64 = 1;
let to = Address::default();
tx.add_output(Output::Coin {
to,
amount: AMOUNT,
asset_id: base_asset,
});
tx.add_output(Output::Change {
to: address,
amount: 0,
asset_id: base_asset,
});

let tx = tx.finalize();

client.send_tx(&tx.into()).await?;

Ok(())
}

async fn wait_until_healthy(&self) {
loop {
if let Ok(true) = self.client().health().await {
Expand All @@ -171,30 +76,27 @@ impl FuelNodeProcess {
&self.url
}

pub async fn fund(
&self,
address: Bech32Address,
amount: u64
) -> anyhow::Result<()> {
pub async fn fund(&self, address: Bech32Address, amount: u64) -> anyhow::Result<()> {
let fuels_provider = Provider::connect(self.url()).await?;

// Create a wallet with the private key of the default account
let mut default_wallet = WalletUnlocked::new_from_private_key(
SecretKey::from_str(
"0xde97d8624a438121b86a1956544bd72ed68cd69f2c99555b08b1e8c51ffd511c",
)
?,
)?,
None,
);
default_wallet.set_provider(fuels_provider.clone());

// Transfer ETH funds to the AWS wallet from the default wallet
let asset_id =
AssetId::from_str("f8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07")
.expect("AssetId to be well formed");

default_wallet
.transfer(
&address,
amount, // Amount to transfer
AssetId::from_str("f8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07").expect("AssetId to be well formed"),
TxPolicies::default(),
)
.await.context("Failed to transfer funds")?;
.transfer(&address, amount, asset_id, TxPolicies::default())
.await
.context("Failed to transfer funds")?;

self.client().produce_blocks(1).await?;

Expand Down
38 changes: 8 additions & 30 deletions e2e/src/kms.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use anyhow::Context;
use aws_config::Region;
use aws_sdk_kms::{config::Credentials, Client as AWSClient};
use aws_sdk_kms::config::BehaviorVersion;
use testcontainers::{core::ContainerPort, runners::AsyncRunner};
use tokio::io::AsyncBufReadExt;
use fuels::accounts::aws_signer::KmsData;
use fuels::accounts::aws::{AwsClient, AwsConfig, KmsData};

#[derive(Default)]
pub struct Kms {
show_logs: bool,
Expand Down Expand Up @@ -49,28 +47,8 @@ impl Kms {
let port = container.get_host_port_ipv4(4566).await?;
let url = format!("http://localhost:{}", port);

// Configure AWS SDK
// let config = aws_config::from_env()
// .endpoint_url(url.clone())
// .region("us-east-1")
// .credentials_provider(Credentials::new("test", "test", None, None, "test"))
// .load()
// .await;

let config = aws_config::defaults(BehaviorVersion::latest())
.credentials_provider(Credentials::new(
"test",
"test",
None,
None,
"Static Credentials",
))
.endpoint_url(url.clone())
.region(Region::new("us-east-1")) // placeholder region for test
.load()
.await;

let client = AWSClient::new(&config);
let config = AwsConfig::for_testing(url.clone()).await;
let client = AwsClient::new(config);

Ok(KmsProcess {
_container: container,
Expand Down Expand Up @@ -121,14 +99,15 @@ fn spawn_log_printer(container: &testcontainers::ContainerAsync<KmsImage>) {

pub struct KmsProcess {
_container: testcontainers::ContainerAsync<KmsImage>,
client: AWSClient,
client: AwsClient,
url: String,
}

impl KmsProcess {
pub async fn create_key(&self) -> anyhow::Result<KmsKey> {
let response = self
.client
.client.
inner()
.create_key()
.key_usage(aws_sdk_kms::types::KeyUsageType::SignVerify)
.key_spec(aws_sdk_kms::types::KeySpec::EccSecgP256K1)
Expand All @@ -145,13 +124,12 @@ impl KmsProcess {

Ok(KmsKey {
id,
kms_data,// todo fix this
kms_data,
url: self.url.clone(),
})
}
}


#[derive(Debug, Clone)]
pub struct KmsKey {
pub id: String,
Expand Down
Loading

0 comments on commit db5dd0a

Please sign in to comment.