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

Read version info from server, react accordingly #154

Merged
merged 8 commits into from
Jun 18, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
168 changes: 90 additions & 78 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ failure_derive = "0.1"
prettytable-rs = "0.7"
log = "0.4"
linefeed = "0.5"
semver = "0.9"

grin_wallet_api = { path = "./api", version = "2.0.0-beta.1" }
grin_wallet_impls = { path = "./impls", version = "2.0.0-beta.1" }
Expand Down
46 changes: 38 additions & 8 deletions api/src/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,16 @@

use crate::keychain::Keychain;
use crate::libwallet::api_impl::foreign;
use crate::libwallet::{BlockFees, CbData, Error, NodeClient, Slate, VersionInfo, WalletBackend};
use crate::libwallet::{
BlockFees, CbData, Error, NodeClient, NodeVersionInfo, Slate, VersionInfo, WalletBackend,
};
use crate::util::Mutex;
use std::marker::PhantomData;
use std::sync::Arc;

/// ForeignAPI Middleware Check callback
pub type ForeignCheckMiddleware = fn(Option<NodeVersionInfo>, Option<&Slate>) -> Result<(), Error>;

/// Main interface into all wallet API functions.
/// Wallet APIs are split into two seperate blocks of functionality
/// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs
Expand All @@ -46,8 +51,12 @@ where
pub wallet: Arc<Mutex<W>>,
/// Flag to normalize some output during testing. Can mostly be ignored.
pub doctest_mode: bool,
/// phantom
phantom: PhantomData<K>,
/// phantom
phantom_c: PhantomData<C>,
/// foreign check middleware
middleware: Option<ForeignCheckMiddleware>,
}

impl<'a, W: ?Sized, C, K> Foreign<W, C, K>
Expand All @@ -67,6 +76,8 @@ where
/// # Arguments
/// * `wallet_in` - A reference-counted mutex containing an implementation of the
/// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait.
/// * middleware - Option middleware which containts the NodeVersionInfo and can call
/// a predefined function with the slate to check if the operation should continue
///
/// # Returns
/// * An instance of the ForeignApi holding a reference to the provided wallet
Expand Down Expand Up @@ -109,17 +120,18 @@ where
/// LMDBBackend::new(wallet_config.clone(), "", node_client).unwrap()
/// ));
///
/// let api_owner = Foreign::new(wallet.clone());
/// let api_foreign = Foreign::new(wallet.clone(), None);
/// // .. perform wallet operations
///
/// ```

pub fn new(wallet_in: Arc<Mutex<W>>) -> Self {
pub fn new(wallet_in: Arc<Mutex<W>>, middleware: Option<ForeignCheckMiddleware>) -> Self {
Foreign {
wallet: wallet_in,
doctest_mode: false,
phantom: PhantomData,
phantom_c: PhantomData,
middleware,
}
}

Expand All @@ -133,13 +145,17 @@ where
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_foreign = Foreign::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone(), None);
///
/// let version_info = api_foreign.check_version();
/// // check and proceed accordingly
/// ```

pub fn check_version(&self) -> Result<VersionInfo, Error> {
if let Some(m) = self.middleware.as_ref() {
let mut w = self.wallet.lock();
m(w.w2n_client().get_version_info(), None)?;
}
Ok(foreign::check_version())
}

Expand Down Expand Up @@ -176,7 +192,7 @@ where
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_foreign = Foreign::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone(), None);
///
/// let block_fees = BlockFees {
/// fees: 800000,
Expand All @@ -195,6 +211,9 @@ where

pub fn build_coinbase(&self, block_fees: &BlockFees) -> Result<CbData, Error> {
let mut w = self.wallet.lock();
if let Some(m) = self.middleware.as_ref() {
m(w.w2n_client().get_version_info(), None)?;
}
w.open_with_credentials()?;
let res = foreign::build_coinbase(&mut *w, block_fees, self.doctest_mode);
w.close()?;
Expand Down Expand Up @@ -222,7 +241,7 @@ where
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_foreign = Foreign::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone(), None);
///
/// # let slate = Slate::blank(2);
/// // Receive a slate via some means
Expand All @@ -240,6 +259,10 @@ where
/// ```

pub fn verify_slate_messages(&self, slate: &Slate) -> Result<(), Error> {
if let Some(m) = self.middleware.as_ref() {
let mut w = self.wallet.lock();
m(w.w2n_client().get_version_info(), None)?;
}
foreign::verify_slate_messages(slate)
}

Expand Down Expand Up @@ -286,7 +309,7 @@ where
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_foreign = Foreign::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone(), None);
/// # let slate = Slate::blank(2);
///
/// // . . .
Expand All @@ -306,6 +329,9 @@ where
message: Option<String>,
) -> Result<Slate, Error> {
let mut w = self.wallet.lock();
if let Some(m) = self.middleware.as_ref() {
m(w.w2n_client().get_version_info(), None)?;
}
w.open_with_credentials()?;
let res = foreign::receive_tx(&mut *w, slate, dest_acct_name, message, self.doctest_mode);
w.close()?;
Expand Down Expand Up @@ -340,7 +366,7 @@ where
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_owner = Owner::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone());
/// let mut api_foreign = Foreign::new(wallet.clone(), None);
///
/// // . . .
/// // Issue the invoice tx via the owner API
Expand All @@ -360,6 +386,10 @@ where
/// ```

