Skip to content

Commit

Permalink
feat: adds settings JSON-RPC call to allow changes to indexer URL (#744)
Browse files Browse the repository at this point in the history
Description
---
Add new jrpc calls that will allow change of the indexer jrpc url in the
wallet daemon.

Motivation and Context
---

How Has This Been Tested?
---
as below

What process can a PR reviewer use to test or verify this change?
---
Run dan-testing with 2 indexers. And call the jrpc method to change it.
And e.g. send money using the new indexer. Then you should clearly see
in the logs which one was used.


Breaking Changes
---

- [x] None
- [ ] Requires data directory to be deleted
- [ ] Other - Please specify
  • Loading branch information
Cifko authored Nov 1, 2023
1 parent d337cfe commit 51d6aab
Show file tree
Hide file tree
Showing 14 changed files with 159 additions and 93 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.

1 change: 1 addition & 0 deletions applications/tari_dan_wallet_daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ webrtc = "0.7.1"
libsqlite3-sys = { version = "0.25", features = ["bundled"] }
log4rs = { version = "1.1.1", features = ["rolling_file_appender", "compound_policy", "size_trigger", "fixed_window_roller", "console_appender"] }
mime_guess = "2.0.4"
url = "2.4.1"

[dev-dependencies]
tari_utilities = "0.4.10"
Expand Down
1 change: 1 addition & 0 deletions applications/tari_dan_wallet_daemon/src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod helpers;
pub mod keys;
pub mod nfts;
pub mod rpc;
pub mod settings;
pub mod transaction;
pub mod validator;
pub mod webrtc;
Expand Down
39 changes: 39 additions & 0 deletions applications/tari_dan_wallet_daemon/src/handlers/settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright 2023 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use tari_dan_common_types::optional::Optional;
use tari_dan_wallet_sdk::{
apis::{config::ConfigKey, jwt::JrpcPermission},
network::WalletNetworkInterface,
};
use tari_wallet_daemon_client::types::{SettingsGetResponse, SettingsSetRequest, SettingsSetResponse};

use crate::handlers::HandlerContext;

pub async fn handle_get(
context: &HandlerContext,
token: Option<String>,
_value: serde_json::Value,
) -> Result<SettingsGetResponse, anyhow::Error> {
let sdk = context.wallet_sdk().clone();
sdk.jwt_api().check_auth(token, &[JrpcPermission::Admin])?;
let indexer_url = if let Some(indexer_url) = sdk.config_api().get(ConfigKey::IndexerUrl).optional()? {
indexer_url
} else {
sdk.get_config().indexer_jrpc_endpoint.clone()
};

Ok(SettingsGetResponse { indexer_url })
}

pub async fn handle_set(
context: &HandlerContext,
token: Option<String>,
req: SettingsSetRequest,
) -> Result<SettingsSetResponse, anyhow::Error> {
let mut sdk = context.wallet_sdk().clone();
sdk.jwt_api().check_auth(token, &[JrpcPermission::Admin])?;
sdk.get_network_interface().set_endpoint(&req.indexer_url)?;
sdk.config_api().set(ConfigKey::IndexerUrl, &req.indexer_url, false)?;
Ok(SettingsSetResponse {})
}
23 changes: 18 additions & 5 deletions applications/tari_dan_wallet_daemon/src/indexer_jrpc_impl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright 2023 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use std::sync::{Arc, Mutex};

use axum::async_trait;
use reqwest::{IntoUrl, Url};
use tari_dan_common_types::optional::IsNotFoundError;
Expand All @@ -22,23 +24,26 @@ use tari_indexer_client::{
},
};
use tari_transaction::{SubstateRequirement, Transaction, TransactionId};
use url::ParseError;

#[derive(Debug, Clone)]
pub struct IndexerJsonRpcNetworkInterface {
indexer_jrpc_address: Url,
indexer_jrpc_address: Arc<Mutex<Url>>,
}

impl IndexerJsonRpcNetworkInterface {
pub fn new<T: IntoUrl>(indexer_jrpc_address: T) -> Self {
Self {
indexer_jrpc_address: indexer_jrpc_address
.into_url()
.expect("Malformed indexer JSON-RPC address"),
indexer_jrpc_address: Arc::new(Mutex::new(
indexer_jrpc_address
.into_url()
.expect("Malformed indexer JSON-RPC address"),
)),
}
}

fn get_client(&self) -> Result<IndexerJsonRpcClient, IndexerJrpcError> {
let client = IndexerJsonRpcClient::connect(self.indexer_jrpc_address.clone())?;
let client = IndexerJsonRpcClient::connect((*self.indexer_jrpc_address.lock().unwrap()).clone())?;
Ok(client)
}
}
Expand Down Expand Up @@ -119,18 +124,26 @@ impl WalletNetworkInterface for IndexerJsonRpcNetworkInterface {
result: convert_indexer_result_to_wallet_result(resp.result),
})
}

