Skip to content

Commit

Permalink
Merge pull request maidsafe#2209 from grumbach/simpler_evm_connection
Browse files Browse the repository at this point in the history
  • Loading branch information
grumbach authored Oct 8, 2024
2 parents 8fa2265 + 3a8eef4 commit 5c61df8
Show file tree
Hide file tree
Showing 20 changed files with 133 additions and 50 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

8 changes: 8 additions & 0 deletions autonomi/src/client/data.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::self_encryption::DataMapLevel;
use bytes::Bytes;
use evmlib::wallet;
Expand Down
8 changes: 8 additions & 0 deletions autonomi/src/client/files.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::client::data::{GetError, PutError};
use crate::client::Client;
use crate::self_encryption::encrypt;
Expand Down
8 changes: 8 additions & 0 deletions autonomi/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

pub mod address;

#[cfg(feature = "data")]
Expand Down
8 changes: 8 additions & 0 deletions autonomi/src/client/vault.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use std::collections::HashSet;

use crate::client::data::PutError;
Expand Down
9 changes: 9 additions & 0 deletions autonomi/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Copyright 2024 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

//! Connect to and build on the Autonomi network.
//!
//! # Data types
Expand Down Expand Up @@ -25,6 +33,7 @@ pub mod client;
#[cfg(feature = "data")]
mod self_encryption;

pub use sn_evm::evm;
pub use sn_evm::EvmNetwork;
pub use sn_evm::EvmWallet as Wallet;

