mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-12-05 05:13:59 +01:00
APIV2 refactoring (#23)
* continue refactor * rustfmt * further refactoring * impl crate compiling * main crate compilation * rustfmt * test fix * rustfmt * test compilation * rustfmt * refwallet tests passing * rustfmt * all tests passing * move http listener startup out of adapter * rustfmt * rename refwallet->controller * rustfmt * travis tests and api doctests * rustfmt
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
// 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.
|
||||
|
||||
use self::chain::Chain;
|
||||
use self::core::core::{OutputFeatures, OutputIdentifier, Transaction};
|
||||
use self::core::{consensus, global, pow, ser};
|
||||
use self::util::secp::pedersen;
|
||||
use self::util::Mutex;
|
||||
use crate::config::WalletConfig;
|
||||
use crate::libwallet;
|
||||
use crate::libwallet::api_impl::{foreign, owner};
|
||||
use crate::libwallet::types::{
|
||||
BlockFees, CbData, NodeClient, WalletBackend, WalletInfo, WalletInst,
|
||||
};
|
||||
use crate::lmdb_wallet::LMDBBackend;
|
||||
use crate::WalletSeed;
|
||||
use chrono::Duration;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_util as util;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod testclient;
|
||||
|
||||
pub use self::{testclient::LocalWalletClient, testclient::WalletProxy};
|
||||
|
||||
/// Get an output from the chain locally and present it back as an API output
|
||||
fn get_output_local(chain: &chain::Chain, commit: &pedersen::Commitment) -> Option<api::Output> {
|
||||
let outputs = [
|
||||
OutputIdentifier::new(OutputFeatures::Plain, commit),
|
||||
OutputIdentifier::new(OutputFeatures::Coinbase, commit),
|
||||
];
|
||||
|
||||
for x in outputs.iter() {
|
||||
if let Ok(_) = chain.is_unspent(&x) {
|
||||
let block_height = chain.get_header_for_output(&x).unwrap().height;
|
||||
let output_pos = chain.get_output_pos(&x.commit).unwrap_or(0);
|
||||
return Some(api::Output::new(&commit, block_height, output_pos));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// get output listing traversing pmmr from local
|
||||
fn get_outputs_by_pmmr_index_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
start_index: u64,
|
||||
max: u64,
|
||||
) -> api::OutputListing {
|
||||
let outputs = chain
|
||||
.unspent_outputs_by_insertion_index(start_index, max)
|
||||
.unwrap();
|
||||
api::OutputListing {
|
||||
last_retrieved_index: outputs.0,
|
||||
highest_index: outputs.1,
|
||||
outputs: outputs
|
||||
.2
|
||||
.iter()
|
||||
.map(|x| api::OutputPrintable::from_output(x, chain.clone(), None, true))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a block with a given reward to the chain and mines it
|
||||
pub fn add_block_with_reward(chain: &Chain, txs: Vec<&Transaction>, reward: CbData) {
|
||||
let prev = chain.head_header().unwrap();
|
||||
let next_header_info = consensus::next_difficulty(1, chain.difficulty_iter());
|
||||
let out_bin = util::from_hex(reward.output).unwrap();
|
||||
let kern_bin = util::from_hex(reward.kernel).unwrap();
|
||||
let output = ser::deserialize(&mut &out_bin[..]).unwrap();
|
||||
let kernel = ser::deserialize(&mut &kern_bin[..]).unwrap();
|
||||
let mut b = core::core::Block::new(
|
||||
&prev,
|
||||
txs.into_iter().cloned().collect(),
|
||||
next_header_info.clone().difficulty,
|
||||
(output, kernel),
|
||||
)
|
||||
.unwrap();
|
||||
b.header.timestamp = prev.timestamp + Duration::seconds(60);
|
||||
b.header.pow.secondary_scaling = next_header_info.secondary_scaling;
|
||||
chain.set_txhashset_roots(&mut b).unwrap();
|
||||
pow::pow_size(
|
||||
&mut b.header,
|
||||
next_header_info.difficulty,
|
||||
global::proofsize(),
|
||||
global::min_edge_bits(),
|
||||
)
|
||||
.unwrap();
|
||||
chain.process_block(b, chain::Options::MINE).unwrap();
|
||||
chain.validate(false).unwrap();
|
||||
}
|
||||
|
||||
/// adds a reward output to a wallet, includes that reward in a block, mines
|
||||
/// the block and adds it to the chain, with option transactions included.
|
||||
/// Helpful for building up precise wallet balances for testing.
|
||||
pub fn award_block_to_wallet<C, K>(
|
||||
chain: &Chain,
|
||||
txs: Vec<&Transaction>,
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
// build block fees
|
||||
let prev = chain.head_header().unwrap();
|
||||
let fee_amt = txs.iter().map(|tx| tx.fee()).sum();
|
||||
let block_fees = BlockFees {
|
||||
fees: fee_amt,
|
||||
key_id: None,
|
||||
height: prev.height + 1,
|
||||
};
|
||||
// build coinbase (via api) and add block
|
||||
let coinbase_tx = {
|
||||
let mut w = wallet.lock();
|
||||
w.open_with_credentials()?;
|
||||
let res = foreign::build_coinbase(&mut *w, &block_fees)?;
|
||||
w.close()?;
|
||||
res
|
||||
};
|
||||
add_block_with_reward(chain, txs, coinbase_tx.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Award a blocks to a wallet directly
|
||||
pub fn award_blocks_to_wallet<C, K>(
|
||||
chain: &Chain,
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
number: usize,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
for _ in 0..number {
|
||||
award_block_to_wallet(chain, vec![], wallet.clone())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// dispatch a db wallet
|
||||
pub fn create_wallet<C, K>(
|
||||
dir: &str,
|
||||
n_client: C,
|
||||
rec_phrase: Option<&str>,
|
||||
) -> Arc<Mutex<dyn WalletInst<C, K>>>
|
||||
where
|
||||
C: NodeClient + 'static,
|
||||
K: keychain::Keychain + 'static,
|
||||
{
|
||||
let z_string = match rec_phrase {
|
||||
Some(s) => Some(util::ZeroingString::from(s)),
|
||||
None => None,
|
||||
};
|
||||
let mut wallet_config = WalletConfig::default();
|
||||
wallet_config.data_file_dir = String::from(dir);
|
||||
let _ = WalletSeed::init_file(&wallet_config, 32, z_string, "");
|
||||
let mut wallet = LMDBBackend::new(wallet_config.clone(), "", n_client)
|
||||
.unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, wallet_config));
|
||||
wallet.open_with_credentials().unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Error initializing wallet: {:?} Config: {:?}",
|
||||
e, wallet_config
|
||||
)
|
||||
});
|
||||
Arc::new(Mutex::new(wallet))
|
||||
}
|
||||
|
||||
/// send an amount to a destination
|
||||
pub fn send_to_dest<T: ?Sized, C, K>(
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
client: LocalWalletClient,
|
||||
dest: &str,
|
||||
amount: u64,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
let slate = {
|
||||
let mut w = wallet.lock();
|
||||
w.open_with_credentials()?;
|
||||
let slate_i = owner::initiate_tx(
|
||||
&mut *w, None, // account
|
||||
amount, // amount
|
||||
2, // minimum confirmations
|
||||
500, // max outputs
|
||||
1, // num change outputs
|
||||
true, // select all outputs
|
||||
None, None,
|
||||
)?;
|
||||
let mut slate = client.send_tx_slate_direct(dest, &slate_i)?;
|
||||
owner::tx_lock_outputs(&mut *w, &slate)?;
|
||||
owner::finalize_tx(&mut *w, &mut slate)?;
|
||||
w.close()?;
|
||||
slate
|
||||
};
|
||||
let client = {
|
||||
let mut w = wallet.lock();
|
||||
w.w2n_client().clone()
|
||||
};
|
||||
owner::post_tx(&client, &slate.tx, false)?; // mines a block
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get wallet info totals
|
||||
pub fn wallet_info<T: ?Sized, C, K>(
|
||||
wallet: Arc<Mutex<dyn WalletInst<C, K>>>,
|
||||
) -> Result<WalletInfo, libwallet::Error>
|
||||
where
|
||||
T: WalletBackend<C, K>,
|
||||
C: NodeClient,
|
||||
K: keychain::Keychain,
|
||||
{
|
||||
let mut w = wallet.lock();
|
||||
w.open_with_credentials()?;
|
||||
let (wallet_refreshed, wallet_info) = owner::retrieve_summary_info(&mut *w, true, 1)?;
|
||||
assert!(wallet_refreshed);
|
||||
w.close()?;
|
||||
Ok(wallet_info)
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
// 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.
|
||||
|
||||
//! Test client that acts against a local instance of a node
|
||||
//! so that wallet API can be fully exercised
|
||||
//! Operates directly on a chain instance
|
||||
|
||||
use self::chain::types::NoopAdapter;
|
||||
use self::chain::Chain;
|
||||
use self::core::core::verifier_cache::LruVerifierCache;
|
||||
use self::core::core::Transaction;
|
||||
use self::core::global::{set_mining_mode, ChainTypes};
|
||||
use self::core::{pow, ser};
|
||||
use self::keychain::Keychain;
|
||||
use self::util::secp::pedersen;
|
||||
use self::util::secp::pedersen::Commitment;
|
||||
use self::util::{Mutex, RwLock, StopState};
|
||||
use crate::config::WalletConfig;
|
||||
use crate::libwallet::api_impl::foreign;
|
||||
use crate::libwallet::slate::Slate;
|
||||
use crate::libwallet::types::*;
|
||||
use crate::{libwallet, WalletCommAdapter};
|
||||
use failure::ResultExt;
|
||||
use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_util as util;
|
||||
use serde_json;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Messages to simulate wallet requests/responses
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WalletProxyMessage {
|
||||
/// sender ID
|
||||
pub sender_id: String,
|
||||
/// destination wallet (or server)
|
||||
pub dest: String,
|
||||
/// method (like a GET url)
|
||||
pub method: String,
|
||||
/// payload (json body)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// communicates with a chain instance or other wallet
|
||||
/// listener APIs via message queues
|
||||
pub struct WalletProxy<C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// directory to create the chain in
|
||||
pub chain_dir: String,
|
||||
/// handle to chain itself
|
||||
pub chain: Arc<Chain>,
|
||||
/// list of interested wallets
|
||||
pub wallets: HashMap<
|
||||
String,
|
||||
(
|
||||
Sender<WalletProxyMessage>,
|
||||
Arc<Mutex<dyn WalletInst<LocalWalletClient, K>>>,
|
||||
),
|
||||
>,
|
||||
/// simulate json send to another client
|
||||
/// address, method, payload (simulate HTTP request)
|
||||
pub tx: Sender<WalletProxyMessage>,
|
||||
/// simulate json receiving
|
||||
pub rx: Receiver<WalletProxyMessage>,
|
||||
/// queue control
|
||||
pub running: Arc<AtomicBool>,
|
||||
/// Phantom
|
||||
phantom_c: PhantomData<C>,
|
||||
/// Phantom
|
||||
phantom_k: PhantomData<K>,
|
||||
}
|
||||
|
||||
impl<C, K> WalletProxy<C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// Create a new client that will communicate with the given grin node
|
||||
pub fn new(chain_dir: &str) -> Self {
|
||||
set_mining_mode(ChainTypes::AutomatedTesting);
|
||||
let genesis_block = pow::mine_genesis_block().unwrap();
|
||||
let verifier_cache = Arc::new(RwLock::new(LruVerifierCache::new()));
|
||||
let dir_name = format!("{}/.grin", chain_dir);
|
||||
let c = Chain::init(
|
||||
dir_name.to_string(),
|
||||
Arc::new(NoopAdapter {}),
|
||||
genesis_block,
|
||||
pow::verify_size,
|
||||
verifier_cache,
|
||||
false,
|
||||
Arc::new(Mutex::new(StopState::new())),
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, rx) = channel();
|
||||
let retval = WalletProxy {
|
||||
chain_dir: chain_dir.to_owned(),
|
||||
chain: Arc::new(c),
|
||||
tx: tx,
|
||||
rx: rx,
|
||||
wallets: HashMap::new(),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
phantom_c: PhantomData,
|
||||
phantom_k: PhantomData,
|
||||
};
|
||||
retval
|
||||
}
|
||||
|
||||
/// Add wallet with a given "address"
|
||||
pub fn add_wallet(
|
||||
&mut self,
|
||||
addr: &str,
|
||||
tx: Sender<WalletProxyMessage>,
|
||||
wallet: Arc<Mutex<dyn WalletInst<LocalWalletClient, K>>>,
|
||||
) {
|
||||
self.wallets.insert(addr.to_owned(), (tx, wallet));
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
self.running.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Run the incoming message queue and respond more or less
|
||||
/// synchronously
|
||||
pub fn run(&mut self) -> Result<(), libwallet::Error> {
|
||||
self.running.store(true, Ordering::Relaxed);
|
||||
loop {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
// read queue
|
||||
let m = self.rx.recv().unwrap();
|
||||
trace!("Wallet Client Proxy Received: {:?}", m);
|
||||
let resp = match m.method.as_ref() {
|
||||
"get_chain_height" => self.get_chain_height(m)?,
|
||||
"get_outputs_from_node" => self.get_outputs_from_node(m)?,
|
||||
"get_outputs_by_pmmr_index" => self.get_outputs_by_pmmr_index(m)?,
|
||||
"send_tx_slate" => self.send_tx_slate(m)?,
|
||||
"post_tx" => self.post_tx(m)?,
|
||||
_ => panic!("Unknown Wallet Proxy Message"),
|
||||
};
|
||||
|
||||
self.respond(resp);
|
||||
if !self.running.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a message to a given wallet client
|
||||
fn respond(&mut self, m: WalletProxyMessage) {
|
||||
if let Some(s) = self.wallets.get_mut(&m.dest) {
|
||||
if let Err(e) = s.0.send(m.clone()) {
|
||||
panic!("Error sending response from proxy: {:?}, {}", m, e);
|
||||
}
|
||||
} else {
|
||||
panic!("Unknown wallet recipient for response message: {:?}", m);
|
||||
}
|
||||
}
|
||||
|
||||
/// post transaction to the chain (and mine it, taking the reward)
|
||||
fn post_tx(&mut self, m: WalletProxyMessage) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let dest_wallet = self.wallets.get_mut(&m.sender_id).unwrap().1.clone();
|
||||
let wrapper: TxWrapper = serde_json::from_str(&m.body).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper".to_owned()),
|
||||
)?;
|
||||
|
||||
let tx_bin = util::from_hex(wrapper.tx_hex).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper: tx_bin".to_owned()),
|
||||
)?;
|
||||
|
||||
let tx: Transaction = ser::deserialize(&mut &tx_bin[..]).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper: tx".to_owned()),
|
||||
)?;
|
||||
|
||||
super::award_block_to_wallet(&self.chain, vec![&tx], dest_wallet)?;
|
||||
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: "".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// send tx slate
|
||||
fn send_tx_slate(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let dest_wallet = self.wallets.get_mut(&m.dest);
|
||||
let wallet = match dest_wallet {
|
||||
None => panic!("Unknown wallet destination for send_tx_slate: {:?}", m),
|
||||
Some(w) => w,
|
||||
};
|
||||
|
||||
let mut slate = serde_json::from_str(&m.body).context(
|
||||
libwallet::ErrorKind::ClientCallback("Error parsing TxWrapper".to_owned()),
|
||||
)?;
|
||||
;
|
||||
{
|
||||
let mut w = wallet.1.lock();
|
||||
w.open_with_credentials()?;
|
||||
// receive tx
|
||||
foreign::receive_tx(&mut *w, &mut slate, None, None)?;
|
||||
w.close()?;
|
||||
}
|
||||
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: m.dest,
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&slate).unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get chain height
|
||||
fn get_chain_height(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: format!("{}", self.chain.head().unwrap().height).to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get api outputs
|
||||
fn get_outputs_from_node(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let split = m.body.split(",");
|
||||
//let mut api_outputs: HashMap<pedersen::Commitment, String> = HashMap::new();
|
||||
let mut outputs: Vec<api::Output> = vec![];
|
||||
for o in split {
|
||||
let o_str = String::from(o);
|
||||
if o_str.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
let c = util::from_hex(o_str).unwrap();
|
||||
let commit = Commitment::from_vec(c);
|
||||
let out = super::get_output_local(&self.chain.clone(), &commit);
|
||||
if let Some(o) = out {
|
||||
outputs.push(o);
|
||||
}
|
||||
}
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&outputs).unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
/// get api outputs
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&mut self,
|
||||
m: WalletProxyMessage,
|
||||
) -> Result<WalletProxyMessage, libwallet::Error> {
|
||||
let split = m.body.split(",").collect::<Vec<&str>>();
|
||||
let start_index = split[0].parse::<u64>().unwrap();
|
||||
let max = split[1].parse::<u64>().unwrap();
|
||||
let ol = super::get_outputs_by_pmmr_index_local(self.chain.clone(), start_index, max);
|
||||
Ok(WalletProxyMessage {
|
||||
sender_id: "node".to_owned(),
|
||||
dest: m.sender_id,
|
||||
method: m.method,
|
||||
body: serde_json::to_string(&ol).unwrap(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct LocalWalletClient {
|
||||
/// wallet identifier for the proxy queue
|
||||
pub id: String,
|
||||
/// proxy's tx queue (receive messages from other wallets or node
|
||||
pub proxy_tx: Arc<Mutex<Sender<WalletProxyMessage>>>,
|
||||
/// my rx queue
|
||||
pub rx: Arc<Mutex<Receiver<WalletProxyMessage>>>,
|
||||
/// my tx queue
|
||||
pub tx: Arc<Mutex<Sender<WalletProxyMessage>>>,
|
||||
}
|
||||
|
||||
impl LocalWalletClient {
|
||||
/// new
|
||||
pub fn new(id: &str, proxy_rx: Sender<WalletProxyMessage>) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
LocalWalletClient {
|
||||
id: id.to_owned(),
|
||||
proxy_tx: Arc::new(Mutex::new(proxy_rx)),
|
||||
rx: Arc::new(Mutex::new(rx)),
|
||||
tx: Arc::new(Mutex::new(tx)),
|
||||
}
|
||||
}
|
||||
|
||||
/// get an instance of the send queue for other senders
|
||||
pub fn get_send_instance(&self) -> Sender<WalletProxyMessage> {
|
||||
self.tx.lock().clone()
|
||||
}
|
||||
|
||||
/// Send the slate to a listening wallet instance
|
||||
pub fn send_tx_slate_direct(
|
||||
&self,
|
||||
dest: &str,
|
||||
slate: &Slate,
|
||||
) -> Result<Slate, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: dest.to_owned(),
|
||||
method: "send_tx_slate".to_owned(),
|
||||
body: serde_json::to_string(slate).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Send TX Slate".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received send_tx_slate response: {:?}", m.clone());
|
||||
Ok(
|
||||
serde_json::from_str(&m.body).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing send_tx_slate response".to_owned(),
|
||||
))?,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl WalletCommAdapter for LocalWalletClient {
|
||||
fn supports_sync(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Send the slate to a listening wallet instance
|
||||
fn send_tx_sync(&self, dest: &str, slate: &Slate) -> Result<Slate, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: dest.to_owned(),
|
||||
method: "send_tx_slate".to_owned(),
|
||||
body: serde_json::to_string(slate).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Send TX Slate".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received send_tx_slate response: {:?}", m.clone());
|
||||
Ok(
|
||||
serde_json::from_str(&m.body).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing send_tx_slate response".to_owned(),
|
||||
))?,
|
||||
)
|
||||
}
|
||||
|
||||
fn send_tx_async(&self, _dest: &str, _slate: &Slate) -> Result<(), libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn receive_tx_async(&self, _params: &str) -> Result<Slate, libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn listen(
|
||||
&self,
|
||||
_params: HashMap<String, String>,
|
||||
_config: WalletConfig,
|
||||
_passphrase: &str,
|
||||
_account: &str,
|
||||
_node_api_secret: Option<String>,
|
||||
) -> Result<(), libwallet::Error> {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeClient for LocalWalletClient {
|
||||
fn node_url(&self) -> &str {
|
||||
"node"
|
||||
}
|
||||
fn node_api_secret(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn set_node_url(&mut self, _node_url: &str) {}
|
||||
fn set_node_api_secret(&mut self, _node_api_secret: Option<String>) {}
|
||||
/// 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> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "post_tx".to_owned(),
|
||||
body: serde_json::to_string(tx).unwrap(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"post_tx send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received post_tx response: {:?}", m.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the chain tip from a given node
|
||||
fn get_chain_height(&self) -> Result<u64, libwallet::Error> {
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_chain_height".to_owned(),
|
||||
body: "".to_owned(),
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get chain height send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
trace!("Received get_chain_height response: {:?}", m.clone());
|
||||
Ok(m.body
|
||||
.parse::<u64>()
|
||||
.context(libwallet::ErrorKind::ClientCallback(
|
||||
"Parsing get_height response".to_owned(),
|
||||
))?)
|
||||
}
|
||||
|
||||
/// Retrieve outputs from node
|
||||
fn get_outputs_from_node(
|
||||
&self,
|
||||
wallet_outputs: Vec<pedersen::Commitment>,
|
||||
) -> Result<HashMap<pedersen::Commitment, (String, u64, u64)>, libwallet::Error> {
|
||||
let query_params: Vec<String> = wallet_outputs
|
||||
.iter()
|
||||
.map(|commit| format!("{}", util::to_hex(commit.as_ref().to_vec())))
|
||||
.collect();
|
||||
let query_str = query_params.join(",");
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_outputs_from_node".to_owned(),
|
||||
body: query_str,
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get outputs from node send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
let outputs: Vec<api::Output> = serde_json::from_str(&m.body).unwrap();
|
||||
let mut api_outputs: HashMap<pedersen::Commitment, (String, u64, u64)> = HashMap::new();
|
||||
for out in outputs {
|
||||
api_outputs.insert(
|
||||
out.commit.commit(),
|
||||
(util::to_hex(out.commit.to_vec()), out.height, out.mmr_index),
|
||||
);
|
||||
}
|
||||
Ok(api_outputs)
|
||||
}
|
||||
|
||||
fn get_outputs_by_pmmr_index(
|
||||
&self,
|
||||
start_height: u64,
|
||||
max_outputs: u64,
|
||||
) -> Result<
|
||||
(
|
||||
u64,
|
||||
u64,
|
||||
Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)>,
|
||||
),
|
||||
libwallet::Error,
|
||||
> {
|
||||
// start index, max
|
||||
let query_str = format!("{},{}", start_height, max_outputs);
|
||||
let m = WalletProxyMessage {
|
||||
sender_id: self.id.clone(),
|
||||
dest: self.node_url().to_owned(),
|
||||
method: "get_outputs_by_pmmr_index".to_owned(),
|
||||
body: query_str,
|
||||
};
|
||||
{
|
||||
let p = self.proxy_tx.lock();
|
||||
p.send(m).context(libwallet::ErrorKind::ClientCallback(
|
||||
"Get outputs from node by PMMR index send".to_owned(),
|
||||
))?;
|
||||
}
|
||||
|
||||
let r = self.rx.lock();
|
||||
let m = r.recv().unwrap();
|
||||
let o: api::OutputListing = serde_json::from_str(&m.body).unwrap();
|
||||
|
||||
let mut api_outputs: Vec<(pedersen::Commitment, pedersen::RangeProof, bool, u64, u64)> =
|
||||
Vec::new();
|
||||
|
||||
for out in o.outputs {
|
||||
let is_coinbase = match out.output_type {
|
||||
api::OutputType::Coinbase => true,
|
||||
api::OutputType::Transaction => false,
|
||||
};
|
||||
api_outputs.push((
|
||||
out.commit,
|
||||
out.range_proof().unwrap(),
|
||||
is_coinbase,
|
||||
out.block_height.unwrap(),
|
||||
out.mmr_index,
|
||||
));
|
||||
}
|
||||
Ok((o.highest_index, o.last_retrieved_index, api_outputs))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user