Skip to content

Commit

Permalink
Merge branch '2.0' into is_network_healthy
Browse files Browse the repository at this point in the history
  • Loading branch information
thibault-martinez authored Mar 22, 2024
2 parents 89046b7 + 3091393 commit 2259f6e
Show file tree
Hide file tree
Showing 20 changed files with 375 additions and 202 deletions.
4 changes: 2 additions & 2 deletions .github/actions/ledger-nano/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ runs:
uses: actions/checkout@v3
with:
repository: iotaledger/ledger-iota-app
ref: develop
ref: feat/nova
path: ledger-iota-app

- name: Update submodules
Expand All @@ -17,5 +17,5 @@ runs:

- name: Run the simulator
shell: bash
run: ./build.sh -s -v shimmer -b
run: ./build.sh -s -b
working-directory: ledger-iota-app
5 changes: 1 addition & 4 deletions .github/workflows/private-tangle-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,7 @@ jobs:
uses: "./.github/actions/ledger-nano"

- name: Run tests
run: |
cargo nextest run test_get_info --all-features --run-ignored ignored-only --profile ci --cargo-profile ci -p iota-sdk -p iota-sdk-bindings-core --no-capture
# TODO: change in the future to run all tests and not only test_get_info
# cargo ci-tangle-test
run: cargo ci-tangle-test

