Skip to content

Commit 2fb204b

Browse files
committed
provider: don't use providerAccounts
This relied on calling payment init, which is obsolete. The new solution is to get the default identity and allow for specifying the complete platform instead of just the network.
1 parent fe776bb commit 2fb204b

File tree

6 files changed

+96
-82
lines changed

6 files changed

+96
-82
lines changed

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -280,9 +280,9 @@ ya-service-api-interfaces = { path = "core/serv-api/interfaces" }
280280
ya-service-api-web = { path = "core/serv-api/web" }
281281

282282
## CLIENT
283-
ya-client = { git = "https://github.com/golemfactory/ya-client.git", rev = "b60640065835a1fc8eb33d2fb174ec6c0e4b30c4" }
283+
ya-client = { git = "https://github.com/golemfactory/ya-client.git", rev = "e3113709178fa31fc144e79a835c06afcc6f8a34" }
284284
#ya-client = { path = "../ya-client" }
285-
ya-client-model = { git = "https://github.com/golemfactory/ya-client.git", rev = "b60640065835a1fc8eb33d2fb174ec6c0e4b30c4" }
285+
ya-client-model = { git = "https://github.com/golemfactory/ya-client.git", rev = "e3113709178fa31fc144e79a835c06afcc6f8a34" }
286286
#ya-client-model = "0.7"
287287
golem-certificate = { git = "https://github.com/golemfactory/golem-certificate.git", rev = "f2d7514c18fc066e9cfb796090b90f5b27cfe1c6" }
288288

agent/provider/src/provider_agent.rs

+23-61
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use actix::prelude::*;
22
use anyhow::{anyhow, Error};
33
use futures::{FutureExt, StreamExt, TryFutureExt};
44
use ya_client::net::NetApi;
5+
use ya_core_model::NodeId;
56