Expand Down
1 change: 0 additions & 1 deletion autonomi_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ autonomi = { path = "../autonomi", version = "0.1.0", features = ["data", "files
clap = { version = "4.2.1", features = ["derive"] }
color-eyre = "~0.6"
dirs-next = "~2.0.0"
evmlib = { path = "../evmlib", version = "0.1.0" }
indicatif = { version = "0.17.5", features = ["tokio"] }
tokio = { version = "1.32.0", features = [
"io-util",
Expand Down
3 changes: 1 addition & 2 deletions autonomi_cli/src/access/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ const REGISTER_SIGNING_KEY_FILE: &str = "register_signing_key";
pub fn load_evm_wallet() -> Result<Wallet> {
let secret_key =
get_secret_key().wrap_err("The secret key is required to perform this action")?;
let network = crate::network::get_evm_network_from_environment()
.wrap_err("Failed to load EVM network")?;
let network = crate::network::get_evm_network_from_env();
let wallet = Wallet::new_from_private_key(network, &secret_key)
.wrap_err("Failed to load EVM wallet from key")?;
Ok(wallet)
Expand Down
11 changes: 7 additions & 4 deletions autonomi_cli/src/access/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

use autonomi::EvmNetwork;
use autonomi::Multiaddr;
use color_eyre::eyre::eyre;
use color_eyre::eyre::Context;
use color_eyre::Result;
use color_eyre::Section;
Expand All @@ -23,7 +22,11 @@ pub async fn get_peers(peers: PeersArgs) -> Result<Vec<Multiaddr>> {
.with_suggestion(|| "a peer address looks like this: /ip4/42.42.42.42/udp/4242/quic-v1/p2p/B64nodePeerIDvdjb3FAJF4ks3moreBase64CharsHere")
}

pub(crate) fn get_evm_network_from_environment() -> Result<EvmNetwork> {
evmlib::utils::evm_network_from_env()
.map_err(|err| eyre!("Failed to get EVM network from environment: {err}"))
pub fn get_evm_network_from_env() -> EvmNetwork {
let network = autonomi::evm::network_from_env();
if matches!(network, EvmNetwork::Custom(_)) {
println!("Using custom EVM network found from environment variables");
info!("Using custom EVM network found from environment variables {network:?}");
}
network
}
1 change: 1 addition & 0 deletions evm_testnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ version = "0.1.0"
clap = { version = "4.5", features = ["derive"] }
dirs-next = "~2.0.0"
evmlib = { path = "../evmlib" }
sn_evm = { path = "../sn_evm" }
tokio = { version = "1.40", features = ["rt-multi-thread", "signal"] }

[lints]
Expand Down
15 changes: 15 additions & 0 deletions evm_testnet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,21 @@ impl TestnetData {
if let Some((tokens, gas)) = self.tokens_and_gas {
println!("Genesis wallet balance (atto): (tokens: {tokens}, gas: {gas})");
}

println!();
println!("--------------");
println!("Run the CLI or Node with the following env vars set to use this network:");
println!(
"{}=\"{}\" {}=\"{}\" {}=\"{}\"",
sn_evm::evm::RPC_URL,
self.rpc_url,
sn_evm::evm::PAYMENT_TOKEN_ADDRESS,
self.payment_token_address,
sn_evm::evm::DATA_PAYMENTS_ADDRESS,
self.data_payments_address
);
println!("--------------");
println!();
}

fn save_csv(&self) {
Expand Down
10 changes: 9 additions & 1 deletion evmlib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub struct CustomNetwork {
}

impl CustomNetwork {
pub fn new(rpc_url: &str, payment_token_addr: &str, data_payments_addr: &str) -> Self {
fn new(rpc_url: &str, payment_token_addr: &str, data_payments_addr: &str) -> Self {
Self {
rpc_url_http: reqwest::Url::parse(rpc_url).expect("Invalid RPC URL"),
payment_token_address: Address::from_str(payment_token_addr)
Expand All @@ -56,6 +56,14 @@ pub enum Network {
}

impl Network {
pub fn new_custom(rpc_url: &str, payment_token_addr: &str, chunk_payments_addr: &str) -> Self {
Self::Custom(CustomNetwork::new(
rpc_url,
payment_token_addr,
chunk_payments_addr,
))
}

pub fn identifier(&self) -> &str {
match self {
Network::ArbitrumOne => "arbitrum-one",
Expand Down
10 changes: 8 additions & 2 deletions evmlib/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ use std::env;

pub const EVM_TESTNET_CSV_FILENAME: &str = "evm_testnet_data.csv";

/// environment variable to connect to a custom EVM network
pub const RPC_URL: &str = "RPC_URL";
pub const PAYMENT_TOKEN_ADDRESS: &str = "PAYMENT_TOKEN_ADDRESS";
pub const DATA_PAYMENTS_ADDRESS: &str = "DATA_PAYMENTS_ADDRESS";

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Failed to get EVM network")]
Expand All @@ -24,7 +29,7 @@ pub fn dummy_hash() -> Hash {

/// Get the `Network` from environment variables
pub fn evm_network_from_env() -> Result<Network, Error> {
let evm_vars = ["RPC_URL", "PAYMENT_TOKEN_ADDRESS", "DATA_PAYMENTS_ADDRESS"]
let evm_vars = [RPC_URL, PAYMENT_TOKEN_ADDRESS, DATA_PAYMENTS_ADDRESS]
.iter()
.map(|var| env::var(var).map_err(|_| Error::FailedToGetEvmNetwork))
.collect::<Result<Vec<String>, Error>>();
Expand Down Expand Up @@ -62,7 +67,8 @@ pub fn local_evm_network_from_csv() -> Result<Network, Error> {

if !csv_path.exists() {
error!("evm data csv path does not exist {:?}", csv_path);
return Err(Error::FailedToGetEvmNetwork);
return Err(Error::FailedToGetEvmNetwork)
.inspect_err(|_| error!("Missing evm testnet CSV file"))?;
}

let csv = std::fs::read_to_string(&csv_path)
Expand Down
17 changes: 17 additions & 0 deletions sn_evm/src/data_payments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// permissions and limitations relating to use of the SAFE Network Software.

use crate::{AttoTokens, EvmError};
use evmlib::common::TxHash;
use evmlib::{
common::{Address as RewardsAddress, QuoteHash},
utils::dummy_address,
Expand All @@ -22,6 +23,22 @@ pub const QUOTE_EXPIRATION_SECS: u64 = 3600;
/// The margin allowed for live_time
const LIVE_TIME_MARGIN: u64 = 10;

/// The proof of payment for a data payment
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ProofOfPayment {
/// The Quote we're paying for
pub quote: PaymentQuote,
/// The transaction hash
pub tx_hash: TxHash,
}

impl ProofOfPayment {
pub fn to_peer_id_payee(&self) -> Option<PeerId> {
let pub_key = PublicKey::try_decode_protobuf(&self.quote.pub_key).ok()?;
Some(PeerId::from_public_key(&pub_key))
}
}

/// Quoting metrics that got used to generate a quote, or to track peer's status.
#[derive(
Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize, custom_debug::Debug,
Expand Down
28 changes: 10 additions & 18 deletions sn_evm/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,17 @@
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use evmlib::common::TxHash;
use libp2p::identity::PublicKey;
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use crate::EvmNetwork;

use crate::PaymentQuote;
pub use evmlib::utils::{DATA_PAYMENTS_ADDRESS, PAYMENT_TOKEN_ADDRESS, RPC_URL};

/// The proof of payment for a data payment
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ProofOfPayment {
/// The Quote we're paying for
pub quote: PaymentQuote,
/// The transaction hash
pub tx_hash: TxHash,
}

impl ProofOfPayment {
pub fn to_peer_id_payee(&self) -> Option<PeerId> {
let pub_key = PublicKey::try_decode_protobuf(&self.quote.pub_key).ok()?;
Some(PeerId::from_public_key(&pub_key))
/// Load the evm network from env
pub fn network_from_env() -> EvmNetwork {
match evmlib::utils::evm_network_from_env() {
Ok(network) => network,
Err(e) => {
warn!("Failed to get EVM network from environment variables, using default: {e}");
EvmNetwork::default()
}
}
}
8 changes: 4 additions & 4 deletions sn_evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ pub use evmlib::common::Address as RewardsAddress;
pub use evmlib::common::{QuoteHash, TxHash};
pub use evmlib::utils;
pub use evmlib::wallet::Wallet as EvmWallet;
pub use evmlib::CustomNetwork as EvmNetworkCustom;
pub use evmlib::Network as EvmNetwork;

mod amount;
mod data_payments;
mod error;
mod evm;

pub use data_payments::{PaymentQuote, QuotingMetrics};
pub use evm::ProofOfPayment;
/// EVM network configuration
pub mod evm;

pub use data_payments::{PaymentQuote, ProofOfPayment, QuotingMetrics};

/// Types used in the public API
pub use amount::{Amount, AttoTokens};
Expand Down
7 changes: 6 additions & 1 deletion sn_node/src/bin/safenode/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,12 @@ fn main() -> Result<()> {
.as_ref()
.cloned()
.map(|v| v.into())
.unwrap_or_default();
.unwrap_or_else(sn_evm::evm::network_from_env);
if matches!(evm_network, EvmNetwork::Custom(_)) {
println!("Using custom EVM network");
info!("Using custom EVM network {evm_network:?}");
}
println!("EVM network: {evm_network:?}");

let node_socket_addr = SocketAddr::new(opt.ip, opt.port);
let (root_dir, keypair) = get_root_dir_and_keypair(&opt.root_dir)?;
Expand Down
8 changes: 2 additions & 6 deletions sn_node/src/bin/safenode/subcommands.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clap::Subcommand;
use sn_evm::{EvmNetwork, EvmNetworkCustom};
use sn_evm::EvmNetwork;

#[derive(Subcommand, Clone, Debug)]
pub(crate) enum EvmNetworkCommand {
Expand Down Expand Up @@ -31,11 +31,7 @@ impl Into<EvmNetwork> for EvmNetworkCommand {
rpc_url,
payment_token_address,
data_payments_address,
} => EvmNetwork::Custom(EvmNetworkCustom::new(
&rpc_url,
&payment_token_address,
&data_payments_address,
)),
} => EvmNetwork::new_custom(&rpc_url, &payment_token_address, &data_payments_address),
}
}
}
6 changes: 3 additions & 3 deletions sn_node_manager/src/bin/cli/subcommands/evm_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

use clap::Subcommand;
use color_eyre::eyre::Result;
use sn_evm::{utils::local_evm_network_from_csv, EvmNetwork, EvmNetworkCustom};
use sn_evm::{utils::local_evm_network_from_csv, EvmNetwork};

#[derive(Subcommand, Clone, Debug)]
#[allow(clippy::enum_variant_names)]
Expand Down Expand Up @@ -49,11 +49,11 @@ impl TryInto<EvmNetwork> for EvmNetworkCommand {
rpc_url,
payment_token_address,
data_payments_address,
} => Ok(EvmNetwork::Custom(EvmNetworkCustom::new(
} => Ok(EvmNetwork::new_custom(
&rpc_url,
&payment_token_address,
&data_payments_address,
))),
)),
}
}
}
15 changes: 8 additions & 7 deletions sn_node_manager/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@
// permissions and limitations relating to use of the SAFE Network Software.

use crate::add_services::config::PortRange;
#[cfg(feature = "faucet")]
use crate::helpers::get_username;
use crate::helpers::{
check_port_availability, get_bin_version, get_start_port_if_applicable, increment_port_option,
};

#[cfg(feature = "faucet")]
use crate::helpers::get_username;
#[cfg(feature = "faucet")]
use sn_service_management::FaucetServiceData;
#[cfg(feature = "faucet")]
use sn_transfers::get_faucet_data_dir;

use color_eyre::eyre::OptionExt;
use color_eyre::{eyre::eyre, Result};
use colored::Colorize;
Expand All @@ -20,16 +26,11 @@ use libp2p::{multiaddr::Protocol, Multiaddr, PeerId};
use mockall::automock;
use sn_evm::{EvmNetwork, RewardsAddress};
use sn_logging::LogFormat;
#[cfg(feature = "faucet")]
use sn_service_management::FaucetServiceData;
use sn_service_management::{
control::ServiceControl,
rpc::{RpcActions, RpcClient},
NodeRegistry, NodeServiceData, ServiceStatus,
};
#[cfg(feature = "faucet")]
use sn_transfers::get_faucet_data_dir;

use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
Expand Down

0 comments on commit 5c61df8

Please sign in to comment.