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

fix(sdk)!: create channel error due to empty address #2317

Open
wants to merge 20 commits into
base: v1.7-dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
6 changes: 0 additions & 6 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ on:
branches:
- master
- 'v[0-9]+\.[0-9]+-dev'
push:
branches:
- master
- 'v[0-9]+\.[0-9]+-dev'
schedule:
- cron: "30 4 * * *"

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
Expand Down
55 changes: 31 additions & 24 deletions packages/rs-dapi-client/src/address_list.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Subsystem to manage DAPI nodes.

use chrono::Utc;
use dapi_grpc::tonic::codegen::http;
use dapi_grpc::tonic::transport::Uri;
use rand::{rngs::SmallRng, seq::IteratorRandom, SeedableRng};
use std::collections::HashSet;
Expand All @@ -26,8 +25,8 @@ impl FromStr for Address {

fn from_str(s: &str) -> Result<Self, Self::Err> {
Uri::from_str(s)
.map(Address::from)
.map_err(AddressListError::from)
.map_err(|e| AddressListError::InvalidAddressUri(e.to_string()))
.map(Address::try_from)?
}
}

Expand All @@ -49,13 +48,21 @@ impl Hash for Address {
}
}

impl From<Uri> for Address {
fn from(uri: Uri) -> Self {
Address {
impl TryFrom<Uri> for Address {
type Error = AddressListError;

fn try_from(value: Uri) -> Result<Self, Self::Error> {
if value.host().is_none() {
return Err(AddressListError::InvalidAddressUri(
"uri must contain host".to_string(),
));
}

Ok(Address {
ban_count: 0,
banned_until: None,
uri,
}
uri: value,
})
}
}

Expand Down Expand Up @@ -96,7 +103,7 @@ pub enum AddressListError {
/// A valid uri is required to create an Address
#[error("unable parse address: {0}")]
#[cfg_attr(feature = "mocks", serde(skip))]
InvalidAddressUri(#[from] http::uri::InvalidUri),
InvalidAddressUri(String),
}

/// A structure to manage DAPI addresses to select from
Expand Down Expand Up @@ -167,13 +174,12 @@ impl AddressList {
self.addresses.insert(address)
}

// TODO: this is the most simple way to add an address
// however we need to support bulk loading (e.g. providing a network name)
// and also fetch updated from SML.
#[deprecated]
// TODO: Remove in favor of add
/// Add a node [Address] to [AddressList] by [Uri].
/// Returns false if the address is already in the list.
pub fn add_uri(&mut self, uri: Uri) -> bool {
self.addresses.insert(uri.into())
self.addresses.insert(uri.try_into().expect("valid uri"))
lklimek marked this conversation as resolved.
Show resolved Hide resolved
}

/// Randomly select a not banned address.
Expand All @@ -185,7 +191,7 @@ impl AddressList {

/// Get all addresses that are not banned.
fn unbanned(&self) -> Vec<&Address> {
let now = chrono::Utc::now();
let now = Utc::now();

self.addresses
.iter()
Expand Down Expand Up @@ -216,23 +222,24 @@ impl AddressList {
}
}

// TODO: Must be changed to FromStr
impl From<&str> for AddressList {
fn from(value: &str) -> Self {
let uri_list: Vec<Uri> = value
impl FromStr for AddressList {
type Err = AddressListError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let uri_list: Vec<Address> = s
.split(',')
.map(|uri| Uri::from_str(uri).expect("invalid uri"))
.collect();
.map(Address::from_str)
.collect::<Result<_, _>>()?;

Self::from_iter(uri_list)
Ok(Self::from_iter(uri_list))
}
}

impl FromIterator<Uri> for AddressList {
fn from_iter<T: IntoIterator<Item = Uri>>(iter: T) -> Self {
impl FromIterator<Address> for AddressList {
fn from_iter<T: IntoIterator<Item = Address>>(iter: T) -> Self {
let mut address_list = Self::new();
for uri in iter {
address_list.add_uri(uri);
address_list.add(uri);
}

address_list
Expand Down
10 changes: 5 additions & 5 deletions packages/rs-dapi-client/src/transport/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ impl TransportClient for PlatformGrpcClient {
.get_or_create(PoolPrefix::Platform, &uri, None, || {
match create_channel(uri.clone(), None) {
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
"Channel creation failed: {}",
Err(e) => Err(dapi_grpc::tonic::Status::invalid_argument(format!(
"channel creation failed: {}",
shumkov marked this conversation as resolved.
Show resolved Hide resolved
e
))),
}
Expand All @@ -65,7 +65,7 @@ impl TransportClient for PlatformGrpcClient {
Some(settings),
|| match create_channel(uri.clone(), Some(settings)) {
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
Err(e) => Err(dapi_grpc::tonic::Status::invalid_argument(format!(
"Channel creation failed: {}",
e
))),
Expand All @@ -81,7 +81,7 @@ impl TransportClient for CoreGrpcClient {
.get_or_create(PoolPrefix::Core, &uri, None, || {
match create_channel(uri.clone(), None) {
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
Err(e) => Err(dapi_grpc::tonic::Status::invalid_argument(format!(
"Channel creation failed: {}",
e
))),
Expand All @@ -102,7 +102,7 @@ impl TransportClient for CoreGrpcClient {
Some(settings),
|| match create_channel(uri.clone(), Some(settings)) {
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
Err(e) => Err(dapi_grpc::tonic::Status::invalid_argument(format!(
"Channel creation failed: {}",
e
))),
Expand Down
8 changes: 4 additions & 4 deletions packages/rs-sdk/examples/read_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{num::NonZeroUsize, str::FromStr};
use clap::Parser;
use dash_sdk::{mock::provider::GrpcContextProvider, platform::Fetch, Sdk, SdkBuilder};
use dpp::prelude::{DataContract, Identifier};
use rs_dapi_client::AddressList;
use rs_dapi_client::{Address, AddressList};
use zeroize::Zeroizing;

#[derive(clap::Parser, Debug)]
Expand Down Expand Up @@ -80,14 +80,14 @@ fn setup_sdk(config: &Config) -> Sdk {

// Let's build the Sdk.
// First, we need an URI of some Dash Platform DAPI host to connect to and use as seed.
let uri = http::Uri::from_str(&format!(
"http://{}:{}",
let address = Address::from_str(&format!(
"https://{}:{}",
config.server_address, config.platform_port
))
.expect("parse uri");

// Now, we create the Sdk with the wallet and context provider.
let sdk = SdkBuilder::new(AddressList::from_iter([uri]))
let sdk = SdkBuilder::new(AddressList::from_iter([address]))
.build()
.expect("cannot build sdk");

Expand Down
4 changes: 2 additions & 2 deletions packages/rs-sdk/src/platform/types/evonode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use std::fmt::Debug;
/// use futures::executor::block_on;
///
/// let sdk = Sdk::new_mock();
/// let uri: http::Uri = "http://127.0.0.1:1".parse().unwrap();
/// let node = EvoNode::new(uri.into());
/// let address = "http://127.0.0.1:1".parse().expect("valid address");
/// let node = EvoNode::new(address);
shumkov marked this conversation as resolved.
Show resolved Hide resolved
/// let status = block_on(EvoNodeStatus::fetch_unproved(&sdk, node)).unwrap();
/// ```

Expand Down
7 changes: 3 additions & 4 deletions packages/rs-sdk/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,10 @@ where
let result= ::backon::Retryable::retry(closure,backoff_strategy)
.when(|e| {
if e.can_retry() {
// requests sent for current execution attempt;
// requests sent for current execution attempt;
let requests_sent = e.retries + 1;

// requests sent in all preceeding attempts; user expects `settings.retries +1`
// requests sent in all preceeding attempts; user expects `settings.retries +1`
retries += requests_sent;
let all_requests_sent = retries;

Expand Down Expand Up @@ -231,7 +231,6 @@ where
#[cfg(test)]
mod test {
use super::*;
use http::Uri;
use rs_dapi_client::ExecutionError;
use std::{
future::Future,
Expand Down Expand Up @@ -342,7 +341,7 @@ mod test {
Err(ExecutionError {
inner: MockError::Generic,
retries,
address: Some(Uri::from_static("http://localhost").into()),
address: Some("http://localhost".parse().expect("valid address")),
})
}

Expand Down
9 changes: 6 additions & 3 deletions packages/rs-sdk/tests/fetch/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use dpp::{
dashcore::{hashes::Hash, ProTxHash},
prelude::Identifier,
};
use rs_dapi_client::AddressList;
use rs_dapi_client::{Address, AddressList};
use serde::Deserialize;
use std::{path::PathBuf, str::FromStr};
use zeroize::Zeroizing;
Expand Down Expand Up @@ -131,9 +131,12 @@ impl Config {
false => "http",
};

let address: String = format!("{}://{}:{}", scheme, self.platform_host, self.platform_port);
let address: Address =
format!("{}://{}:{}", scheme, self.platform_host, self.platform_port)
.parse()
.expect("valid address");

AddressList::from_iter(vec![http::Uri::from_str(&address).expect("valid uri")])
AddressList::from_iter([address])
}

/// Create new SDK instance
Expand Down
7 changes: 4 additions & 3 deletions packages/rs-sdk/tests/fetch/evonode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use dash_sdk::platform::{types::evonode::EvoNode, FetchUnproved};
use dpp::dashcore::{hashes::Hash, ProTxHash};
use drive_proof_verifier::types::EvoNodeStatus;
use http::Uri;
use rs_dapi_client::Address;
use std::time::Duration;
/// Given some existing evonode URIs, WHEN we connect to them, THEN we get status.
use tokio::time::timeout;
Expand Down Expand Up @@ -61,11 +62,11 @@ async fn test_evonode_status_refused() {
let cfg = Config::new();
let sdk = cfg.setup_api("test_evonode_status_refused").await;

let uri: Uri = "http://127.0.0.1:1".parse().unwrap();
let address: Address = "http://127.0.0.1:1".parse().expect("valid address");

let node = EvoNode::new(uri.clone().into());
let node = EvoNode::new(address.clone());
let result = EvoNodeStatus::fetch_unproved(&sdk, node).await;
tracing::debug!(?result, ?uri, "evonode status");
tracing::debug!(?result, ?address, "evonode status");

assert!(result.is_err());
}
Loading