Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
sdbondi committed Oct 14, 2024
1 parent 45fc0b2 commit 924e1b5
Show file tree
Hide file tree
Showing 24 changed files with 203 additions and 436 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

15 changes: 4 additions & 11 deletions base_layer/wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,16 @@ edition = "2018"

[dependencies]
tari_network = { workspace = true }
tari_rpc_framework = { workspace = true }
tari_common = { path = "../../common", version = "1.6.0-pre.0" }
tari_common_sqlite = { path = "../../common_sqlite", version = "1.6.0-pre.0" }
tari_common_types = { path = "../../base_layer/common_types", version = "1.6.0-pre.0" }
tari_contacts = { path = "../../base_layer/contacts", version = "1.6.0-pre.0" }
tari_core = { path = "../../base_layer/core", default-features = false, features = [
"transactions",
"mempool_proto",
"base_node_proto",
], version = "1.6.0-pre.0" }
tari_core = { path = "../../base_layer/core", default-features = false, features = ["transactions", "mempool_proto", "base_node_proto"], version = "1.6.0-pre.0" }
tari_crypto = { version = "0.20.3" }
tari_max_size = { path = "../../infrastructure/max_size" }
tari_key_manager = { path = "../key_manager", features = [
"key_manager_service",
], version = "1.6.0-pre.0" }
tari_p2p = { path = "../p2p", features = [
"auto-update",
], version = "1.6.0-pre.0" }
tari_key_manager = { path = "../key_manager", features = ["key_manager_service", ], version = "1.6.0-pre.0" }
tari_p2p = { path = "../p2p", features = ["auto-update"], version = "1.6.0-pre.0" }
tari_script = { path = "../../infrastructure/tari_script", version = "1.6.0-pre.0" }
tari_service_framework = { path = "../service_framework", version = "1.6.0-pre.0" }
tari_shutdown = { path = "../../infrastructure/shutdown", version = "1.6.0-pre.0" }
Expand Down
117 changes: 117 additions & 0 deletions base_layer/wallet/src/base_node_service/backoff.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright 2019, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::{cmp::min, time::Duration};

/// Boxed backoff
pub type BoxedBackoff = Box<dyn Backoff + Send + Sync>;

pub trait Backoff {
fn calculate_backoff(&self, attempts: usize) -> Duration;
}

impl Backoff for BoxedBackoff {
fn calculate_backoff(&self, attempts: usize) -> Duration {
(**self).calculate_backoff(attempts)
}
}

/// Returns a backoff Duration that increases exponentially to the number of attempts.
#[derive(Debug, Clone)]
pub struct ExponentialBackoff {
factor: f32,
}

impl ExponentialBackoff {
pub fn new(factor: f32) -> Self {
Self { factor }
}
}

impl Default for ExponentialBackoff {
fn default() -> Self {
Self::new(1.5)
}
}

impl Backoff for ExponentialBackoff {
fn calculate_backoff(&self, attempts: usize) -> Duration {
if attempts <= 1 {
return Duration::from_secs(0);
}
// We put an upper bound on attempts so that it can never overflow the 52-bit mantissa when converting to f64
let secs = (f64::from(self.factor)) * ((1usize << min(attempts, 51)) as f64 - 1.0);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Duration::from_secs(secs.ceil() as u64)
}
}

/// Returns a backoff Duration that increases linearly to the number of attempts.
#[derive(Clone)]
pub struct ConstantBackoff(Duration);

impl ConstantBackoff {
pub fn new(timeout: Duration) -> Self {
Self(timeout)
}
}