- name: Tear down private tangle
if: always()
Expand Down
18 changes: 7 additions & 11 deletions bindings/core/tests/combined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,13 @@ async fn client_from_wallet() -> Result<(), Error> {
.build()
.await?;

// TODO reenable
// // Send ClientMethod via the client from the wallet
// let response = wallet
// .client()
// .call_method(ClientMethod::GetHealth)
// .await;

// match response {
// Response::Bool(_) => {}
// _ => panic!("unexpected response {response:?}"),
// }
// Send ClientMethod via the client from the wallet
let response = wallet.client().call_method(ClientMethod::GetProtocolParameters).await;

match response {
Response::ProtocolParameters(_) => {}
_ => panic!("unexpected response {response:?}"),
}

std::fs::remove_dir_all(storage_path).ok();
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ std = [
"iota_stronghold?/std",
"iota-crypto/std",
"once_cell?/std",
"dep:instant"
]
storage = ["iota-crypto/chacha", "dep:time", "dep:anymap", "dep:once_cell"]
stronghold = [
Expand All @@ -199,7 +200,6 @@ client = [
"iota-crypto/slip10",
"dep:async-trait",
"dep:futures",
"dep:instant",
"dep:log",
"dep:reqwest",
"dep:thiserror",
Expand Down
7 changes: 4 additions & 3 deletions sdk/src/client/api/block_builder/transaction_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,8 +449,9 @@ impl TransactionBuilder {
return Err(TransactionBuilderError::InvalidOutputCount(outputs.len()));
}

let inputs_data: Vec<InputSigningData> = self.selected_inputs.into_sorted_iter().collect();
for output_id in self.mana_rewards.keys() {
if !self.selected_inputs.iter().any(|i| output_id == i.output_id()) {
if !inputs_data.iter().any(|i| output_id == i.output_id()) {
return Err(TransactionBuilderError::ExtraManaRewards(*output_id));
}
}
Expand All @@ -463,7 +464,7 @@ impl TransactionBuilder {
.chain(self.commitment_context_input.map(ContextInput::from))
.collect::<Vec<_>>();

for (idx, input) in self.selected_inputs.iter().enumerate() {
for (idx, input) in inputs_data.iter().enumerate() {
inputs.push(Input::Utxo(UtxoInput::from(*input.output_id())));
if self.reward_context_inputs.contains(input.output_id()) {
context_inputs.push(RewardContextInput::new(idx as u16).unwrap().into());
Expand Down Expand Up @@ -494,7 +495,7 @@ impl TransactionBuilder {

let data = PreparedTransactionData {
transaction,
inputs_data: self.selected_inputs.into_sorted_iter().collect(),
inputs_data,
remainders: self.remainders.data,
mana_rewards: self.mana_rewards.into_iter().collect(),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ impl TransactionBuilder {
self.remainders.data.push(RemainderData {
output: catchall,
chain: remainder_address_chain,
address: remainder_address.clone(),
address: remainder_address,
});

Ok(())
Expand Down
9 changes: 2 additions & 7 deletions sdk/src/types/block/output/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,14 +517,9 @@ mod tests {

use super::*;
use crate::types::block::{
output::{basic::dto::BasicOutputDto, FoundryId, SimpleTokenScheme, TokenId},
output::basic::dto::BasicOutputDto,
protocol::iota_mainnet_protocol_parameters,
rand::{
address::rand_account_address,
output::{
feature::rand_allowed_features, rand_basic_output, unlock_condition::rand_address_unlock_condition,
},
},
rand::output::{rand_basic_output, unlock_condition::rand_address_unlock_condition},
};

#[test]
Expand Down
14 changes: 14 additions & 0 deletions sdk/src/types/block/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use core::borrow::Borrow;

use crypto::hashes::{blake2b::Blake2b256, Digest};
use getset::{CopyGetters, Getters};
#[cfg(feature = "std")]
use instant::Duration;
use packable::{prefix::StringPrefix, Packable, PackableExt};
#[cfg(feature = "protocol_parameters_samples")]
pub use samples::{iota_mainnet_protocol_parameters, shimmer_mainnet_protocol_parameters};
Expand Down Expand Up @@ -173,6 +175,18 @@ impl ProtocolParameters {
}
}

/// Calculates the number of slots in a duration.
#[cfg(feature = "std")]
pub fn slots_in_duration(&self, duration: Duration) -> u32 {
(duration.as_secs() / self.slot_duration_in_seconds() as u64) as u32
}

/// Calculates the [`Duration`] of a number of slots.
#[cfg(feature = "std")]
pub fn duration_of_slots(&self, slots: u32) -> Duration {
Duration::from_secs((slots * self.slot_duration_in_seconds() as u32) as u64)
}

/// Gets the [`EpochIndex`] of a given [`SlotIndex`].
pub fn epoch_index_of(&self, slot_index: impl Into<SlotIndex>) -> EpochIndex {
EpochIndex::from_slot_index(slot_index, self.genesis_slot, self.slots_per_epoch_exponent())
Expand Down
1 change: 0 additions & 1 deletion sdk/src/wallet/operations/output_consolidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ where
.map(|bech32| bech32.into_inner())
.unwrap_or_else(|| wallet_address.into_inner()),
),
allow_additional_input_selection: false,
..Default::default()
});

Expand Down
2 changes: 1 addition & 1 deletion sdk/tests/client/common/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@

pub static NODE_LOCAL: &str = "http://localhost:8050";

pub static FAUCET_URL: &str = "http://localhost:8091/api/enqueue";
pub static FAUCET_URL: &str = "http://localhost:8088/api/enqueue";

pub static DEFAULT_MNEMONIC: &str = "inhale gorilla deny three celery song category owner lottery rent author wealth penalty crawl hobby obtain glad warm early rain clutch slab august bleak";
21 changes: 10 additions & 11 deletions sdk/tests/client/node_api/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ async fn test_get_issuance() {
#[ignore]
#[tokio::test]
async fn test_post_block_with_tagged_data() {
let secret_manager = setup_secret_manager();
let block_id = setup_tagged_data_block(&secret_manager).await;
let block_id = setup_tagged_data_block().await.unwrap();
println!("{block_id}");
}

Expand All @@ -72,9 +71,8 @@ async fn test_post_block_with_transaction() {
#[tokio::test]
async fn test_get_block_data() {
let client = setup_client_with_node_health_ignored().await;
let secret_manager = setup_secret_manager();

let block_id = setup_tagged_data_block(&secret_manager).await;
let block_id = setup_tagged_data_block().await.unwrap();
let r = client.get_block(&block_id).await.unwrap();

println!("{r:#?}");
Expand All @@ -83,8 +81,7 @@ async fn test_get_block_data() {
#[ignore]
#[tokio::test]
async fn test_get_block_metadata() {
let secret_manager = setup_secret_manager();
let block_id = setup_tagged_data_block(&secret_manager).await;
let block_id = setup_tagged_data_block().await.unwrap();

let r = setup_client_with_node_health_ignored()
.await
Expand All @@ -98,8 +95,7 @@ async fn test_get_block_metadata() {
#[ignore]
#[tokio::test]
async fn test_get_block_raw() {
let secret_manager = setup_secret_manager();
let block_id = setup_tagged_data_block(&secret_manager).await;
let block_id = setup_tagged_data_block().await.unwrap();

let r = setup_client_with_node_health_ignored()
.await
Expand Down Expand Up @@ -201,7 +197,7 @@ async fn test_call_plugin_route() {

// we call the "custom" plugin "node info"
let plugin_res: NodeInfoResponse = c
.call_plugin_route("api/core/v2/", "GET", "info", vec![], None)
.call_plugin_route("api/core/v3/", "GET", "info", vec![], None)
.await
.unwrap();

Expand All @@ -218,7 +214,7 @@ async fn test_get_routes() {

let routes_response = client.get_routes().await.unwrap();
// At at least one route, which is not created by plugin, is available
assert!(routes_response.routes.contains(&"core/v2".to_string()));
assert!(routes_response.routes.contains(&"core/v3".to_string()));

println!("{routes_response:#?}");
}
Expand All @@ -231,7 +227,10 @@ async fn test_get_included_block_metadata() {
let metadata_response = client.get_included_block_metadata(&transaction_id).await.unwrap();

assert_eq!(metadata_response.block_id, block_id);
assert_eq!(metadata_response.block_state, BlockState::Finalized);
match metadata_response.block_state {
BlockState::Accepted | BlockState::Confirmed | BlockState::Finalized => {}
_ => panic!("block state is not accepted/confirmed/finalized"),
}

println!("{metadata_response:#?}");
}
59 changes: 50 additions & 9 deletions sdk/tests/client/node_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ use iota_sdk::{
client::{
api::GetAddressesOptions,
constants::IOTA_COIN_TYPE,
generate_mnemonic,
node_api::indexer::query_parameters::BasicOutputQueryParameters,
request_funds_from_faucet,
secret::{SecretManager, SignBlock},
secret::{mnemonic::MnemonicSecretManager, SecretManager, SignBlock},
Client,
},
types::block::{
address::{Address, Bech32Address, ImplicitAccountCreationAddress},
output::AccountId,
payload::{signed_transaction::TransactionId, tagged_data::TaggedDataPayload, Payload},
BlockId,
Expand All @@ -29,24 +31,63 @@ use crate::client::common::{setup_client_with_node_health_ignored, FAUCET_URL};
const DEFAULT_DEVELOPMENT_SEED: &str = "0x256a818b2aac458941f7274985a410e57fb750f3a3a67969ece5bd9ae7eef5b2";

// Sends a tagged data block to the node to test against it.
async fn setup_tagged_data_block(secret_manager: &SecretManager) -> BlockId {
async fn setup_tagged_data_block() -> Result<BlockId, Box<dyn std::error::Error>> {
let client = setup_client_with_node_health_ignored().await;

let protocol_params = client.get_protocol_parameters().await.unwrap();
let secret_manager = SecretManager::Mnemonic(MnemonicSecretManager::try_from_mnemonic(generate_mnemonic()?)?);

let bech32_hrp = client.get_bech32_hrp().await?;

let address = secret_manager
.generate_ed25519_address(IOTA_COIN_TYPE, 0, 0, bech32_hrp, None)
.await?;
let address =
Address::ImplicitAccountCreation(ImplicitAccountCreationAddress::new(**address.into_inner().as_ed25519()));
let bech32_address = Bech32Address::new(bech32_hrp, address);

request_funds_from_faucet(FAUCET_URL, &bech32_address).await?;

client
let mut account_id = AccountId::null();
// Continue only after funds are received
for i in 0..30 {
let output_ids = client
.basic_output_ids(BasicOutputQueryParameters::only_address_unlock_condition(
bech32_address.clone(),
))
.await?
.items;
if !output_ids.is_empty() {
account_id = AccountId::from(&output_ids[0]);
break;
}
if i == 29 {
panic!("Faucet no longer wants to hand over coins");
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
// Wait until account is read to issue blocks
for _ in 0..60 {
if client.get_account_congestion(&account_id, None).await.is_ok() {
break;
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}

let block = client
.build_basic_block(
AccountId::null(),
account_id,
Some(Payload::TaggedData(Box::new(
TaggedDataPayload::new(b"Hello".to_vec(), b"Tangle".to_vec()).unwrap(),
))),
)
.await
.unwrap()
.sign_ed25519(secret_manager, Bip44::new(IOTA_COIN_TYPE))
.await
.unwrap()
.id(&protocol_params)
.sign_ed25519(&secret_manager, Bip44::new(IOTA_COIN_TYPE))
.await?;
client.post_block(&block).await?;

let protocol_params = client.get_protocol_parameters().await.unwrap();
Ok(block.id(&protocol_params))
}

pub fn setup_secret_manager() -> SecretManager {
Expand Down
Loading

0 comments on commit 2259f6e

Please sign in to comment.