pub fn finalize_invoice_tx(&self, slate: &Slate) -> Result<Slate, Error> {
let mut w = self.wallet.lock();
if let Some(m) = self.middleware.as_ref() {
m(w.w2n_client().get_version_info(), None)?;
}
let mut w = self.wallet.lock();
w.open_with_credentials()?;
let res = foreign::finalize_invoice_tx(&mut *w, slate);
Expand Down
17 changes: 13 additions & 4 deletions api/src/foreign_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

use crate::keychain::Keychain;
use crate::libwallet::{
BlockFees, CbData, ErrorKind, InitTxArgs, IssueInvoiceTxArgs, NodeClient, Slate, VersionInfo,
VersionedSlate, WalletBackend,
self, BlockFees, CbData, ErrorKind, InitTxArgs, IssueInvoiceTxArgs, NodeClient,
NodeVersionInfo, Slate, VersionInfo, VersionedSlate, WalletBackend,
};
use crate::Foreign;
use easy_jsonrpc;
Expand Down Expand Up @@ -557,6 +557,15 @@ where
}
}

fn test_check_middleware(
_node_version_info: Option<NodeVersionInfo>,
_slate: Option<&Slate>,
) -> Result<(), libwallet::Error> {
// TODO: Implement checks
// return Err(ErrorKind::GenericError("Test Rejection".into()))?
Ok(())
}

/// helper to set up a real environment to run integrated doctests
pub fn run_doctest_foreign(
request: serde_json::Value,
Expand Down Expand Up @@ -675,8 +684,8 @@ pub fn run_doctest_foreign(
}

let mut api_foreign = match init_invoice_tx {
false => Foreign::new(wallet1.clone()),
true => Foreign::new(wallet2.clone()),
false => Foreign::new(wallet1.clone(), Some(test_check_middleware)),
true => Foreign::new(wallet2.clone(), Some(test_check_middleware)),
};
api_foreign.doctest_mode = true;
let foreign_api = &api_foreign as &dyn ForeignRpc;
Expand Down
2 changes: 1 addition & 1 deletion api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ mod foreign;
mod foreign_rpc;
mod owner;
mod owner_rpc;
pub use crate::foreign::Foreign;
pub use crate::foreign::{Foreign, ForeignCheckMiddleware};
pub use crate::foreign_rpc::ForeignRpc;
pub use crate::owner::Owner;
pub use crate::owner_rpc::OwnerRpc;
Expand Down
14 changes: 11 additions & 3 deletions controller/src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! invocations) as needed.
use crate::api::{self, ApiServer, BasicAuthMiddleware, ResponseFuture, Router, TLSConfig};
use crate::keychain::Keychain;
use crate::libwallet::{Error, ErrorKind, NodeClient, WalletBackend};
use crate::libwallet::{Error, ErrorKind, NodeClient, NodeVersionInfo, Slate, WalletBackend};
use crate::util::to_base64;
use crate::util::Mutex;
use failure::ResultExt;
Expand All @@ -39,6 +39,14 @@ lazy_static! {
HeaderValue::from_str("Basic realm=GrinOwnerAPI").unwrap();
}

fn check_middleware(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Middleware goes here (may have to redefine the middleware call to pass in the name of the function as well)

_node_version_info: Option<NodeVersionInfo>,
_slate: Option<&Slate>,
) -> Result<(), Error> {
// TODO: Implement checks
Ok(())
}

/// Instantiate wallet Owner API for a single-use (command line) call
/// Return a function containing a loaded API context to call
pub fn owner_single_use<F, T: ?Sized, C, K>(wallet: Arc<Mutex<T>>, f: F) -> Result<(), Error>
Expand All @@ -61,7 +69,7 @@ where
C: NodeClient,
K: Keychain,
{
f(&mut Foreign::new(wallet.clone()))?;
f(&mut Foreign::new(wallet.clone(), Some(check_middleware)))?;
Ok(())
}

Expand Down Expand Up @@ -279,7 +287,7 @@ where
}

