Add check_version function to Foreign API (#87)

* move api deser types into separate types mod

* rustfmt

* missing types file

* make all exports from libwallet more explicit

* rustfmt

* add version check function to foreign api

* rustfmt

* change check_version return value to result, for consistency
This commit is contained in:
Yeastplume 2019-04-24 09:27:14 +01:00 committed by GitHub
parent bff07eb3f5
commit d774272fee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
36 changed files with 342 additions and 256 deletions

View file

@ -16,9 +16,7 @@
use crate::keychain::Keychain;
use crate::libwallet::api_impl::foreign;
use crate::libwallet::slate::Slate;
use crate::libwallet::types::{BlockFees, CbData, NodeClient, WalletBackend};
use crate::libwallet::Error;
use crate::libwallet::{BlockFees, CbData, Error, NodeClient, Slate, VersionInfo, WalletBackend};
use crate::util::Mutex;
use std::marker::PhantomData;
use std::sync::Arc;
@ -91,7 +89,7 @@ where
/// use api::Foreign;
/// use config::WalletConfig;
/// use impls::{HTTPNodeClient, LMDBBackend};
/// use libwallet::types::WalletBackend;
/// use libwallet::WalletBackend;
///
/// let mut wallet_config = WalletConfig::default();
/// # let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
@ -125,6 +123,26 @@ where
}
}
/// Return the version capabilities of the running ForeignApi Node
/// # Arguments
/// None
/// # Returns
/// * [`VersionInfo`](../grin_wallet_libwallet/api_impl/types/struct.VersionInfo.html)
/// # Example
/// Set up as in [`new`](struct.Foreign.html#method.new) method above.
/// ```
/// # grin_wallet_api::doctest_helper_setup_doc_env_foreign!(wallet, wallet_config);
///
/// let mut api_foreign = Foreign::new(wallet.clone());
///
/// let version_info = api_foreign.check_version();
/// // check and proceed accordingly
/// ```
pub fn check_version(&self) -> Result<VersionInfo, Error> {
Ok(foreign::check_version())
}
/// Builds a new unconfirmed coinbase output in the wallet, generally for inclusion in a
/// potential new block's coinbase output during mining.
///
@ -136,7 +154,7 @@ where
///
/// # Arguments
///
/// * `block_fees` - A [`BlockFees`](../grin_wallet_libwallet/types/struct.BlockFees.html)
/// * `block_fees` - A [`BlockFees`](../grin_wallet_libwallet/api_impl/types/struct.BlockFees.html)
/// struct, set up as follows:
///
/// `fees` - should contain the sum of all transaction fees included in the potential
@ -149,7 +167,7 @@ where
/// id will be assigned
///
/// # Returns
/// * `Ok`([`cb_data`](../grin_wallet_libwallet/types/struct.CbData.html)`)` if successful. This
/// * `Ok`([`cb_data`](../grin_wallet_libwallet/api_impl/types/struct.CbData.html)`)` if successful. This
/// will contain the corresponding output, kernel and keyID used to create the coinbase output.
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered.
///
@ -305,7 +323,6 @@ macro_rules! doctest_helper_setup_doc_env_foreign {
use grin_wallet_libwallet as libwallet;
use grin_wallet_util::grin_keychain as keychain;
use grin_wallet_util::grin_util as util;
use libwallet::slate::Slate;
use keychain::ExtKeychain;
use tempfile::tempdir;
@ -316,7 +333,7 @@ macro_rules! doctest_helper_setup_doc_env_foreign {
use api::Foreign;
use config::WalletConfig;
use impls::{HTTPNodeClient, LMDBBackend, WalletSeed};
use libwallet::types::{BlockFees, WalletBackend};
use libwallet::{BlockFees, Slate, WalletBackend};
let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
let dir = dir

View file

@ -15,9 +15,10 @@
//! JSON-RPC Stub generation for the Foreign API
use crate::keychain::Keychain;
use crate::libwallet::types::{BlockFees, CbData, InitTxArgs, NodeClient, WalletBackend};
use crate::libwallet::ErrorKind;
use crate::libwallet::{Slate, VersionedSlate};
use crate::libwallet::{
BlockFees, CbData, ErrorKind, InitTxArgs, NodeClient, Slate, VersionInfo, VersionedSlate,
WalletBackend,
};
use crate::Foreign;
use easy_jsonrpc;
@ -27,6 +28,40 @@ use easy_jsonrpc;
/// * The endpoint only supports POST operations, with the json-rpc request as the body
#[easy_jsonrpc::rpc]
pub trait ForeignRpc {
/**
Networked version of [Foreign::check_version](struct.Foreign.html#method.check_version).
# Json rpc example
```
# grin_wallet_api::doctest_helper_json_rpc_foreign_assert_response!(
# r#"
{
"jsonrpc": "2.0",
"method": "check_version",
"id": 1,
"params": []
}
# "#
# ,
# r#"
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"Ok": {
"default_slate_version": 2,
"foreign_api_version": 2
}
}
}
# "#
# , 0, false);
```
*/
fn check_version(&self) -> Result<VersionInfo, ErrorKind>;
/**
Networked version of [Foreign::build_coinbase](struct.Foreign.html#method.build_coinbase).
@ -322,6 +357,10 @@ where
C: NodeClient,
K: Keychain,
{
fn check_version(&self) -> Result<VersionInfo, ErrorKind> {
Foreign::check_version(self).map_err(|e| e.kind())
}
fn build_coinbase(&self, block_fees: &BlockFees) -> Result<CbData, ErrorKind> {
Foreign::build_coinbase(self, block_fees).map_err(|e| e.kind())
}

View file

@ -24,12 +24,10 @@ use crate::core::core::Transaction;
use crate::impls::{HTTPWalletCommAdapter, KeybaseWalletCommAdapter};
use crate::keychain::{Identifier, Keychain};
use crate::libwallet::api_impl::owner;
use crate::libwallet::slate::Slate;
use crate::libwallet::types::{
AcctPathMapping, InitTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, TxLogEntry,
WalletBackend, WalletInfo,
use crate::libwallet::{
AcctPathMapping, Error, ErrorKind, InitTxArgs, NodeClient, NodeHeightResult,
OutputCommitMapping, Slate, TxLogEntry, WalletBackend, WalletInfo,
};
use crate::libwallet::{Error, ErrorKind};
/// Main interface into all wallet API functions.
/// Wallet APIs are split into two seperate blocks of functionality
@ -99,7 +97,7 @@ where
/// use api::Owner;
/// use config::WalletConfig;
/// use impls::{HTTPNodeClient, LMDBBackend};
/// use libwallet::types::WalletBackend;
/// use libwallet::WalletBackend;
///
/// let mut wallet_config = WalletConfig::default();
/// # let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
@ -1018,7 +1016,7 @@ macro_rules! doctest_helper_setup_doc_env {
use api::Owner;
use config::WalletConfig;
use impls::{HTTPNodeClient, LMDBBackend, WalletSeed};
use libwallet::types::{InitTxArgs, WalletBackend};
use libwallet::{InitTxArgs, WalletBackend};
let dir = tempdir().map_err(|e| format!("{:#?}", e)).unwrap();
let dir = dir

View file

@ -17,12 +17,10 @@ use uuid::Uuid;
use crate::core::core::Transaction;
use crate::keychain::{Identifier, Keychain};
use crate::libwallet::slate::Slate;
use crate::libwallet::types::{
AcctPathMapping, InitTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, TxLogEntry,
WalletBackend, WalletInfo,
use crate::libwallet::{
AcctPathMapping, ErrorKind, InitTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping,
Slate, TxLogEntry, WalletBackend, WalletInfo,
};
use crate::libwallet::ErrorKind;
use crate::Owner;
use easy_jsonrpc;

View file

@ -35,7 +35,7 @@ use crate::impls::{
LMDBBackend, NullWalletCommAdapter,
};
use crate::impls::{HTTPNodeClient, WalletSeed};
use crate::libwallet::types::{InitTxArgs, NodeClient, WalletInst};
use crate::libwallet::{InitTxArgs, NodeClient, WalletInst};
use crate::{controller, display};
/// Arguments common to all wallet commands

View file

@ -20,12 +20,10 @@ use crate::core::core;
use crate::core::core::Transaction;
use crate::impls::{FileWalletCommAdapter, HTTPWalletCommAdapter, KeybaseWalletCommAdapter};
use crate::keychain::Keychain;
use crate::libwallet::slate::Slate;
use crate::libwallet::types::{
CbData, InitTxArgs, NodeClient, OutputCommitMapping, SendTXArgs, TxLogEntry, WalletBackend,
WalletInfo,
use crate::libwallet::{
CbData, Error, ErrorKind, InitTxArgs, NodeClient, OutputCommitMapping, SendTXArgs, Slate,
TxLogEntry, WalletBackend, WalletInfo,
};
use crate::libwallet::{Error, ErrorKind};
use crate::util::to_base64;
use crate::util::Mutex;
use failure::ResultExt;

View file

@ -14,10 +14,9 @@
use crate::core::core::{self, amount_to_hr_string};
use crate::core::global;
use crate::libwallet::types::{
AcctPathMapping, OutputCommitMapping, OutputStatus, TxLogEntry, WalletInfo,
use crate::libwallet::{
AcctPathMapping, Error, OutputCommitMapping, OutputStatus, TxLogEntry, WalletInfo,
};
use crate::libwallet::Error;
use crate::util;
use prettytable;
use std::io::prelude::Write;

View file

@ -26,7 +26,7 @@ use self::core::global::ChainTypes;
use self::keychain::{ExtKeychain, Keychain};
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use libwallet::types::InitTxArgs;
use libwallet::InitTxArgs;
use std::fs;
use std::thread;
use std::time::Duration;

View file

@ -28,7 +28,7 @@ use self::keychain::ExtKeychain;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use impls::FileWalletCommAdapter;
use libwallet::types::{InitTxArgs, WalletInst};
use libwallet::{InitTxArgs, WalletInst};
use std::fs;
use std::thread;
use std::time::Duration;
@ -123,7 +123,7 @@ fn check_repair_impl(test_dir: &str) -> Result<(), libwallet::Error> {
assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward);
// check tx log as well
let (_, txs) = api.retrieve_txs(true, None, None)?;
let (c, _) = libwallet::types::TxLogEntry::sum_confirmed(&txs);
let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs);
assert_eq!(wallet1_info.total, c);
assert_eq!(txs.len(), bh as usize);
Ok(())
@ -135,7 +135,7 @@ fn check_repair_impl(test_dir: &str) -> Result<(), libwallet::Error> {
w1_outputs_commits = api.retrieve_outputs(false, true, None)?.1;
Ok(())
})?;
let w1_outputs: Vec<libwallet::types::OutputData> =
let w1_outputs: Vec<libwallet::OutputData> =
w1_outputs_commits.into_iter().map(|m| m.output).collect();
{
let mut w = wallet1.lock();
@ -145,7 +145,7 @@ fn check_repair_impl(test_dir: &str) -> Result<(), libwallet::Error> {
batch.delete(&w1_outputs[4].key_id, &None)?;
batch.delete(&w1_outputs[10].key_id, &None)?;
let mut accidental_spent = w1_outputs[13].clone();
accidental_spent.status = libwallet::types::OutputStatus::Spent;
accidental_spent.status = libwallet::OutputStatus::Spent;
batch.save(accidental_spent)?;
batch.commit()?;
}
@ -156,7 +156,7 @@ fn check_repair_impl(test_dir: &str) -> Result<(), libwallet::Error> {
wallet::controller::owner_single_use(wallet1.clone(), |api| {
let (_, wallet1_info) = api.retrieve_summary_info(true, 1)?;
let (_, txs) = api.retrieve_txs(true, None, None)?;
let (c, _) = libwallet::types::TxLogEntry::sum_confirmed(&txs);
let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs);
assert!(wallet1_info.total != c);
Ok(())
})?;
@ -223,10 +223,9 @@ fn check_repair_impl(test_dir: &str) -> Result<(), libwallet::Error> {
fn two_wallets_one_seed_impl(test_dir: &str) -> Result<(), libwallet::Error> {
setup(test_dir);
let seed_phrase =
"affair pistol cancel crush garment candy ancient flag work \
market crush dry stand focus mutual weapon offer ceiling rival turn team spring \
where swift";
let seed_phrase = "affair pistol cancel crush garment candy ancient flag work \
market crush dry stand focus mutual weapon offer ceiling rival turn team spring \
where swift";
// Create a new proxy to simulate server and wallet responses
let mut wallet_proxy: WalletProxy<LocalWalletClient, ExtKeychain> = WalletProxy::new(test_dir);

View file

@ -31,7 +31,7 @@ use std::fs;
use std::thread;
use std::time::Duration;
use grin_wallet_libwallet::types::InitTxArgs;
use grin_wallet_libwallet::InitTxArgs;
use serde_json;

View file

@ -25,8 +25,7 @@ use grin_wallet_util::grin_util as util;
use self::core::global;
use self::core::global::ChainTypes;
use self::keychain::ExtKeychain;
use self::libwallet::slate::Slate;
use self::libwallet::types::InitTxArgs;
use self::libwallet::{InitTxArgs, Slate};
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use impls::FileWalletCommAdapter;
use std::fs;

View file

@ -25,8 +25,7 @@ use grin_wallet_util::grin_util as util;
use self::core::global;
use self::core::global::ChainTypes;
use self::keychain::{ExtKeychain, Identifier, Keychain};
use self::libwallet::slate::Slate;
use self::libwallet::types::{AcctPathMapping, InitTxArgs};
use self::libwallet::{AcctPathMapping, InitTxArgs, Slate};
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use std::fs;
use std::sync::atomic::Ordering;
@ -124,11 +123,11 @@ fn compare_wallet_restore(
}
});
let mut src_info: Option<libwallet::types::WalletInfo> = None;
let mut dest_info: Option<libwallet::types::WalletInfo> = None;
let mut src_info: Option<libwallet::WalletInfo> = None;
let mut dest_info: Option<libwallet::WalletInfo> = None;
let mut src_txs: Option<Vec<libwallet::types::TxLogEntry>> = None;
let mut dest_txs: Option<Vec<libwallet::types::TxLogEntry>> = None;
let mut src_txs: Option<Vec<libwallet::TxLogEntry>> = None;
let mut dest_txs: Option<Vec<libwallet::TxLogEntry>> = None;
let mut src_accts: Option<Vec<AcctPathMapping>> = None;
let mut dest_accts: Option<Vec<AcctPathMapping>> = None;

View file

@ -26,7 +26,7 @@ use self::core::global::ChainTypes;
use self::keychain::ExtKeychain;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use libwallet::types::InitTxArgs;
use libwallet::InitTxArgs;
use std::fs;
use std::thread;
use std::time::Duration;

View file

@ -26,8 +26,7 @@ use self::core::core::transaction;
use self::core::global;
use self::core::global::ChainTypes;
use self::keychain::ExtKeychain;
use self::libwallet::slate::Slate;
use self::libwallet::types::{InitTxArgs, OutputStatus};
use self::libwallet::{InitTxArgs, OutputStatus, Slate};
use impls::test_framework::{self, LocalWalletClient, WalletProxy};
use std::fs;
use std::thread;
@ -75,7 +74,7 @@ fn basic_transaction_api(test_dir: &str) -> Result<(), libwallet::Error> {
// few values to keep things shorter
let reward = core::consensus::REWARD;
let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height
// mine a few blocks
// mine a few blocks
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), 10, false);
// Check wallet 1 contents are as expected
@ -379,7 +378,7 @@ fn tx_rollback(test_dir: &str) -> Result<(), libwallet::Error> {
// few values to keep things shorter
let reward = core::consensus::REWARD;
let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height
// mine a few blocks
// mine a few blocks
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), 5, false);
let amount = 30_000_000_000;

View file

@ -17,8 +17,7 @@ use std::fs::File;
use std::io::{Read, Write};
use crate::config::WalletConfig;
use crate::libwallet::slate::Slate;
use crate::libwallet::Error;
use crate::libwallet::{Error, Slate};
use crate::WalletCommAdapter;
use std::collections::HashMap;

View file

@ -16,9 +16,8 @@
/// HTTP Wallet 'plugin' implementation
use crate::api;
use crate::libwallet::slate::Slate;
use crate::libwallet::slate_versions::{v0, v1};
use crate::libwallet::{Error, ErrorKind};
use crate::libwallet::{Error, ErrorKind, Slate};
use crate::WalletCommAdapter;
use config::WalletConfig;
use failure::ResultExt;

View file

@ -16,8 +16,7 @@
use crate::config::WalletConfig;
use crate::libwallet::api_impl::foreign;
use crate::libwallet::slate::Slate;
use crate::libwallet::{Error, ErrorKind};
use crate::libwallet::{Error, ErrorKind, Slate};
use crate::{instantiate_wallet, HTTPNodeClient, WalletCommAdapter};
use failure::ResultExt;
use serde::Serialize;

View file

@ -23,8 +23,7 @@ pub use self::keybase::KeybaseWalletCommAdapter;
pub use self::null::NullWalletCommAdapter;
use crate::config::WalletConfig;
use crate::libwallet::slate::Slate;
use crate::libwallet::Error;
use crate::libwallet::{Error, Slate};
use std::collections::HashMap;
/// Encapsulate wallet to wallet communication functions

View file

@ -14,8 +14,7 @@
use crate::config::WalletConfig;
/// Null Output 'plugin' implementation
use crate::libwallet::slate::Slate;
use crate::libwallet::Error;
use crate::libwallet::{Error, Slate};
use crate::WalletCommAdapter;
use std::collections::HashMap;

View file

@ -50,7 +50,7 @@ pub use crate::seed::{EncryptedWalletSeed, WalletSeed, SEED_FILE};
use crate::util::Mutex;
use std::sync::Arc;
use libwallet::types::{NodeClient, WalletBackend, WalletInst};
use libwallet::{NodeClient, WalletBackend, WalletInst};
/// Helper to create an instance of the LMDB wallet
pub fn instantiate_wallet(

View file

@ -30,9 +30,11 @@ use crate::store::{self, option_to_not_found, to_key, to_key_u64};
use crate::core::core::Transaction;
use crate::core::{global, ser};
use crate::libwallet::types::*;
use crate::libwallet::{check_repair, restore};
use crate::libwallet::{Error, ErrorKind};
use crate::libwallet::{
AcctPathMapping, Context, Error, ErrorKind, NodeClient, OutputData, TxLogEntry, WalletBackend,
WalletOutputBatch,
};
use crate::util;
use crate::util::secp::constants::SECRET_KEY_SIZE;
use crate::util::ZeroingString;

View file

@ -17,7 +17,7 @@
use futures::{stream, Stream};
use crate::libwallet::types::*;
use crate::libwallet::{NodeClient, TxWrapper};
use std::collections::HashMap;
use tokio::runtime::Runtime;

View file

@ -22,7 +22,7 @@ use crate::core::{consensus, global, pow};
use crate::keychain;
use crate::libwallet;
use crate::libwallet::api_impl::{foreign, owner};
use crate::libwallet::types::{
use crate::libwallet::{
BlockFees, CbData, InitTxArgs, NodeClient, WalletBackend, WalletInfo, WalletInst,
};
use crate::lmdb_wallet::LMDBBackend;

View file

@ -26,8 +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::slate::Slate;
use crate::libwallet::types::*;
use crate::libwallet::{NodeClient, Slate, TxWrapper, WalletInst};
use crate::util;
use crate::util::secp::pedersen;
use crate::util::secp::pedersen::Commitment;

View file

@ -23,3 +23,4 @@
pub mod foreign;
pub mod owner;
pub mod types;

View file

@ -16,12 +16,22 @@
use crate::grin_keychain::Keychain;
use crate::internal::{tx, updater};
use crate::slate::Slate;
use crate::types::{BlockFees, CbData, NodeClient, TxLogEntryType, WalletBackend};
use crate::{Error, ErrorKind};
use crate::{
slate_versions, BlockFees, CbData, Error, ErrorKind, NodeClient, Slate, TxLogEntryType,
VersionInfo, WalletBackend,
};
const FOREIGN_API_VERSION: u16 = 2;
const USER_MESSAGE_MAX_LEN: usize = 256;
/// Return the version info
pub fn check_version() -> VersionInfo {
VersionInfo {
foreign_api_version: FOREIGN_API_VERSION,
default_slate_version: slate_versions::CURRENT_SLATE_VERSION,
}
}
/// Build a coinbase transaction
pub fn build_coinbase<T: ?Sized, C, K>(
w: &mut T,

View file

@ -24,11 +24,9 @@ use crate::grin_util;
use crate::grin_keychain::{Identifier, Keychain};
use crate::internal::{keys, selection, tx, updater};
use crate::slate::Slate;
use crate::types::{
AcctPathMapping, InitTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, TxLogEntry,
TxWrapper, WalletBackend, WalletInfo,
};
use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, TxWrapper, WalletBackend, WalletInfo};
use crate::{Error, ErrorKind};
use crate::{InitTxArgs, NodeHeightResult, OutputCommitMapping};
const USER_MESSAGE_MAX_LEN: usize = 256;

View file

@ -0,0 +1,193 @@
// Copyright 2018 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Types specific to the wallet api, mostly argument serialization
use crate::grin_core::core::{Output, TxKernel};
use crate::grin_core::libtx::secp_ser;
use crate::grin_keychain::Identifier;
use crate::grin_util::secp::pedersen;
use crate::types::OutputData;
/// Send TX API Args
// TODO: This is here to ensure the legacy V1 API remains intact
// remove this when v1 api is removed
#[derive(Clone, Serialize, Deserialize)]
pub struct SendTXArgs {
/// amount to send
pub amount: u64,
/// minimum confirmations
pub minimum_confirmations: u64,
/// payment method
pub method: String,
/// destination url
pub dest: String,
/// Max number of outputs
pub max_outputs: usize,
/// Number of change outputs to generate
pub num_change_outputs: usize,
/// whether to use all outputs (combine)
pub selection_strategy_is_use_all: bool,
/// Optional message, that will be signed
pub message: Option<String>,
/// Optional slate version to target when sending
pub target_slate_version: Option<u16>,
}
/// V2 Init / Send TX API Args
#[derive(Clone, Serialize, Deserialize)]
pub struct InitTxArgs {
/// The human readable account name from which to draw outputs
/// for the transaction, overriding whatever the active account is as set via the
/// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method.
pub src_acct_name: Option<String>,
#[serde(with = "secp_ser::string_or_u64")]
/// The amount to send, in nanogrins. (`1 G = 1_000_000_000nG`)
pub amount: u64,
#[serde(with = "secp_ser::string_or_u64")]
/// The minimum number of confirmations an output
/// should have in order to be included in the transaction.
pub minimum_confirmations: u64,
/// By default, the wallet selects as many inputs as possible in a
/// transaction, to reduce the Output set and the fees. The wallet will attempt to spend
/// include up to `max_outputs` in a transaction, however if this is not enough to cover
/// the whole amount, the wallet will include more outputs. This parameter should be considered
/// a soft limit.
pub max_outputs: u32,
/// The target number of change outputs to create in the transaction.
/// The actual number created will be `num_change_outputs` + whatever remainder is needed.
pub num_change_outputs: u32,
/// If `true`, attempt to use up as many outputs as
/// possible to create the transaction, up the 'soft limit' of `max_outputs`. This helps
/// to reduce the size of the UTXO set and the amount of data stored in the wallet, and
/// minimizes fees. This will generally result in many inputs and a large change output(s),
/// usually much larger than the amount being sent. If `false`, the transaction will include
/// as many outputs as are needed to meet the amount, (and no more) starting with the smallest
/// value outputs.
pub selection_strategy_is_use_all: bool,
/// An optional participant message to include alongside the sender's public
/// ParticipantData within the slate. This message will include a signature created with the
/// sender's private excess value, and will be publically verifiable. Note this message is for
/// the convenience of the participants during the exchange; it is not included in the final
/// transaction sent to the chain. The message will be truncated to 256 characters.
pub message: Option<String>,
/// Optionally set the output target slate version (acceptable
/// down to the minimum slate version compatible with the current. If `None` the slate
/// is generated with the latest version.
pub target_slate_version: Option<u16>,
/// If true, just return an estimate of the resulting slate, containing fees and amounts
/// locked without actually locking outputs or creating the transaction. Note if this is set to
/// 'true', the amount field in the slate will contain the total amount locked, not the provided
/// transaction amount
pub estimate_only: Option<bool>,
/// Sender arguments. If present, the underlying function will also attempt to send the
/// transaction to a destination and optionally finalize the result
pub send_args: Option<InitTxSendArgs>,
}
/// Send TX API Args, for convenience functionality that inits the transaction and sends
/// in one go
#[derive(Clone, Serialize, Deserialize)]
pub struct InitTxSendArgs {
/// The transaction method. Can currently be 'http' or 'keybase'.
pub method: String,
/// The destination, contents will depend on the particular method
pub dest: String,
/// Whether to finalize the result immediately if the send was successful
pub finalize: bool,
/// Whether to post the transasction if the send and finalize were successful
pub post_tx: bool,
/// Whether to use dandelion when posting. If false, skip the dandelion relay
pub fluff: bool,
}
impl Default for InitTxArgs {
fn default() -> InitTxArgs {
InitTxArgs {
src_acct_name: None,
amount: 0,
minimum_confirmations: 10,
max_outputs: 500,
num_change_outputs: 1,
selection_strategy_is_use_all: true,
message: None,
target_slate_version: None,
estimate_only: Some(false),
send_args: None,
}
}
}
/// Fees in block to use for coinbase amount calculation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BlockFees {
/// fees
#[serde(with = "secp_ser::string_or_u64")]
pub fees: u64,
/// height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// key id
pub key_id: Option<Identifier>,
}
impl BlockFees {
/// return key id
pub fn key_id(&self) -> Option<Identifier> {
self.key_id.clone()
}
}
/// Response to build a coinbase output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CbData {
/// Output
pub output: Output,
/// Kernel
pub kernel: TxKernel,
/// Key Id
pub key_id: Option<Identifier>,
}
/// Map Outputdata to commits
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct OutputCommitMapping {
/// Output Data
pub output: OutputData,
/// The commit
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::commitment_from_hex"
)]
pub commit: pedersen::Commitment,
}
/// Node height result
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeHeightResult {
/// Last known height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// Whether this height was updated from the node
pub updated_from_node: bool,
}
/// Version request result
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VersionInfo {
/// API version
pub foreign_api_version: u16,
/// Slate version
pub default_slate_version: u16,
}

View file

@ -19,7 +19,7 @@ use crate::grin_keychain::{ExtKeychain, Identifier, Keychain};
use crate::grin_util::secp::{key::SecretKey, pedersen};
use crate::internal::{keys, updater};
use crate::types::*;
use crate::Error;
use crate::{Error, OutputCommitMapping};
use std::collections::HashMap;
/// Utility struct for return values from below

View file

@ -28,9 +28,9 @@ use crate::grin_util as util;
use crate::grin_util::secp::pedersen;
use crate::internal::keys;
use crate::types::{
BlockFees, CbData, NodeClient, OutputCommitMapping, OutputData, OutputStatus, TxLogEntry,
TxLogEntryType, WalletBackend, WalletInfo,
NodeClient, OutputData, OutputStatus, TxLogEntry, TxLogEntryType, WalletBackend, WalletInfo,
};
use crate::{BlockFees, CbData, OutputCommitMapping};
/// Retrieve all of the outputs (doesn't attempt to update from node)
pub fn retrieve_outputs<T: ?Sized, C, K>(

View file

@ -42,11 +42,19 @@ extern crate lazy_static;
pub mod api_impl;
mod error;
mod internal;
pub mod slate;
mod slate;
pub mod slate_versions;
pub mod types;
mod types;
pub use crate::error::{Error, ErrorKind};
pub use crate::slate::Slate;
pub use crate::slate::{ParticipantData, ParticipantMessageData, Slate};
pub use crate::slate_versions::{SlateVersion, VersionedSlate};
pub use api_impl::types::{
BlockFees, CbData, InitTxArgs, InitTxSendArgs, NodeHeightResult, OutputCommitMapping,
SendTXArgs, VersionInfo,
};
pub use internal::restore::{check_repair, restore};
pub use types::{
AcctPathMapping, BlockIdentifier, Context, NodeClient, OutputData, OutputStatus, TxLogEntry,
TxLogEntryType, TxWrapper, WalletBackend, WalletInfo, WalletInst, WalletOutputBatch,
};

View file

@ -17,7 +17,7 @@
use crate::error::{Error, ErrorKind};
use crate::grin_core::core::hash::Hash;
use crate::grin_core::core::{Output, Transaction, TxKernel};
use crate::grin_core::core::Transaction;
use crate::grin_core::libtx::{aggsig, secp_ser};
use crate::grin_core::ser;
use crate::grin_keychain::{Identifier, Keychain};
@ -697,168 +697,3 @@ pub struct TxWrapper {
/// hex representation of transaction
pub tx_hex: String,
}
// Types to facilitate API arguments and serialization
/// Send TX API Args
// TODO: This is here to ensure the legacy V1 API remains intact
// remove this when v1 api is removed
#[derive(Clone, Serialize, Deserialize)]
pub struct SendTXArgs {
/// amount to send
pub amount: u64,
/// minimum confirmations
pub minimum_confirmations: u64,
/// payment method
pub method: String,
/// destination url
pub dest: String,
/// Max number of outputs
pub max_outputs: usize,
/// Number of change outputs to generate
pub num_change_outputs: usize,
/// whether to use all outputs (combine)
pub selection_strategy_is_use_all: bool,
/// Optional message, that will be signed
pub message: Option<String>,
/// Optional slate version to target when sending
pub target_slate_version: Option<u16>,
}
/// V2 Init / Send TX API Args
#[derive(Clone, Serialize, Deserialize)]
pub struct InitTxArgs {
/// The human readable account name from which to draw outputs
/// for the transaction, overriding whatever the active account is as set via the
/// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method.
pub src_acct_name: Option<String>,
#[serde(with = "secp_ser::string_or_u64")]
/// The amount to send, in nanogrins. (`1 G = 1_000_000_000nG`)
pub amount: u64,
#[serde(with = "secp_ser::string_or_u64")]
/// The minimum number of confirmations an output
/// should have in order to be included in the transaction.
pub minimum_confirmations: u64,
/// By default, the wallet selects as many inputs as possible in a
/// transaction, to reduce the Output set and the fees. The wallet will attempt to spend
/// include up to `max_outputs` in a transaction, however if this is not enough to cover
/// the whole amount, the wallet will include more outputs. This parameter should be considered
/// a soft limit.
pub max_outputs: u32,
/// The target number of change outputs to create in the transaction.
/// The actual number created will be `num_change_outputs` + whatever remainder is needed.
pub num_change_outputs: u32,
/// If `true`, attempt to use up as many outputs as
/// possible to create the transaction, up the 'soft limit' of `max_outputs`. This helps
/// to reduce the size of the UTXO set and the amount of data stored in the wallet, and
/// minimizes fees. This will generally result in many inputs and a large change output(s),
/// usually much larger than the amount being sent. If `false`, the transaction will include
/// as many outputs as are needed to meet the amount, (and no more) starting with the smallest
/// value outputs.
pub selection_strategy_is_use_all: bool,
/// An optional participant message to include alongside the sender's public
/// ParticipantData within the slate. This message will include a signature created with the
/// sender's private excess value, and will be publically verifiable. Note this message is for
/// the convenience of the participants during the exchange; it is not included in the final
/// transaction sent to the chain. The message will be truncated to 256 characters.
pub message: Option<String>,
/// Optionally set the output target slate version (acceptable
/// down to the minimum slate version compatible with the current. If `None` the slate
/// is generated with the latest version.
pub target_slate_version: Option<u16>,
/// If true, just return an estimate of the resulting slate, containing fees and amounts
/// locked without actually locking outputs or creating the transaction. Note if this is set to
/// 'true', the amount field in the slate will contain the total amount locked, not the provided
/// transaction amount
pub estimate_only: Option<bool>,
/// Sender arguments. If present, the underlying function will also attempt to send the
/// transaction to a destination and optionally finalize the result
pub send_args: Option<InitTxSendArgs>,
}
/// Send TX API Args, for convenience functionality that inits the transaction and sends
/// in one go
#[derive(Clone, Serialize, Deserialize)]
pub struct InitTxSendArgs {
/// The transaction method. Can currently be 'http' or 'keybase'.
pub method: String,
/// The destination, contents will depend on the particular method
pub dest: String,
/// Whether to finalize the result immediately if the send was successful
pub finalize: bool,
/// Whether to post the transasction if the send and finalize were successful
pub post_tx: bool,
/// Whether to use dandelion when posting. If false, skip the dandelion relay
pub fluff: bool,
}
impl Default for InitTxArgs {
fn default() -> InitTxArgs {
InitTxArgs {
src_acct_name: None,
amount: 0,
minimum_confirmations: 10,
max_outputs: 500,
num_change_outputs: 1,
selection_strategy_is_use_all: true,
message: None,
target_slate_version: None,
estimate_only: Some(false),
send_args: None,
}
}
}
/// Fees in block to use for coinbase amount calculation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BlockFees {
/// fees
#[serde(with = "secp_ser::string_or_u64")]
pub fees: u64,
/// height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// key id
pub key_id: Option<Identifier>,
}
impl BlockFees {
/// return key id
pub fn key_id(&self) -> Option<Identifier> {
self.key_id.clone()
}
}
/// Response to build a coinbase output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CbData {
/// Output
pub output: Output,
/// Kernel
pub kernel: TxKernel,
/// Key Id
pub key_id: Option<Identifier>,
}
/// Map Outputdata to commits
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct OutputCommitMapping {
/// Output Data
pub output: OutputData,
/// The commit
#[serde(
serialize_with = "secp_ser::as_hex",
deserialize_with = "secp_ser::commitment_from_hex"
)]
pub commit: pedersen::Commitment,
}
/// Node height result
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeHeightResult {
/// Last known height
#[serde(with = "secp_ser::string_or_u64")]
pub height: u64,
/// Whether this height was updated from the node
pub updated_from_node: bool,
}

View file

@ -12,7 +12,7 @@
// limitations under the License.
//! core::libtx specific tests
use grin_wallet_libwallet::types::Context;
use grin_wallet_libwallet::Context;
use grin_wallet_util::grin_core::core::transaction;
use grin_wallet_util::grin_core::libtx::{aggsig, proof};
use grin_wallet_util::grin_keychain::{

View file

@ -12,7 +12,7 @@
// limitations under the License.
//! core::libtx specific tests
use grin_wallet_libwallet::slate::Slate;
use grin_wallet_libwallet::Slate;
// test all slate conversions
#[test]

View file

@ -22,7 +22,7 @@ use grin_wallet_config::WalletConfig;
use grin_wallet_controller::command;
use grin_wallet_controller::{Error, ErrorKind};
use grin_wallet_impls::{instantiate_wallet, WalletSeed};
use grin_wallet_libwallet::types::{NodeClient, WalletInst};
use grin_wallet_libwallet::{NodeClient, WalletInst};
use grin_wallet_util::grin_core as core;
use grin_wallet_util::grin_keychain as keychain;
use linefeed::terminal::Signal;

View file

@ -28,7 +28,7 @@ mod wallet_tests {
use grin_wallet_config::{GlobalWalletConfig, WalletConfig};
use grin_wallet_impls::{LMDBBackend, WalletSeed};
use grin_wallet_libwallet::types::{WalletBackend, WalletInst};
use grin_wallet_libwallet::{WalletBackend, WalletInst};
use grin_wallet_util::grin_core::global::{self, ChainTypes};
use grin_wallet_util::grin_keychain::ExtKeychain;