67
use std::convert::TryFrom;
78
use std::path::{Path, PathBuf};
@@ -28,7 +29,9 @@ use crate::market::provider_market::{OfferKind, Shutdown as MarketShutdown, Unsu
2829
use crate::market::{CreateOffer, Preset, PresetManager, ProviderMarket};
2930
use crate::payments::{AccountView, LinearPricingOffer, Payments, PricingOffer};
3031
use crate::rules::RulesManager;
31-
use crate::startup_config::{FileMonitor, NodeConfig, ProviderConfig, RunConfig};
32+
use crate::startup_config::{
33+
FileMonitor, PaymentPlatform, NodeConfig, ProviderConfig, RunConfig,
34+
};
3235
use crate::tasks::task_manager::{InitializeTaskManager, TaskManager};
3336

3437
struct GlobalsManager {
@@ -77,9 +80,9 @@ pub struct ProviderAgent {
7780
task_manager: Addr<TaskManager>,
7881
presets: PresetManager,
7982
hardware: hardware::Manager,
80-
accounts: Vec<AccountView>,
83+
account: NodeId,
8184
log_handler: LoggerHandle,
82-
networks: Vec<NetworkName>,
85+
networks: Vec<PaymentPlatform>,
8386
rulestore_monitor: FileMonitor,
8487
keystore_monitor: FileMonitor,
8588
whitelist_monitor: FileMonitor,
@@ -116,14 +119,8 @@ impl ProviderAgent {
116119
let api = ProviderApi::try_from(&args.api)?;
117120

118121
log::info!("Loading payment accounts...");
119-
let accounts: Vec<AccountView> = api
120-
.payment
121-
.get_provider_accounts()
122-
.await?
123-
.into_iter()
124-
.map(Into::into)
125-
.collect();
126-
log::info!("Payment accounts: {:#?}", accounts);
122+
let account = api.identity.me().await?.identity;
123+
log::info!("Payment account: {:#?}", account);
127124
let registry = config.registry()?;
128125
registry.validate()?;
129126
registry.test_runtimes(&data_dir).await?;
@@ -149,7 +146,7 @@ impl ProviderAgent {
149146

150147
let networks = args.node.account.networks.clone();
151148
for n in networks.iter() {
152-
let net_color = match n {
149+
let net_color = match n.network {
153150
NetworkName::Mainnet => yansi::Color::Magenta,
154151
NetworkName::Polygon => yansi::Color::Magenta,
155152
NetworkName::Rinkeby => yansi::Color::Cyan,
@@ -158,7 +155,7 @@ impl ProviderAgent {
158155
NetworkName::Holesky => yansi::Color::Cyan,
159156
_ => yansi::Color::Red,
160157
};
161-
log::info!("Using payment network: {}", net_color.paint(&n));
158+
log::info!("Using payment network: {}", net_color.paint(&n.network));
162159
}
163160

164161
let mut globals = GlobalsManager::try_new(&config.globals_file, args.node)?;
@@ -186,7 +183,7 @@ impl ProviderAgent {
186183
task_manager,
187184
presets,
188185
hardware,
189-
accounts,
186+
account,
190187
log_handler,
191188
networks,
192189
rulestore_monitor,
@@ -317,56 +314,21 @@ impl ProviderAgent {
317314
.support_multi_activity(true))
318315
}
319316

320-
fn accounts(&self, networks: &Vec<NetworkName>) -> anyhow::Result<Vec<AccountView>> {
317+
fn accounts(&self, networks: &Vec<PaymentPlatform>) -> anyhow::Result<Vec<AccountView>> {
321318
let globals = self.globals.get_state();
322-
if let Some(address) = &globals.account {
323-
log::info!(
324-
"Filtering payment accounts by address={} and networks={:?}",
325-
address,
326-
networks,
327-
);
328-
let accounts: Vec<AccountView> = self
329-
.accounts
330-
.iter()
331-
.filter(|acc| &acc.address == address && networks.contains(&acc.network))
332-
.cloned()
333-
.collect();
334-
335-
if accounts.is_empty() {
336-
anyhow::bail!(
337-
"Payment account {} not initialized. Please run\n\
338-
\t`yagna payment init --receiver --network {} --account {}`\n\
339-
for all drivers you want to use.",
340-
address,
341-
networks[0],
342-
address,
343-
)
344-
}
345319

346-
Ok(accounts)
347-
} else {
348-
log::debug!("Filtering payment accounts by networks={:?}", networks);
349-
let accounts: Vec<AccountView> = self
350-
.accounts
351-
.iter()
352-
// FIXME: this is dirty fix -- we can get more that one address from this filter
353-
// FIXME: use /me endpoint and filter out only accounts bound to given app-key
354-
// FIXME: or introduce param to getProviderAccounts to filter out external account above
355-
.filter(|acc| networks.contains(&acc.network))
356-
.cloned()
357-
.collect();
358-
359-
if accounts.is_empty() {
360-
anyhow::bail!(
361-
"Default payment account not initialized. Please run\n\
362-
\t`yagna payment init --receiver --network {}`\n\
363-
for all drivers you want to use.",
364-
networks[0],
365-
)
366-
}
320+
let account = globals.account.unwrap_or(self.account);
367321

368-
Ok(accounts)
369-
}
322+
let accounts: Vec<_> = networks
323+
.iter()
324+
.map(|network| AccountView {
325+
address: account,
326+
network: network.network.clone(),
327+
platform: network.platform(),
328+
})
329+
.collect();
330+
331+
Ok(accounts)
370332
}
371333
}
372334

agent/provider/src/startup_config.rs

+65-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1+
use std::convert::TryInto;
12
use std::env;
23
use std::error::Error;
34
use std::path::{Path, PathBuf};
5+
use std::str::FromStr;
46
use std::sync::mpsc;
57
use std::time::Duration;
68

79
use directories::UserDirs;
810
use futures::channel::oneshot;
911
use notify::*;
10-
use serde::{Deserialize, Serialize};
1112
use structopt::{clap, StructOpt};
1213
use strum::VariantNames;
1314
use ya_client::{cli::ApiOpts, model::node_id::NodeId};
1415

15-
use ya_core_model::payment::local::NetworkName;
16+
use ya_core_model::payment::local::{DriverName, NetworkName, DEFAULT_PAYMENT_DRIVER};
1617
use ya_utils_path::data_dir::DataDir;
1718

1819
use crate::cli::clean::CleanConfig;
@@ -142,7 +143,61 @@ impl ProviderConfig {
142143
}
143144
}
144145

145-
#[derive(StructOpt, Clone, Debug, Serialize, Deserialize, derive_more::Display)]
146+
#[derive(Clone, Debug)]
147+
pub struct PaymentPlatform {
148+
pub driver: String,
149+
pub network: NetworkName,
150+
}
151+
152+
impl PaymentPlatform {
153+
pub fn platform(&self) -> String {
154+
format!(
155+
"{}-{}-{}",
156+
self.driver,
157+
self.network,
158+
self.network.get_token()
159+
)
160+
.to_lowercase()
161+
}
162+
}
163+
164+
impl FromStr for PaymentPlatform {
165+
type Err = String;
166+
167+
fn from_str(arg: &str) -> std::result::Result<Self, Self::Err> {
168+
let value = if let Ok(network_name) = NetworkName::from_str(arg) {
169+
PaymentPlatform {
170+
driver: DEFAULT_PAYMENT_DRIVER.to_string(),
171+
network: network_name,
172+
}
173+
} else {
174+
let err = "Not a valid network or a platform";
175+
176+
let parts: [&str; 3] = arg
177+
.split("-")
178+
.collect::<Vec<_>>()
179+
.try_into()
180+
.map_err(|_| err.to_string())?;
181+
182+
if !DriverName::VARIANTS.contains(&parts[0]) {
183+
return Err(err.to_string());
184+
}
185+
let network_name = NetworkName::from_str(&parts[1]).map_err(|_| err.to_string())?;
186+
if parts[2] != network_name.get_token() {
187+
return Err(err.to_string());
188+
}
189+
190+
PaymentPlatform {
191+
driver: parts[0].to_string(),
192+
network: network_name,
193+
}
194+
};
195+
196+
Ok(value)
197+
}
198+
}
199+
200+
#[derive(StructOpt, Clone, Debug, derive_more::Display)]
146201
#[display(
147202
fmt = "{}Networks: {:?}",
148203
"account.map(|a| format!(\"Address: {}\n\", a)).unwrap_or_else(|| \"\".into())",
@@ -153,8 +208,13 @@ pub struct ReceiverAccount {
153208
#[structopt(long, env = "YA_ACCOUNT")]
154209
pub account: Option<NodeId>,
155210
/// Payment network.
156-
#[structopt(long = "payment-network", env = "YA_PAYMENT_NETWORK", possible_values = NetworkName::VARIANTS, default_value = NetworkName::Mainnet.into())]
157-
pub networks: Vec<NetworkName>,
211+
#[structopt(
212+
long = "payment-network",
213+
env = "YA_PAYMENT_NETWORK",
214+
default_value = NetworkName::Mainnet.into(),
215+
help = "Specify platforms to collect funds, e.g. erc20-mainnet-glm. Network name can be passed as well, in which case the default driver will be used"
216+
)]
217+
pub networks: Vec<PaymentPlatform>,
158218
}
159219

160220
#[derive(StructOpt, Clone, Debug)]

core/model/src/payment.rs

+6
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,12 @@ pub mod local {
570570
Mumbai,
571571
}
572572

573+
impl NetworkName {
574+
pub fn get_token(&self) -> &'static str {
575+
get_token_from_network_name(self)
576+
}
577+
}
578+
573579
pub fn get_token_from_network_name(network_name: &NetworkName) -> &'static str {
574580
network_name
575581
.get_str("token")

core/serv-api/web/src/middleware/auth/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ where
8787
// TODO: remove this hack; possibly by enabling creation of arbitrary appkey from CLI
8888
if req.uri().to_string().starts_with("/metrics-api")
8989
|| req.uri().to_string().starts_with("/version")
90-
|| req.uri().to_string().starts_with("/default-identity")
9190
{
9291
log::debug!("skipping authorization for uri={}", req.uri());
9392
return Box::pin(service.borrow_mut().call(req));

core/serv/src/main.rs

-13
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use actix_web::{middleware, web, App, HttpServer, Responder};
44
use anyhow::{Context, Result};
55
use futures::prelude::*;
66
use metrics::{counter, gauge};
7-
use ya_core_model::identity;
87
#[cfg(feature = "static-openssl")]
98
extern crate openssl_probe;
109

@@ -569,7 +568,6 @@ impl ServiceCommand {
569568
.wrap(auth::Auth::new(cors.cache()))
570569
.wrap(cors.cors())
571570
.route("/me", web::get().to(me))
572-
.route("/default-identity", web::get().to(default_identity))
573571
.service(forward_gsb);
574572
let rest = Services::rest(app, &context);
575573
if count_started.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
@@ -684,17 +682,6 @@ async fn me(id: Identity) -> impl Responder {
684682
web::Json(id)
685683
}
686684

687-
async fn default_identity() -> impl Responder {
688-
let id = ya_service_bus::typed::service(identity::BUS_ID)
689-
.call(identity::Get::ByDefault)
690-
.await
691-
.map_err(actix_web::error::ErrorInternalServerError)?
692-
.map_err(actix_web::error::ErrorInternalServerError)?
693-
.unwrap();
694-
695-
Ok::<_, actix_web::Error>(web::Json(id.node_id))
696-
}
697-
698685
#[actix_web::post("/_gsb/{service:.*}")]
699686
async fn forward_gsb(
700687
id: Identity,

0 commit comments

Comments
 (0)