mirror of
https://github.com/jwinterm/grin-wallet.git
synced 2026-12-05 05:13:59 +01:00
Merge upstream staging (#755 multi-LMDB backend) into contracts
Reconcile the contract feature with #755, which replaced the WalletBackend trait with a concrete WalletBackend<C,K> struct (libwallet/src/backend.rs) and removed impls/src/backends/lmdb.rs. - Port the contract module and contract API entry points from the trait form (T: WalletBackend<'a,C,K>) to the concrete struct. - Re-home next_child_for and a parent_id+log_id get_tx_log_entry onto backend.rs. - Re-apply the self-spend tx-log filters, cancel-loop, v5 payment-proof fields, and Context contract fields onto staging's rewritten files. - Adapt to fallible iter()/tx_log_iter() and self-consuming batch commit. Full suite green (53 binaries / 191 tests).
This commit is contained in:
@@ -1,817 +0,0 @@
|
||||
// Copyright 2021 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 std::cell::RefCell;
|
||||
use std::{fs, path};
|
||||
|
||||
// for writing stored transaction files
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::marker::PhantomData;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::blake2::blake2b::{Blake2b, Blake2bResult};
|
||||
|
||||
use crate::keychain::{ChildNumber, ExtKeychain, Identifier, Keychain, SwitchCommitmentType};
|
||||
use crate::store::{self, option_to_not_found, to_key, to_key_u64};
|
||||
|
||||
use crate::core::core::Transaction;
|
||||
use crate::core::ser;
|
||||
use crate::libwallet::{
|
||||
AcctPathMapping, Context, Error, NodeClient, OutputData, ScannedBlockInfo, TxLogEntry,
|
||||
WalletBackend, WalletInitStatus, WalletOutputBatch,
|
||||
};
|
||||
use crate::util::secp::constants::SECRET_KEY_SIZE;
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::{self, secp, ToHex};
|
||||
|
||||
use rand::rngs::mock::StepRng;
|
||||
use rand::thread_rng;
|
||||
|
||||
pub const DB_DIR: &str = "db";
|
||||
pub const TX_SAVE_DIR: &str = "saved_txs";
|
||||
|
||||
const OUTPUT_PREFIX: u8 = b'o';
|
||||
const DERIV_PREFIX: u8 = b'd';
|
||||
const CONFIRMED_HEIGHT_PREFIX: u8 = b'c';
|
||||
const PRIVATE_TX_CONTEXT_PREFIX: u8 = b'p';
|
||||
const TX_LOG_ENTRY_PREFIX: u8 = b't';
|
||||
const TX_LOG_ID_PREFIX: u8 = b'i';
|
||||
const ACCOUNT_PATH_MAPPING_PREFIX: u8 = b'a';
|
||||
const LAST_SCANNED_BLOCK: u8 = b'l';
|
||||
const LAST_SCANNED_KEY: &str = "LAST_SCANNED_KEY";
|
||||
const WALLET_INIT_STATUS: u8 = b'w';
|
||||
const WALLET_INIT_STATUS_KEY: &str = "WALLET_INIT_STATUS";
|
||||
|
||||
/// test to see if database files exist in the current directory. If so,
|
||||
/// use a DB backend for all operations
|
||||
pub fn wallet_db_exists(data_file_dir: &str) -> bool {
|
||||
let db_path = path::Path::new(data_file_dir).join(DB_DIR);
|
||||
db_path.exists()
|
||||
}
|
||||
|
||||
/// Helper to derive XOR keys for storing private transaction keys in the DB
|
||||
/// (blind_xor_key, nonce_xor_key)
|
||||
fn private_ctx_xor_keys<K>(
|
||||
keychain: &K,
|
||||
slate_id: &[u8],
|
||||
) -> Result<([u8; SECRET_KEY_SIZE], [u8; SECRET_KEY_SIZE]), Error>
|
||||
where
|
||||
K: Keychain,
|
||||
{
|
||||
let root_key = keychain.derive_key(0, &K::root_key_id(), SwitchCommitmentType::Regular)?;
|
||||
|
||||
// derive XOR values for storing secret values in DB
|
||||
// h(root_key|slate_id|"blind")
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
hasher.update(&slate_id[..]);
|
||||
hasher.update(&b"blind"[..]);
|
||||
let blind_xor_key = hasher.finalize();
|
||||
let mut ret_blind = [0; SECRET_KEY_SIZE];
|
||||
ret_blind.copy_from_slice(&blind_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
|
||||
|
||||
// h(root_key|slate_id|"nonce")
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
hasher.update(&slate_id[..]);
|
||||
hasher.update(&b"nonce"[..]);
|
||||
let nonce_xor_key = hasher.finalize();
|
||||
let mut ret_nonce = [0; SECRET_KEY_SIZE];
|
||||
ret_nonce.copy_from_slice(&nonce_xor_key.as_bytes()[0..SECRET_KEY_SIZE]);
|
||||
|
||||
Ok((ret_blind, ret_nonce))
|
||||
}
|
||||
|
||||
pub struct LMDBBackend<'ck, C, K>
|
||||
where
|
||||
C: NodeClient + 'ck,
|
||||
K: Keychain + 'ck,
|
||||
{
|
||||
db: store::Store,
|
||||
data_file_dir: String,
|
||||
/// Keychain
|
||||
pub keychain: Option<K>,
|
||||
/// Check value for XORed keychain seed
|
||||
pub master_checksum: Box<Option<Blake2bResult>>,
|
||||
/// Parent path to use by default for output operations
|
||||
parent_key_id: Identifier,
|
||||
/// wallet to node client
|
||||
w2n_client: C,
|
||||
///phantom
|
||||
_phantom: &'ck PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<'ck, C, K> LMDBBackend<'ck, C, K>
|
||||
where
|
||||
C: NodeClient + 'ck,
|
||||
K: Keychain + 'ck,
|
||||
{
|
||||
pub fn new(data_file_dir: &str, n_client: C) -> Result<Self, Error> {
|
||||
let db_path = path::Path::new(data_file_dir).join(DB_DIR);
|
||||
fs::create_dir_all(&db_path).expect("Couldn't create wallet backend directory!");
|
||||
|
||||
let stored_tx_path = path::Path::new(data_file_dir).join(TX_SAVE_DIR);
|
||||
fs::create_dir_all(&stored_tx_path)
|
||||
.expect("Couldn't create wallet backend tx storage directory!");
|
||||
|
||||
let store = store::Store::new(db_path.to_str().unwrap(), None, Some(DB_DIR), None)?;
|
||||
|
||||
// Make sure default wallet derivation path always exists
|
||||
// as well as path (so it can be retrieved by batches to know where to store
|
||||
// completed transactions, for reference
|
||||
let default_account = AcctPathMapping {
|
||||
label: "default".to_owned(),
|
||||
path: LMDBBackend::<C, K>::default_path(),
|
||||
};
|
||||
let acct_key = to_key(
|
||||
ACCOUNT_PATH_MAPPING_PREFIX,
|
||||
&mut default_account.label.as_bytes().to_vec(),
|
||||
);
|
||||
|
||||
{
|
||||
let batch = store.batch()?;
|
||||
batch.put_ser(&acct_key, &default_account)?;
|
||||
batch.commit()?;
|
||||
}
|
||||
|
||||
let res = LMDBBackend {
|
||||
db: store,
|
||||
data_file_dir: data_file_dir.to_owned(),
|
||||
keychain: None,
|
||||
master_checksum: Box::new(None),
|
||||
parent_key_id: LMDBBackend::<C, K>::default_path(),
|
||||
w2n_client: n_client,
|
||||
_phantom: &PhantomData,
|
||||
};
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn default_path() -> Identifier {
|
||||
// return the default parent wallet path, corresponding to the default account
|
||||
// in the BIP32 spec. Parent is account 0 at level 2, child output identifiers
|
||||
// are all at level 3
|
||||
ExtKeychain::derive_key_id(2, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
/// Just test to see if database files exist in the current directory. If
|
||||
/// so, use a DB backend for all operations
|
||||
pub fn exists(data_file_dir: &str) -> bool {
|
||||
let db_path = path::Path::new(data_file_dir).join(DB_DIR);
|
||||
db_path.exists()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ck, C, K> WalletBackend<'ck, C, K> for LMDBBackend<'ck, C, K>
|
||||
where
|
||||
C: NodeClient + 'ck,
|
||||
K: Keychain + 'ck,
|
||||
{
|
||||
/// Set the keychain, which should already have been opened
|
||||
fn set_keychain(
|
||||
&mut self,
|
||||
mut k: Box<K>,
|
||||
mask: bool,
|
||||
use_test_rng: bool,
|
||||
) -> Result<Option<SecretKey>, Error> {
|
||||
// store hash of master key, so it can be verified later after unmasking
|
||||
let root_key = k.derive_key(0, &K::root_key_id(), SwitchCommitmentType::Regular)?;
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
self.master_checksum = Box::new(Some(hasher.finalize()));
|
||||
|
||||
let mask_value = {
|
||||
match mask {
|
||||
true => {
|
||||
// Random value that must be XORed against the stored wallet seed
|
||||
// before it is used
|
||||
let mask_value = match use_test_rng {
|
||||
true => {
|
||||
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
|
||||
secp::key::SecretKey::new(&k.secp(), &mut test_rng)
|
||||
}
|
||||
false => secp::key::SecretKey::new(&k.secp(), &mut thread_rng()),
|
||||
};
|
||||
k.mask_master_key(&mask_value)?;
|
||||
Some(mask_value)
|
||||
}
|
||||
false => None,
|
||||
}
|
||||
};
|
||||
|
||||
self.keychain = Some(*k);
|
||||
Ok(mask_value)
|
||||
}
|
||||
|
||||
/// Close wallet
|
||||
fn close(&mut self) -> Result<(), Error> {
|
||||
self.keychain = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the keychain being used, cloned with XORed token value
|
||||
/// for temporary use
|
||||
fn keychain(&self, mask: Option<&SecretKey>) -> Result<K, Error> {
|
||||
match self.keychain.as_ref() {
|
||||
Some(k) => {
|
||||
let mut k_masked = k.clone();
|
||||
if let Some(m) = mask {
|
||||
k_masked.mask_master_key(m)?;
|
||||
}
|
||||
// Check if master seed is what is expected (especially if it's been xored)
|
||||
let root_key =
|
||||
k_masked.derive_key(0, &K::root_key_id(), SwitchCommitmentType::Regular)?;
|
||||
let mut hasher = Blake2b::new(SECRET_KEY_SIZE);
|
||||
hasher.update(&root_key.0[..]);
|
||||
if *self.master_checksum != Some(hasher.finalize()) {
|
||||
error!("Supplied keychain mask is invalid");
|
||||
return Err(Error::InvalidKeychainMask);
|
||||
}
|
||||
Ok(k_masked)
|
||||
}
|
||||
None => Err(Error::KeychainDoesntExist),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the node client being used
|
||||
fn w2n_client(&mut self) -> &mut C {
|
||||
&mut self.w2n_client
|
||||
}
|
||||
|
||||
/// return the version of the commit for caching
|
||||
fn calc_commit_for_cache(
|
||||
&mut self,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
amount: u64,
|
||||
id: &Identifier,
|
||||
) -> Result<Option<String>, Error> {
|
||||
//TODO: Check if this is really necessary, it's the only thing
|
||||
//preventing removing the need for config in the wallet backend
|
||||
/*if self.config.no_commit_cache == Some(true) {
|
||||
Ok(None)
|
||||
} else {*/
|
||||
Ok(Some(
|
||||
self.keychain(keychain_mask)?
|
||||
.commit(amount, &id, SwitchCommitmentType::Regular)?
|
||||
.0
|
||||
.to_vec()
|
||||
.to_hex(), // TODO: proper support for different switch commitment schemes
|
||||
))
|
||||
/*}*/
|
||||
}
|
||||
|
||||
/// Set parent path by account name
|
||||
fn set_parent_key_id_by_name(&mut self, label: &str) -> Result<(), Error> {
|
||||
let label = label.to_owned();
|
||||
let res = self.acct_path_iter().find(|l| l.label == label);
|
||||
if let Some(a) = res {
|
||||
self.set_parent_key_id(a.path);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnknownAccountLabel(label))
|
||||
}
|
||||
}
|
||||
|
||||
/// set parent path
|
||||
fn set_parent_key_id(&mut self, id: Identifier) {
|
||||
self.parent_key_id = id;
|
||||
}
|
||||
|
||||
fn parent_key_id(&mut self) -> Identifier {
|
||||
self.parent_key_id.clone()
|
||||
}
|
||||
|
||||
fn get(&self, id: &Identifier, mmr_index: &Option<u64>) -> Result<OutputData, Error> {
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
option_to_not_found(self.db.get_ser(&key, None), || format!("Key Id: {}", id))
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = OutputData> + 'a> {
|
||||
let protocol_version = self.db.protocol_version();
|
||||
let prefix_iter = self.db.iter(&[OUTPUT_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
// TODO: I think this can be deleted
|
||||
// fn get_tx_log_entry(&self, u: &Uuid) -> Result<Option<TxLogEntry>, Error> {
|
||||
// let key = to_key(TX_LOG_ENTRY_PREFIX, &mut u.as_bytes().to_vec());
|
||||
|
||||
// self.db.get_ser(&key, None).map_err(|e| e.into())
|
||||
// }
|
||||
|
||||
fn get_tx_log_entry(
|
||||
&self,
|
||||
parent_id: Identifier,
|
||||
log_id: u32,
|
||||
) -> Result<Option<TxLogEntry>, Error> {
|
||||
let tx_log_key = to_key_u64(
|
||||
TX_LOG_ENTRY_PREFIX,
|
||||
&mut parent_id.to_bytes().to_vec(),
|
||||
log_id as u64,
|
||||
);
|
||||
self.db.get_ser(&tx_log_key, None).map_err(|e| e.into())
|
||||
/*
|
||||
fn save_tx_log_entry(
|
||||
&mut self,
|
||||
tx_in: TxLogEntry,
|
||||
parent_id: &Identifier,
|
||||
) -> Result<(), Error> {
|
||||
let tx_log_key = to_key_u64(
|
||||
TX_LOG_ENTRY_PREFIX,
|
||||
&mut parent_id.to_bytes().to_vec(),
|
||||
tx_in.id as u64,
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&tx_log_key, &tx_in)?;
|
||||
*/
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn tx_log_iter<'a>(&'a self) -> Box<dyn Iterator<Item = TxLogEntry> + 'a> {
|
||||
let protocol_version = self.db.protocol_version();
|
||||
let prefix_iter = self.db.iter(&[TX_LOG_ENTRY_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
fn get_private_context(
|
||||
&mut self,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
slate_id: &[u8],
|
||||
) -> Result<Context, Error> {
|
||||
let ctx_key = to_key_u64(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec(), 0);
|
||||
let (blind_xor_key, nonce_xor_key) =
|
||||
private_ctx_xor_keys(&self.keychain(keychain_mask)?, slate_id)?;
|
||||
|
||||
// A missing context surfaces as Error::NotFoundErr (via the grin_store
|
||||
// conversion), letting callers distinguish it from other store errors.
|
||||
let mut ctx: Context = option_to_not_found(self.db.get_ser(&ctx_key, None), || {
|
||||
format!("Slate id: {:x?}", slate_id.to_vec())
|
||||
})?;
|
||||
|
||||
for i in 0..SECRET_KEY_SIZE {
|
||||
ctx.sec_key.0[i] ^= blind_xor_key[i];
|
||||
ctx.sec_nonce.0[i] ^= nonce_xor_key[i];
|
||||
}
|
||||
|
||||
Ok(ctx)
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn acct_path_iter<'a>(&'a self) -> Box<dyn Iterator<Item = AcctPathMapping> + 'a> {
|
||||
let protocol_version = self.db.protocol_version();
|
||||
let prefix_iter = self
|
||||
.db
|
||||
.iter(&[ACCOUNT_PATH_MAPPING_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
fn get_acct_path(&self, label: String) -> Result<Option<AcctPathMapping>, Error> {
|
||||
let acct_key = to_key(ACCOUNT_PATH_MAPPING_PREFIX, &mut label.as_bytes().to_vec());
|
||||
self.db.get_ser(&acct_key, None).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn store_tx(&self, uuid: &str, tx: &Transaction) -> Result<(), Error> {
|
||||
let filename = format!("{}.grintx", uuid);
|
||||
let path = path::Path::new(&self.data_file_dir)
|
||||
.join(TX_SAVE_DIR)
|
||||
.join(filename);
|
||||
let path_buf = Path::new(&path).to_path_buf();
|
||||
let mut stored_tx = File::create(path_buf)?;
|
||||
let tx_hex = ser::ser_vec(tx, ser::ProtocolVersion(1)).unwrap().to_hex();
|
||||
stored_tx.write_all(&tx_hex.as_bytes())?;
|
||||
stored_tx.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_stored_tx(&self, uuid: &str) -> Result<Option<Transaction>, Error> {
|
||||
let filename = format!("{}.grintx", uuid);
|
||||
let path = path::Path::new(&self.data_file_dir)
|
||||
.join(TX_SAVE_DIR)
|
||||
.join(filename);
|
||||
let tx_file = Path::new(&path).to_path_buf();
|
||||
let mut tx_f = File::open(tx_file)?;
|
||||
let mut content = String::new();
|
||||
tx_f.read_to_string(&mut content)?;
|
||||
let tx_bin = util::from_hex(&content).unwrap();
|
||||
Ok(Some(
|
||||
ser::deserialize(
|
||||
&mut &tx_bin[..],
|
||||
ser::ProtocolVersion(1),
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
))
|
||||
}
|
||||
|
||||
fn batch<'a>(
|
||||
&'a mut self,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<Box<dyn WalletOutputBatch<K> + 'a>, Error> {
|
||||
Ok(Box::new(Batch {
|
||||
_store: self,
|
||||
db: RefCell::new(Some(self.db.batch()?)),
|
||||
keychain: Some(self.keychain(keychain_mask)?),
|
||||
}))
|
||||
}
|
||||
|
||||
fn batch_no_mask<'a>(&'a mut self) -> Result<Box<dyn WalletOutputBatch<K> + 'a>, Error> {
|
||||
Ok(Box::new(Batch {
|
||||
_store: self,
|
||||
db: RefCell::new(Some(self.db.batch()?)),
|
||||
keychain: None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn current_child_index<'a>(&mut self, parent_key_id: &Identifier) -> Result<u32, Error> {
|
||||
let index = {
|
||||
let batch = self.db.batch()?;
|
||||
let deriv_key = to_key(DERIV_PREFIX, &mut parent_key_id.to_bytes().to_vec());
|
||||
match batch.get_ser(&deriv_key, None)? {
|
||||
Some(idx) => idx,
|
||||
None => 0,
|
||||
}
|
||||
};
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn next_child<'a>(&mut self, keychain_mask: Option<&SecretKey>) -> Result<Identifier, Error> {
|
||||
let parent_key_id = self.parent_key_id.clone();
|
||||
self.next_child_for(&parent_key_id, keychain_mask)
|
||||
}
|
||||
|
||||
fn next_child_for<'a>(
|
||||
&mut self,
|
||||
parent_key_id: &Identifier,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<Identifier, Error> {
|
||||
let mut deriv_idx = {
|
||||
let batch = self.db.batch()?;
|
||||
let deriv_key = to_key(DERIV_PREFIX, &mut parent_key_id.to_bytes().to_vec());
|
||||
match batch.get_ser(&deriv_key, None)? {
|
||||
Some(idx) => idx,
|
||||
None => 0,
|
||||
}
|
||||
};
|
||||
let mut return_path = parent_key_id.to_path();
|
||||
return_path.depth += 1;
|
||||
return_path.path[return_path.depth as usize - 1] = ChildNumber::from(deriv_idx);
|
||||
deriv_idx += 1;
|
||||
let mut batch = self.batch(keychain_mask)?;
|
||||
batch.save_child_index(parent_key_id, deriv_idx)?;
|
||||
batch.commit()?;
|
||||
Ok(Identifier::from_path(&return_path))
|
||||
}
|
||||
|
||||
fn last_confirmed_height<'a>(&mut self) -> Result<u64, Error> {
|
||||
let batch = self.db.batch()?;
|
||||
let height_key = to_key(
|
||||
CONFIRMED_HEIGHT_PREFIX,
|
||||
&mut self.parent_key_id.to_bytes().to_vec(),
|
||||
);
|
||||
let last_confirmed_height = match batch.get_ser(&height_key, None)? {
|
||||
Some(h) => h,
|
||||
None => 0,
|
||||
};
|
||||
Ok(last_confirmed_height)
|
||||
}
|
||||
|
||||
fn last_scanned_block<'a>(&mut self) -> Result<ScannedBlockInfo, Error> {
|
||||
let batch = self.db.batch()?;
|
||||
let scanned_block_key = to_key(
|
||||
LAST_SCANNED_BLOCK,
|
||||
&mut LAST_SCANNED_KEY.as_bytes().to_vec(),
|
||||
);
|
||||
let last_scanned_block = match batch.get_ser(&scanned_block_key, None)? {
|
||||
Some(b) => b,
|
||||
None => ScannedBlockInfo {
|
||||
height: 0,
|
||||
hash: "".to_owned(),
|
||||
start_pmmr_index: 0,
|
||||
last_pmmr_index: 0,
|
||||
},
|
||||
};
|
||||
Ok(last_scanned_block)
|
||||
}
|
||||
|
||||
fn init_status<'a>(&mut self) -> Result<WalletInitStatus, Error> {
|
||||
let batch = self.db.batch()?;
|
||||
let init_status_key = to_key(
|
||||
WALLET_INIT_STATUS,
|
||||
&mut WALLET_INIT_STATUS_KEY.as_bytes().to_vec(),
|
||||
);
|
||||
let status = match batch.get_ser(&init_status_key, None)? {
|
||||
Some(s) => s,
|
||||
None => WalletInitStatus::InitComplete,
|
||||
};
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
/// An atomic batch in which all changes can be committed all at once or
|
||||
/// discarded on error.
|
||||
pub struct Batch<'a, C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
_store: &'a LMDBBackend<'a, C, K>,
|
||||
db: RefCell<Option<store::Batch<'a>>>,
|
||||
/// Keychain
|
||||
keychain: Option<K>,
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
impl<'a, C, K> WalletOutputBatch<K> for Batch<'a, C, K>
|
||||
where
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
fn keychain(&mut self) -> &mut K {
|
||||
self.keychain.as_mut().unwrap()
|
||||
}
|
||||
|
||||
fn save(&mut self, out: OutputData) -> Result<(), Error> {
|
||||
// Save the output data to the db.
|
||||
{
|
||||
let key = match out.mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut out.key_id.to_bytes().to_vec(), i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut out.key_id.to_bytes().to_vec()),
|
||||
};
|
||||
self.db.borrow().as_ref().unwrap().put_ser(&key, &out)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get(&self, id: &Identifier, mmr_index: &Option<u64>) -> Result<OutputData, Error> {
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
option_to_not_found(
|
||||
self.db.borrow().as_ref().unwrap().get_ser(&key, None),
|
||||
|| format!("Key ID: {}", id),
|
||||
)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn iter(&self) -> Box<dyn Iterator<Item = OutputData>> {
|
||||
let db = self.db.borrow();
|
||||
let db = db.as_ref().unwrap();
|
||||
let protocol_version = db.protocol_version();
|
||||
let prefix_iter = db.iter(&[OUTPUT_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
fn delete(&mut self, id: &Identifier, mmr_index: &Option<u64>) -> Result<(), Error> {
|
||||
// Delete the output data.
|
||||
{
|
||||
let key = match mmr_index {
|
||||
Some(i) => to_key_u64(OUTPUT_PREFIX, &mut id.to_bytes().to_vec(), *i),
|
||||
None => to_key(OUTPUT_PREFIX, &mut id.to_bytes().to_vec()),
|
||||
};
|
||||
let _ = self.db.borrow().as_ref().unwrap().delete(&key);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_tx_log_id(&mut self, parent_key_id: &Identifier) -> Result<u32, Error> {
|
||||
let tx_id_key = to_key(TX_LOG_ID_PREFIX, &mut parent_key_id.to_bytes().to_vec());
|
||||
let last_tx_log_id = match self
|
||||
.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.get_ser(&tx_id_key, None)?
|
||||
{
|
||||
Some(t) => t,
|
||||
None => 0,
|
||||
};
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&tx_id_key, &(last_tx_log_id + 1))?;
|
||||
Ok(last_tx_log_id)
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn tx_log_iter(&self) -> Box<dyn Iterator<Item = TxLogEntry>> {
|
||||
let db = self.db.borrow();
|
||||
let db = db.as_ref().unwrap();
|
||||
let protocol_version = db.protocol_version();
|
||||
let prefix_iter = db.iter(&[TX_LOG_ENTRY_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
fn save_last_confirmed_height(
|
||||
&mut self,
|
||||
parent_key_id: &Identifier,
|
||||
height: u64,
|
||||
) -> Result<(), Error> {
|
||||
let height_key = to_key(
|
||||
CONFIRMED_HEIGHT_PREFIX,
|
||||
&mut parent_key_id.to_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&height_key, &height)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_last_scanned_block(&mut self, block_info: ScannedBlockInfo) -> Result<(), Error> {
|
||||
let pmmr_index_key = to_key(
|
||||
LAST_SCANNED_BLOCK,
|
||||
&mut LAST_SCANNED_KEY.as_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&pmmr_index_key, &block_info)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_init_status(&mut self, value: WalletInitStatus) -> Result<(), Error> {
|
||||
let init_status_key = to_key(
|
||||
WALLET_INIT_STATUS,
|
||||
&mut WALLET_INIT_STATUS_KEY.as_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&init_status_key, &value)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_child_index(&mut self, parent_id: &Identifier, child_n: u32) -> Result<(), Error> {
|
||||
let deriv_key = to_key(DERIV_PREFIX, &mut parent_id.to_bytes().to_vec());
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&deriv_key, &child_n)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_tx_log_entry(
|
||||
&mut self,
|
||||
tx_in: TxLogEntry,
|
||||
parent_id: &Identifier,
|
||||
) -> Result<(), Error> {
|
||||
let tx_log_key = to_key_u64(
|
||||
TX_LOG_ENTRY_PREFIX,
|
||||
&mut parent_id.to_bytes().to_vec(),
|
||||
tx_in.id as u64,
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&tx_log_key, &tx_in)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_tx_log_entry(&mut self, tx_id: u32, parent_id: &Identifier) -> Result<(), Error> {
|
||||
let tx_log_key = to_key_u64(
|
||||
TX_LOG_ENTRY_PREFIX,
|
||||
&mut parent_id.to_bytes().to_vec(),
|
||||
tx_id as u64,
|
||||
);
|
||||
self.db.borrow().as_ref().unwrap().delete(&tx_log_key)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_acct_path(&mut self, mapping: AcctPathMapping) -> Result<(), Error> {
|
||||
let acct_key = to_key(
|
||||
ACCOUNT_PATH_MAPPING_PREFIX,
|
||||
&mut mapping.label.as_bytes().to_vec(),
|
||||
);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&acct_key, &mapping)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO - fix this awkward conversion between PrefixIterator and our Box<dyn Iterator>
|
||||
fn acct_path_iter(&self) -> Box<dyn Iterator<Item = AcctPathMapping>> {
|
||||
let db = self.db.borrow();
|
||||
let db = db.as_ref().unwrap();
|
||||
let protocol_version = db.protocol_version();
|
||||
let prefix_iter = db.iter(&[ACCOUNT_PATH_MAPPING_PREFIX], move |_, mut v| {
|
||||
ser::deserialize(
|
||||
&mut v,
|
||||
protocol_version,
|
||||
ser::DeserializationMode::default(),
|
||||
)
|
||||
.map_err(From::from)
|
||||
});
|
||||
let iter = prefix_iter.expect("deserialize").into_iter();
|
||||
Box::new(iter)
|
||||
}
|
||||
|
||||
fn lock_output(&mut self, out: &mut OutputData) -> Result<(), Error> {
|
||||
out.lock();
|
||||
self.save(out.clone())
|
||||
}
|
||||
|
||||
fn save_private_context(&mut self, slate_id: &[u8], ctx: &Context) -> Result<(), Error> {
|
||||
let ctx_key = to_key_u64(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec(), 0);
|
||||
let (blind_xor_key, nonce_xor_key) = private_ctx_xor_keys(self.keychain(), slate_id)?;
|
||||
|
||||
let mut s_ctx = ctx.clone();
|
||||
for i in 0..SECRET_KEY_SIZE {
|
||||
s_ctx.sec_key.0[i] ^= blind_xor_key[i];
|
||||
s_ctx.sec_nonce.0[i] ^= nonce_xor_key[i];
|
||||
}
|
||||
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.put_ser(&ctx_key, &s_ctx)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_private_context(&mut self, slate_id: &[u8]) -> Result<(), Error> {
|
||||
let ctx_key = to_key_u64(PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec(), 0);
|
||||
self.db
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.delete(&ctx_key)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn commit(&self) -> Result<(), Error> {
|
||||
let db = self.db.replace(None);
|
||||
db.unwrap().commit()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// Copyright 2021 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.
|
||||
|
||||
mod lmdb;
|
||||
|
||||
pub use self::lmdb::{wallet_db_exists, LMDBBackend};
|
||||
+9
-16
@@ -28,14 +28,12 @@ use grin_api as api;
|
||||
use grin_chain as chain;
|
||||
use grin_core as core;
|
||||
use grin_keychain as keychain;
|
||||
use grin_store as store;
|
||||
use grin_util as util;
|
||||
use grin_wallet_libwallet as libwallet;
|
||||
|
||||
use grin_wallet_config as config;
|
||||
|
||||
mod adapters;
|
||||
mod backends;
|
||||
mod client_utils;
|
||||
mod error;
|
||||
mod lifecycle;
|
||||
@@ -47,7 +45,6 @@ pub use crate::adapters::{
|
||||
HttpSlateSender, PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver,
|
||||
SlateSender,
|
||||
};
|
||||
pub use crate::backends::{wallet_db_exists, LMDBBackend};
|
||||
pub use crate::error::Error;
|
||||
pub use crate::lifecycle::DefaultLCProvider;
|
||||
pub use crate::node_clients::HTTPNodeClient;
|
||||
@@ -57,35 +54,31 @@ use crate::keychain::{ExtKeychain, Keychain};
|
||||
use libwallet::{NodeClient, WalletInst, WalletLCProvider};
|
||||
|
||||
/// Main wallet instance
|
||||
pub struct DefaultWalletImpl<'a, C>
|
||||
pub struct DefaultWalletImpl<C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
C: NodeClient,
|
||||
{
|
||||
lc_provider: DefaultLCProvider<'a, C, ExtKeychain>,
|
||||
lc_provider: DefaultLCProvider<C, ExtKeychain>,
|
||||
}
|
||||
|
||||
impl<'a, C> DefaultWalletImpl<'a, C>
|
||||
impl<C> DefaultWalletImpl<C>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
C: NodeClient,
|
||||
{
|
||||
pub fn new(node_client: C) -> Result<Self, Error> {
|
||||
let lc_provider = DefaultLCProvider::new(node_client);
|
||||
Ok(DefaultWalletImpl {
|
||||
lc_provider: lc_provider,
|
||||
})
|
||||
Ok(DefaultWalletImpl { lc_provider })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, L, C, K> WalletInst<'a, L, C, K> for DefaultWalletImpl<'a, C>
|
||||
impl<'a, L, C, K> WalletInst<'a, L, C, K> for DefaultWalletImpl<C>
|
||||
where
|
||||
DefaultLCProvider<'a, C, ExtKeychain>: WalletLCProvider<'a, C, K>,
|
||||
DefaultLCProvider<C, ExtKeychain>: WalletLCProvider<'a, C, K>,
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
fn lc_provider(
|
||||
&mut self,
|
||||
) -> Result<&mut (dyn WalletLCProvider<'a, C, K> + 'a), libwallet::Error> {
|
||||
fn lc_provider(&mut self) -> Result<&mut dyn WalletLCProvider<'a, C, K>, libwallet::Error> {
|
||||
Ok(&mut self.lc_provider)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,13 +23,12 @@ use crate::libwallet::{Error, NodeClient, WalletBackend, WalletInitStatus, Walle
|
||||
use crate::lifecycle::seed::WalletSeed;
|
||||
use crate::util::secp::key::SecretKey;
|
||||
use crate::util::ZeroingString;
|
||||
use crate::LMDBBackend;
|
||||
use grin_util::logger::LoggingConfig;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
|
||||
// Helper fuction to format paths according to OS, avoids bugs on Linux
|
||||
/// Helper function to format paths according to OS, avoids bugs on Linux
|
||||
pub fn fmt_path(path: String) -> String {
|
||||
let sep = &MAIN_SEPARATOR.to_string();
|
||||
let path = path.replace("/", &sep);
|
||||
@@ -37,20 +36,20 @@ pub fn fmt_path(path: String) -> String {
|
||||
path
|
||||
}
|
||||
|
||||
pub struct DefaultLCProvider<'a, C, K>
|
||||
pub struct DefaultLCProvider<C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
data_dir: String,
|
||||
node_client: C,
|
||||
backend: Option<Box<dyn WalletBackend<'a, C, K> + 'a>>,
|
||||
backend: Option<WalletBackend<C, K>>,
|
||||
}
|
||||
|
||||
impl<'a, C, K> DefaultLCProvider<'a, C, K>
|
||||
impl<C, K> DefaultLCProvider<C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
C: NodeClient,
|
||||
K: Keychain,
|
||||
{
|
||||
/// Create new provider
|
||||
pub fn new(node_client: C) -> Self {
|
||||
@@ -62,7 +61,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, C, K> WalletLCProvider<'a, C, K> for DefaultLCProvider<'a, C, K>
|
||||
impl<'a, C, K> WalletLCProvider<'a, C, K> for DefaultLCProvider<C, K>
|
||||
where
|
||||
C: NodeClient + 'a,
|
||||
K: Keychain + 'a,
|
||||
@@ -217,8 +216,8 @@ where
|
||||
Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned())
|
||||
})?;
|
||||
info!("Wallet seed file created");
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
let mut wallet: WalletBackend<C, K> =
|
||||
match WalletBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
error!("{}", msg);
|
||||
@@ -247,8 +246,8 @@ where
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = fmt_path(data_dir_name.to_str().unwrap().to_string());
|
||||
let mut wallet: LMDBBackend<'a, C, K> =
|
||||
match LMDBBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
let mut wallet: WalletBackend<C, K> =
|
||||
match WalletBackend::new(&data_dir_name, self.node_client.clone()) {
|
||||
Err(e) => {
|
||||
let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name);
|
||||
return Err(Error::Lifecycle(msg));
|
||||
@@ -262,8 +261,8 @@ where
|
||||
.derive_keychain(global::is_testnet())
|
||||
.map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?;
|
||||
|
||||
let mask = wallet.set_keychain(Box::new(keychain), create_mask, use_test_rng)?;
|
||||
self.backend = Some(Box::new(wallet));
|
||||
let mask = wallet.set_keychain(keychain, create_mask, use_test_rng)?;
|
||||
self.backend = Some(wallet);
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
@@ -329,8 +328,7 @@ where
|
||||
let mut data_dir_name = PathBuf::from(self.data_dir.clone());
|
||||
data_dir_name.push(GRIN_WALLET_DIR);
|
||||
let data_dir_name = data_dir_name.to_str().unwrap();
|
||||
// get seed for later check
|
||||
|
||||
// Get seed for later check
|
||||
let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old)
|
||||
.map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?;
|
||||
let orig_mnemonic = orig_wallet_seed
|
||||
@@ -366,7 +364,7 @@ where
|
||||
.to_string();
|
||||
return Err(Error::Lifecycle(msg));
|
||||
}
|
||||
// Removin
|
||||
// Removing old file
|
||||
info!("Password change confirmed, removing old seed file.");
|
||||
fs::remove_file(backup_name).map_err(|e| Error::IO(e.to_string()))?;
|
||||
|
||||
@@ -383,13 +381,13 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wallet_inst(&mut self) -> Result<&mut Box<dyn WalletBackend<'a, C, K> + 'a>, Error> {
|
||||
fn wallet_inst(&mut self) -> Result<&mut WalletBackend<C, K>, Error> {
|
||||
match self.backend.as_mut() {
|
||||
None => {
|
||||
let msg = "Wallet has not been opened".into();
|
||||
Err(Error::Lifecycle(msg))
|
||||
}
|
||||
Some(_) => Ok(&mut *self.backend.as_mut().unwrap()),
|
||||
Some(b) => Ok(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ use ring::aead;
|
||||
use ring::pbkdf2;
|
||||
|
||||
use crate::keychain::{mnemonic, Keychain};
|
||||
use crate::lifecycle::default::fmt_path;
|
||||
use crate::util::{self, ToHex};
|
||||
use crate::Error;
|
||||
|
||||
@@ -56,13 +57,6 @@ impl WalletSeed {
|
||||
self.0.to_vec().to_hex()
|
||||
}
|
||||
|
||||
// Helper fuction to format paths according to OS, avoids bugs on Linux
|
||||
pub fn fmt_path(path: String) -> String {
|
||||
let sep = &MAIN_SEPARATOR.to_string();
|
||||
let path = path.replace("/", &sep);
|
||||
let path = path.replace("\\", &sep);
|
||||
path
|
||||
}
|
||||
pub fn to_mnemonic(&self) -> Result<String, Error> {
|
||||
let result = mnemonic::from_entropy(&self.0);
|
||||
match result {
|
||||
@@ -105,7 +99,7 @@ impl WalletSeed {
|
||||
pub fn seed_file_exists(data_file_dir: &str) -> Result<bool, Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
@@ -145,7 +139,7 @@ impl WalletSeed {
|
||||
) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
@@ -184,11 +178,11 @@ impl WalletSeed {
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
let data_file_dir = Self::fmt_path(data_file_dir.to_string());
|
||||
let data_file_dir = fmt_path(data_file_dir.to_string());
|
||||
warn!("Generating wallet seed file at: {}", seed_file_path);
|
||||
let exists = WalletSeed::seed_file_exists(&data_file_dir)?;
|
||||
if exists && !test_mode {
|
||||
@@ -219,7 +213,7 @@ impl WalletSeed {
|
||||
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
@@ -247,7 +241,7 @@ impl WalletSeed {
|
||||
pub fn delete_seed_file(data_file_dir: &str) -> Result<(), Error> {
|
||||
let seed_file_path = &format!(
|
||||
"{}{}{}",
|
||||
Self::fmt_path(data_file_dir.to_string()),
|
||||
fmt_path(data_file_dir.to_string()),
|
||||
MAIN_SEPARATOR,
|
||||
SEED_FILE,
|
||||
);
|
||||
|
||||
@@ -18,7 +18,6 @@ use crate::chain::Chain;
|
||||
use crate::core;
|
||||
use crate::core::core::{Output, Transaction, TxKernel};
|
||||
use crate::core::{consensus, global, pow};
|
||||
use crate::keychain;
|
||||
use crate::libwallet;
|
||||
use crate::libwallet::api_impl::{foreign, owner};
|
||||
use crate::libwallet::{
|
||||
@@ -28,6 +27,7 @@ use crate::util::secp::key::SecretKey;
|
||||
use crate::util::secp::pedersen;
|
||||
use crate::util::Mutex;
|
||||
use chrono::Duration;
|
||||
use grin_keychain::Keychain;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
@@ -36,7 +36,7 @@ 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> {
|
||||
fn get_output_local(chain: &Chain, commit: pedersen::Commitment) -> Option<api::Output> {
|
||||
if chain.get_unspent(commit).unwrap().is_some() {
|
||||
let block_height = chain.get_header_for_output(commit).unwrap().height;
|
||||
let output_pos = chain.get_output_pos(&commit).unwrap_or(0);
|
||||
@@ -48,7 +48,7 @@ fn get_output_local(chain: &chain::Chain, commit: pedersen::Commitment) -> Optio
|
||||
|
||||
/// Get a kernel from the chain locally
|
||||
fn get_kernel_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
chain: Arc<Chain>,
|
||||
excess: &pedersen::Commitment,
|
||||
min_height: Option<u64>,
|
||||
max_height: Option<u64>,
|
||||
@@ -65,7 +65,7 @@ fn get_kernel_local(
|
||||
|
||||
/// get output listing traversing pmmr from local
|
||||
fn get_outputs_by_pmmr_index_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
chain: Arc<Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
max: u64,
|
||||
@@ -86,7 +86,7 @@ fn get_outputs_by_pmmr_index_local(
|
||||
|
||||
/// get output listing in a given block range
|
||||
fn height_range_to_pmmr_indices_local(
|
||||
chain: Arc<chain::Chain>,
|
||||
chain: Arc<Chain>,
|
||||
start_index: u64,
|
||||
end_index: Option<u64>,
|
||||
) -> api::OutputListing {
|
||||
@@ -147,13 +147,13 @@ pub fn create_block_for_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
prev: core::core::BlockHeader,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<core::core::Block, libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
// build block fees
|
||||
let fee_amt = txs.iter().map(|tx| tx.fee()).sum();
|
||||
@@ -166,7 +166,7 @@ where
|
||||
let coinbase_tx = {
|
||||
let mut w_lock = wallet.lock();
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
foreign::build_coinbase(&mut **w, keychain_mask, &block_fees, false)?
|
||||
foreign::build_coinbase(w, keychain_mask, &block_fees, false)?
|
||||
};
|
||||
let block = create_block_with_reward(chain, prev, txs, coinbase_tx.output, coinbase_tx.kernel);
|
||||
Ok(block)
|
||||
@@ -178,13 +178,13 @@ where
|
||||
pub fn award_block_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
txs: &[Transaction],
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
) -> Result<(), libwallet::Error>
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let prev = chain.head_header().unwrap();
|
||||
let block = create_block_for_wallet(chain, prev, txs, wallet, keychain_mask)?;
|
||||
@@ -200,7 +200,7 @@ pub fn process_block(chain: &Chain, block: core::core::Block) {
|
||||
/// Award a blocks to a wallet directly
|
||||
pub fn award_blocks_to_wallet<'a, L, C, K>(
|
||||
chain: &Chain,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<&SecretKey>,
|
||||
number: usize,
|
||||
pause_between: bool,
|
||||
@@ -208,7 +208,7 @@ pub fn award_blocks_to_wallet<'a, L, C, K>(
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
for _ in 0..number {
|
||||
award_block_to_wallet(chain, &[], wallet.clone(), keychain_mask)?;
|
||||
@@ -231,7 +231,7 @@ pub fn send_to_dest<'a, L, C, K>(
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let slate = {
|
||||
let mut w_lock = wallet.lock();
|
||||
@@ -245,10 +245,10 @@ where
|
||||
selection_strategy_is_use_all: true,
|
||||
..Default::default()
|
||||
};
|
||||
let slate_i = owner::init_send_tx(&mut **w, keychain_mask, args, test_mode)?;
|
||||
let slate_i = owner::init_send_tx(w, keychain_mask, args, test_mode)?;
|
||||
let slate = client.send_tx_slate_direct(dest, &slate_i)?;
|
||||
owner::tx_lock_outputs(&mut **w, keychain_mask, &slate)?;
|
||||
owner::finalize_tx(&mut **w, keychain_mask, &slate)?
|
||||
owner::tx_lock_outputs(w, keychain_mask, &slate)?;
|
||||
owner::finalize_tx(w, keychain_mask, &slate)?
|
||||
};
|
||||
let client = {
|
||||
let mut w_lock = wallet.lock();
|
||||
@@ -267,7 +267,7 @@ pub fn wallet_info<'a, L, C, K>(
|
||||
where
|
||||
L: WalletLCProvider<'a, C, K>,
|
||||
C: NodeClient + 'a,
|
||||
K: keychain::Keychain + 'a,
|
||||
K: Keychain + 'a,
|
||||
{
|
||||
let (wallet_refreshed, wallet_info) =
|
||||
owner::retrieve_summary_info(wallet, keychain_mask, &None, true, 1)?;
|
||||
|
||||
@@ -70,7 +70,7 @@ where
|
||||
String,
|
||||
(
|
||||
Sender<WalletProxyMessage>,
|
||||
Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
Option<SecretKey>,
|
||||
),
|
||||
>,
|
||||
@@ -100,14 +100,15 @@ where
|
||||
genesis_block,
|
||||
pow::verify_size,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, rx) = channel();
|
||||
WalletProxy {
|
||||
chain_dir: chain_dir.to_owned(),
|
||||
chain: Arc::new(c),
|
||||
tx: tx,
|
||||
rx: rx,
|
||||
tx,
|
||||
rx,
|
||||
wallets: HashMap::new(),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
@@ -118,7 +119,7 @@ where
|
||||
&mut self,
|
||||
addr: &str,
|
||||
tx: Sender<WalletProxyMessage>,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K> + 'a>>>,
|
||||
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
|
||||
keychain_mask: Option<SecretKey>,
|
||||
) {
|
||||
self.wallets
|
||||
@@ -218,8 +219,7 @@ where
|
||||
let w = w_lock.lc_provider()?.wallet_inst()?;
|
||||
let mask = wallet.2.clone();
|
||||
// receive tx
|
||||
match foreign::receive_tx(&mut **w, (&mask).as_ref(), &Slate::from(slate), None, false)
|
||||
{
|
||||
match foreign::receive_tx(w, (&mask).as_ref(), &Slate::from(slate), None, false) {
|
||||
Err(e) => {
|
||||
return Ok(WalletProxyMessage {
|
||||
sender_id: m.dest,
|
||||
|
||||
Reference in New Issue
Block a user