fn handle_post_request(&self, req: Request<Body>) -> WalletResponseFuture {
let api = Foreign::new(self.wallet.clone());
let api = Foreign::new(self.wallet.clone(), Some(check_middleware));
Box::new(
self.call_api(req, api)
.and_then(|resp| ok(json_response_pretty(&resp))),
Expand Down
37 changes: 34 additions & 3 deletions impls/src/node_clients/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

use futures::{stream, Stream};

use crate::libwallet::{NodeClient, TxWrapper};
use crate::libwallet::{NodeClient, NodeVersionInfo, TxWrapper};
use std::collections::HashMap;
use tokio::runtime::Runtime;

Expand All @@ -30,6 +30,7 @@ use crate::util::secp::pedersen;
pub struct HTTPNodeClient {
node_url: String,
node_api_secret: Option<String>,
node_version_info: Option<NodeVersionInfo>,
}

impl HTTPNodeClient {
Expand All @@ -38,6 +39,7 @@ impl HTTPNodeClient {
HTTPNodeClient {
node_url: node_url.to_owned(),
node_api_secret: node_api_secret,
node_version_info: None,
}
}

Expand All @@ -63,14 +65,43 @@ impl NodeClient for HTTPNodeClient {
self.node_api_secret = node_api_secret;
}

fn get_version_info(&mut self) -> Option<NodeVersionInfo> {
if let Some(v) = self.node_version_info.as_ref() {
return Some(v.clone());
}
let url = format!("{}/v1/version", self.node_url());
let mut retval =
match api::client::get::<NodeVersionInfo>(url.as_str(), self.node_api_secret()) {
Ok(n) => n,
Err(e) => {
// If node isn't available, allow offline functions
// unfortunately have to parse string due to error structure
let err_string = format!("{}", e);
if err_string.contains("404") {
return Some(NodeVersionInfo {
node_version: "1.0.0".into(),
block_header_version: 1,
verified: Some(false),
});
} else {
error!("Unable to contact Node to get version info: {}", e);
return None;
}
}
};
retval.verified = Some(true);
self.node_version_info = Some(retval.clone());
Some(retval)
}

/// Posts a transaction to a grin node
fn post_tx(&self, tx: &TxWrapper, fluff: bool) -> Result<(), libwallet::Error> {
let url;
let dest = self.node_url();
if fluff {
url = format!("{}/v1/pool/push?fluff", dest);
url = format!("{}/v1/pool/push_tx?fluff", dest);
} else {
url = format!("{}/v1/pool/push", dest);
url = format!("{}/v1/pool/push_tx", dest);
}
let res = api::client::post_no_ret(url.as_str(), self.node_api_secret(), tx);
if let Err(e) = res {
Expand Down
5 changes: 4 additions & 1 deletion impls/src/test_framework/testclient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::core::global::{set_mining_mode, ChainTypes};
use crate::core::{pow, ser};
use crate::keychain::Keychain;
use crate::libwallet::api_impl::foreign;
use crate::libwallet::{NodeClient, Slate, TxWrapper, WalletInst};
use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, TxWrapper, WalletInst};
use crate::util;
use crate::util::secp::pedersen;
use crate::util::secp::pedersen::Commitment;
Expand Down Expand Up @@ -402,6 +402,9 @@ impl NodeClient for LocalWalletClient {
}
fn set_node_url(&mut self, _node_url: &str) {}
fn set_node_api_secret(&mut self, _node_api_secret: Option<String>) {}
fn get_version_info(&mut self) -> Option<NodeVersionInfo> {
None
}
/// Posts a transaction to a grin node
/// In this case it will create a new block with award rewarded to
fn post_tx(&self, tx: &TxWrapper, _fluff: bool) -> Result<(), libwallet::Error> {
Expand Down
5 changes: 3 additions & 2 deletions libwallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub use api_impl::types::{
};
pub use internal::restore::{check_repair, restore};
pub use types::{
AcctPathMapping, BlockIdentifier, Context, NodeClient, OutputData, OutputStatus, TxLogEntry,
TxLogEntryType, TxWrapper, WalletBackend, WalletInfo, WalletInst, WalletOutputBatch,
AcctPathMapping, BlockIdentifier, Context, NodeClient, NodeVersionInfo, OutputData,
OutputStatus, TxLogEntry, TxLogEntryType, TxWrapper, WalletBackend, WalletInfo, WalletInst,
WalletOutputBatch,
};
15 changes: 15 additions & 0 deletions libwallet/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ pub trait NodeClient: Sync + Send + Clone {
/// Posts a transaction to a grin node
fn post_tx(&self, tx: &TxWrapper, fluff: bool) -> Result<(), Error>;

/// Returns the api version string and block header version as reported
/// by the node. Result can be cached for later use
fn get_version_info(&mut self) -> Option<NodeVersionInfo>;

/// retrieves the current tip from the specified grin node
fn get_chain_height(&self) -> Result<u64, Error>;

Expand Down Expand Up @@ -250,6 +254,17 @@ pub trait NodeClient: Sync + Send + Clone {
>;
}

/// Node version info
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeVersionInfo {
/// Semver version string
pub node_version: String,
/// block header verson
pub block_header_version: u16,
/// Whether this version info was successfully verified from a node
pub verified: Option<bool>,
}

/// Information about an output that's being tracked by the wallet. Must be
/// enough to reconstruct the commitment associated with the ouput when the
/// root private key is known.
Expand Down
Loading