fn set_endpoint(&mut self, endpoint: &str) -> Result<(), Self::Error> {
*self.indexer_jrpc_address.lock().unwrap() = Url::parse(endpoint)?;
Ok(())
}
}

#[derive(Debug, thiserror::Error)]
pub enum IndexerJrpcError {
#[error("Indexer client error: {0}")]
IndexerClientError(#[from] IndexerClientError),
#[error("Indexer parse error : {0}")]
IndexerParseError(#[from] ParseError),
}

impl IsNotFoundError for IndexerJrpcError {
fn is_not_found_error(&self) -> bool {
match self {
IndexerJrpcError::IndexerClientError(err) => err.is_not_found_error(),
_ => false,
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions applications/tari_dan_wallet_daemon/src/jrpc_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use crate::handlers::{
keys,
nfts,
rpc,
settings,
transaction,
validator,
webrtc,
Expand Down Expand Up @@ -101,6 +102,11 @@ async fn handler(
"get_all_jwt" => call_handler(context, value, token, rpc::handle_get_all_jwt).await,
_ => Ok(value.method_not_found(&value.method)),
},
Some(("settings", method)) => match method {
"get" => call_handler(context, value, token, settings::handle_get).await,
"set" => call_handler(context, value, token, settings::handle_set).await,
_ => Ok(value.method_not_found(&value.method)),
},
Some(("webrtc", "start")) => webrtc::handle_start(context, value, token, shutdown_signal, addresses),
Some(("rpc", "discover")) => call_handler(context, value, token, rpc::handle_discover).await,
Some(("keys", method)) => match method {
Expand Down
18 changes: 16 additions & 2 deletions applications/tari_dan_wallet_daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,15 @@ mod webrtc;
use std::{fs, panic, process};

use log::*;
use tari_dan_wallet_sdk::{apis::key_manager, DanWalletSdk, WalletSdkConfig};
use tari_dan_common_types::optional::Optional;
use tari_dan_wallet_sdk::{
apis::{
config::{ConfigApi, ConfigKey},
key_manager,
},
DanWalletSdk,
WalletSdkConfig,
};
use tari_dan_wallet_storage_sqlite::SqliteWalletStore;
use tari_shutdown::ShutdownSignal;
use tari_template_lib::models::Amount;
Expand Down Expand Up @@ -69,7 +77,13 @@ pub async fn run_tari_dan_wallet_daemon(
jwt_expiry: config.dan_wallet_daemon.jwt_expiry.unwrap(),
jwt_secret_key: config.dan_wallet_daemon.jwt_secret_key.unwrap(),
};
let indexer = IndexerJsonRpcNetworkInterface::new(&sdk_config.indexer_jrpc_endpoint);
let config_api = ConfigApi::new(&store);
let indexer_jrpc_endpoint = if let Some(indexer_url) = config_api.get(ConfigKey::IndexerUrl).optional()? {
indexer_url
} else {
sdk_config.indexer_jrpc_endpoint.clone()
};
let indexer = IndexerJsonRpcNetworkInterface::new(indexer_jrpc_endpoint);
let wallet_sdk = DanWalletSdk::initialize(store, indexer, sdk_config)?;
wallet_sdk
.key_manager_api()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { useTheme } from '@mui/material/styles';
import { useAccountsCreateFreeTestCoins } from '../../../api/hooks/useAccounts';
import ClaimBurn from './ClaimBurn';
import useAccountStore from '../../../store/accountStore';
import SendMoney from './SendMoney';

function ActionMenu() {
const { mutate } = useAccountsCreateFreeTestCoins();
Expand All @@ -48,6 +49,7 @@ function ActionMenu() {
marginBottom: theme.spacing(2),
}}
>
<SendMoney/>
<Button variant="outlined" onClick={onClaimFreeCoins}>
Claim Free Testnet Coins
</Button>
Expand Down
Loading

0 comments on commit 51d6aab

Please sign in to comment.