impl Backoff for ConstantBackoff {
fn calculate_backoff(&self, attempts: usize) -> Duration {
if attempts <= 1 {
return Duration::from_secs(0);
}
self.0
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn default_backoff() {
let backoff = ExponentialBackoff::default();
assert_eq!(backoff.calculate_backoff(0).as_secs(), 0);
assert_eq!(backoff.calculate_backoff(1).as_secs(), 0);
assert_eq!(backoff.calculate_backoff(2).as_secs(), 5);
assert_eq!(backoff.calculate_backoff(3).as_secs(), 11);
assert_eq!(backoff.calculate_backoff(4).as_secs(), 23);
assert_eq!(backoff.calculate_backoff(5).as_secs(), 47);
assert_eq!(backoff.calculate_backoff(6).as_secs(), 95);
assert_eq!(backoff.calculate_backoff(7).as_secs(), 191);
assert_eq!(backoff.calculate_backoff(8).as_secs(), 383);
assert_eq!(backoff.calculate_backoff(9).as_secs(), 767);
assert_eq!(backoff.calculate_backoff(10).as_secs(), 1535);
assert_eq!(backoff.calculate_backoff(63).as_secs(), 3377699720527871);
assert_eq!(backoff.calculate_backoff(64).as_secs(), 3377699720527871);
assert_eq!(backoff.calculate_backoff(200).as_secs(), 3377699720527871);
}

#[test]
fn zero_backoff() {
let backoff = ExponentialBackoff::new(0.0);
assert_eq!(backoff.calculate_backoff(0).as_secs(), 0);
assert_eq!(backoff.calculate_backoff(1).as_secs(), 0);
assert_eq!(backoff.calculate_backoff(200).as_secs(), 0);
}
}
4 changes: 1 addition & 3 deletions base_layer/wallet/src/base_node_service/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use tari_comms::{connectivity::ConnectivityError, protocol::rpc::RpcError};
use tari_comms_dht::outbound::DhtOutboundError;
use tari_rpc_framework::RpcError;
use tari_service_framework::reply_channel::TransportChannelError;
use thiserror::Error;

Expand All @@ -31,8 +31,6 @@ use crate::{connectivity_service::WalletConnectivityError, error::WalletStorageE
pub enum BaseNodeServiceError {
#[error("No base node peer set")]
NoBaseNodePeer,
#[error("Error connecting to base node: {0}")]
BaseNodeConnectivityError(#[from] ConnectivityError),
#[error("RPC Error: `{0}`")]
RpcError(#[from] RpcError),
#[error("No chain metadata from peer")]
Expand Down
1 change: 1 addition & 0 deletions base_layer/wallet/src/base_node_service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub mod error;
pub mod handle;
pub mod service;

mod backoff;
mod monitor;

use log::*;
Expand Down
5 changes: 1 addition & 4 deletions base_layer/wallet/src/base_node_service/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,11 @@ use chrono::Utc;
use futures::{future, future::Either};
use log::*;
use tari_common_types::{chain_metadata::ChainMetadata, types::BlockHash as BlockHashType};
use tari_comms::{
backoff::{Backoff, ExponentialBackoff},
protocol::rpc::RpcError,
};
use tokio::{sync::RwLock, time};

use crate::{
base_node_service::{
backoff::ExponentialBackoff,
handle::{BaseNodeEvent, BaseNodeEventSender},
service::BaseNodeState,
},
Expand Down
4 changes: 2 additions & 2 deletions base_layer/wallet/src/base_node_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use chrono::NaiveDateTime;
use futures::{future, StreamExt};
use log::*;
use tari_common_types::chain_metadata::ChainMetadata;
use tari_comms::peer_manager::NodeId;
use tari_network::identity::PeerId;
use tari_service_framework::reply_channel::Receiver;
use tari_shutdown::ShutdownSignal;
use tokio::sync::RwLock;
Expand All @@ -47,7 +47,7 @@ const LOG_TARGET: &str = "wallet::base_node_service::service";
/// State determined from Base Node Service Requests
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct BaseNodeState {
pub node_id: Option<NodeId>,
pub node_id: Option<PeerId>,
pub chain_metadata: Option<ChainMetadata>,
pub is_synced: Option<bool>,
pub updated: Option<NaiveDateTime>,
Expand Down
3 changes: 0 additions & 3 deletions base_layer/wallet/src/connectivity_service/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,11 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use futures::channel::{mpsc, oneshot};
use tari_comms::connectivity::ConnectivityError;

#[derive(Debug, thiserror::Error)]
pub enum WalletConnectivityError {
#[error("Base node has not been set")]
BaseNodeNotSet,
#[error("Connectivity error: {0}")]
ConnectivityError(#[from] ConnectivityError),
#[error("Service is terminated and can no longer response to requests")]
ServiceTerminated,
#[error("Preferred peer index is out of bounds: {0}")]
Expand Down
6 changes: 1 addition & 5 deletions base_layer/wallet/src/connectivity_service/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,8 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use tari_comms::{
peer_manager::{NodeId, Peer},
protocol::rpc::RpcClientLease,
types::CommsPublicKey,
};
use tari_core::base_node::{rpc::BaseNodeWalletRpcClient, sync::rpc::BaseNodeSyncRpcClient};
use tari_rpc_framework::pool::RpcClientLease;
use tokio::sync::{mpsc, oneshot, watch};

use super::service::OnlineStatus;
Expand Down
7 changes: 0 additions & 7 deletions base_layer/wallet/src/connectivity_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,6 @@
use std::{mem, time::Duration};

use log::*;
use tari_comms::{
connectivity::{ConnectivityError, ConnectivityRequester},
peer_manager::NodeId,
protocol::rpc::{RpcClientLease, RpcClientPool},
Minimized,
PeerConnection,
};
use tari_core::base_node::{rpc::BaseNodeWalletRpcClient, sync::rpc::BaseNodeSyncRpcClient};
use tokio::{
sync::{mpsc, oneshot, watch},
Expand Down
7 changes: 3 additions & 4 deletions base_layer/wallet/src/output_manager_service/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ use tari_common_types::{
transaction::TxId,
types::{BlockHash, Commitment, HashOutput, PrivateKey, PublicKey},
};
use tari_comms::types::CommsDHKE;
use tari_core::{
borsh::SerializedSize,
consensus::ConsensusConstants,
Expand All @@ -42,10 +41,9 @@ use tari_core::{
shared_secret_to_output_encryption_key,
shared_secret_to_output_spending_key,
},
proto::base_node::FetchMatchingUtxos,
transactions::{
fee::Fee,
key_manager::{TariKeyId, TransactionKeyManagerInterface},
key_manager::{RistrettoDiffieHellmanSharedSecret, TariKeyId, TransactionKeyManagerInterface},
tari_amount::MicroMinotari,
transaction_components::{
encrypted_data::PaymentId,
Expand All @@ -68,6 +66,7 @@ use tari_core::{
};
use tari_crypto::{commitment::HomomorphicCommitmentFactory, ristretto::pedersen::PedersenCommitment};
use tari_key_manager::key_manager_service::{KeyAndId, KeyId, SerializedKeyString};
use tari_p2p::proto::base_node::FetchMatchingUtxos;
use tari_script::{
inputs,
push_pubkey_script,
Expand Down Expand Up @@ -1468,7 +1467,7 @@ where
)
.await?;
key_sum = key_sum + &PublicKey::from_vec(&shared_secret_self.as_bytes().to_vec())?;
CommsDHKE::from_canonical_bytes(key_sum.as_bytes())?
RistrettoDiffieHellmanSharedSecret::from_canonical_bytes(key_sum.as_bytes())?
};
trace!(target: LOG_TARGET, "encumber_aggregate_utxo: created dh shared secret");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,9 @@ use std::{
use chrono::{Duration, Utc};
use log::*;
use tari_common_types::types::{BlockHash, FixedHash};
use tari_comms::protocol::rpc::RpcError::RequestFailed;
use tari_core::{
base_node::rpc::BaseNodeWalletRpcClient,
blocks::BlockHeader,
proto::base_node::{QueryDeletedRequest, UtxoQueryRequest},
};
use tari_core::{base_node::rpc::BaseNodeWalletRpcClient, blocks::BlockHeader};
use tari_p2p::proto::base_node::{QueryDeletedRequest, UtxoQueryRequest};
use tari_rpc_framework::RpcError;
use tari_utilities::hex::Hex;
use tokio::sync::watch;

Expand Down Expand Up @@ -501,7 +498,7 @@ where
"Error asking base node for header:{} (Operation ID: {})", rpc_error, self.operation_id
);
match &rpc_error {
RequestFailed(status) => {
RpcError::RequestFailed(status) => {
if status.as_status_code().is_not_found() {
return Ok(None);
} else {
Expand Down
8 changes: 1 addition & 7 deletions base_layer/wallet/src/transaction_service/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ use tari_crypto::{errors::RangeProofError, signatures::CommitmentSignatureError}
use tari_key_manager::key_manager_service::KeyManagerServiceError;
use tari_network::NetworkError;
use tari_p2p::services::liveness::error::LivenessError;
use tari_rpc_framework::RpcError;
use tari_script::ScriptError;
use tari_service_framework::reply_channel::TransportChannelError;
use tari_utilities::ByteArrayError;
Expand Down Expand Up @@ -130,8 +131,6 @@ pub enum TransactionServiceError {
ConversionError(#[from] TransactionConversionError),
#[error("duration::NegativeDurationError: {0}")]
DurationOutOfRange(#[from] NegativeDurationError),
#[error("Node ID error: `{0}`")]
NodeIdError(#[from] NodeIdError),
#[error("Broadcast recv error: `{0}`")]
BroadcastRecvError(#[from] RecvError),
#[error("Broadcast send error: `{0}`")]
Expand Down Expand Up @@ -168,11 +167,6 @@ pub enum TransactionServiceError {
WalletRecoveryInProgress,
#[error("Wallet Transaction Validation already in progress, request ignored")]
TransactionValidationInProgress,
#[error("Connectivity error: {source}")]
ConnectivityError {
#[from]
source: ConnectivityError,
},
#[error("Base Node is not synced")]
BaseNodeNotSynced,
#[error("Value encryption error: `{0}`")]
Expand Down
12 changes: 2 additions & 10 deletions base_layer/wallet/src/transaction_service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,15 @@ use futures::{Stream, StreamExt};
use log::*;
use tari_common::configuration::Network;
use tari_common_types::wallet_types::WalletType;
use tari_comms::NodeIdentity;
use tari_comms_dht::Dht;
use tari_core::{
consensus::ConsensusManager,
proto::base_node as base_node_proto,
transactions::{
key_manager::TransactionKeyManagerInterface,
transaction_protocol::proto::protocol as proto,
CryptoFactories,
},
transactions::{key_manager::TransactionKeyManagerInterface, CryptoFactories},
};
use tari_network::identity;
use tari_p2p::{
comms_connector::SubscriptionFactory,
message::{DomainMessage, TariMessageType},
services::utils::map_decode,
tari_message::TariMessageType,
proto::{base_node as base_node_proto, transaction_protocol as proto},
Dispatcher,
};
use tari_service_framework::{
Expand Down
Loading

0 comments on commit 924e1b5

Please sign in to comment.