Store and use last scanned PMMR height in check_repair (#246)

* store last scanned PMMR check index

* rustfmt

* fix issue where account names will be overwritten on check_repair

* rustfmt

* attempts to include check_repair scan as part of normal update

* rustfmt

* fix error on restore due to incorrect parent key id being set

* addition of calls to heigt_range_to_pmmr_indices traits and implementations

* rustfmt

* get_chain_height -> get_chain_tip

* rustfmt

* retrieve height+hash from node, modify check_repair to use block heights

* rustfmt

* fixes from live testing

* rustfmt

* test cleanup and change dependencies back to grin master

* rustfmt
This commit is contained in:
Yeastplume
2019-11-04 21:10:05 +00:00
committed by GitHub
parent ba6c5ed0f8
commit c518f35c8d
16 changed files with 855 additions and 358 deletions
+68 -8
View File
@@ -33,8 +33,8 @@ use crate::core::core::Transaction;
use crate::core::ser;
use crate::libwallet::{check_repair, restore};
use crate::libwallet::{
AcctPathMapping, Context, Error, ErrorKind, NodeClient, OutputData, TxLogEntry, WalletBackend,
WalletOutputBatch,
AcctPathMapping, Context, Error, ErrorKind, NodeClient, OutputData, ScannedBlockInfo,
TxLogEntry, WalletBackend, WalletOutputBatch,
};
use crate::util::secp::constants::SECRET_KEY_SIZE;
use crate::util::secp::key::SecretKey;
@@ -53,6 +53,8 @@ const PRIVATE_TX_CONTEXT_PREFIX: u8 = 'p' as u8;
const TX_LOG_ENTRY_PREFIX: u8 = 't' as u8;
const TX_LOG_ID_PREFIX: u8 = 'i' as u8;
const ACCOUNT_PATH_MAPPING_PREFIX: u8 = 'a' as u8;
const LAST_SCANNED_BLOCK: u8 = 'l' as u8;
const LAST_SCANNED_KEY: &str = "LAST_SCANNED_KEY";
/// test to see if database files exist in the current directory. If so,
/// use a DB backend for all operations
@@ -395,6 +397,18 @@ where
}))
}
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)? {
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();
let mut deriv_idx = {
@@ -428,18 +442,51 @@ where
Ok(last_confirmed_height)
}
fn restore(&mut self, keychain_mask: Option<&SecretKey>) -> Result<(), Error> {
restore(self, keychain_mask).context(ErrorKind::Restore)?;
Ok(())
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)? {
Some(b) => b,
None => ScannedBlockInfo {
height: 0,
hash: "".to_owned(),
start_pmmr_index: 0,
last_pmmr_index: 0,
},
};
Ok(last_scanned_block)
}
fn restore(
&mut self,
keychain_mask: Option<&SecretKey>,
to_height: u64,
) -> Result<Option<ScannedBlockInfo>, Error> {
let res = restore(self, keychain_mask, to_height).context(ErrorKind::Restore)?;
Ok(res)
}
fn check_repair(
&mut self,
keychain_mask: Option<&SecretKey>,
delete_unconfirmed: bool,
) -> Result<(), Error> {
check_repair(self, keychain_mask, delete_unconfirmed).context(ErrorKind::Restore)?;
Ok(())
start_height: u64,
end_height: u64,
status_fn: fn(&str),
) -> Result<ScannedBlockInfo, Error> {
let res = check_repair(
self,
keychain_mask,
delete_unconfirmed,
start_height,
end_height,
status_fn,
)
.context(ErrorKind::Restore)?;
Ok(res)
}
}
@@ -558,6 +605,19 @@ where
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_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
+38 -6
View File
@@ -47,8 +47,8 @@ impl HTTPNodeClient {
}
/// Allow returning the chain height without needing a wallet instantiated
pub fn chain_height(&self) -> Result<u64, libwallet::Error> {
self.get_chain_height()
pub fn chain_height(&self) -> Result<(u64, String), libwallet::Error> {
self.get_chain_tip()
}
}
@@ -117,7 +117,7 @@ impl NodeClient for HTTPNodeClient {
}
/// Return the chain tip from a given node
fn get_chain_height(&self) -> Result<u64, libwallet::Error> {
fn get_chain_tip(&self) -> Result<(u64, String), libwallet::Error> {
let addr = self.node_url();
let url = format!("{}/v1/chain", addr);
let client = Client::new();
@@ -128,7 +128,7 @@ impl NodeClient for HTTPNodeClient {
error!("Get chain height error: {}", e);
Err(libwallet::ErrorKind::ClientCallback(report).into())
}
Ok(r) => Ok(r.height),
Ok(r) => Ok((r.height, r.last_block_pushed)),
}
}
@@ -230,7 +230,8 @@ impl NodeClient for HTTPNodeClient {
fn get_outputs_by_pmmr_index(
&self,
start_height: u64,
start_index: u64,
end_index: Option<u64>,
max_outputs: u64,
) -> Result<
(
@@ -241,7 +242,11 @@ impl NodeClient for HTTPNodeClient {
libwallet::Error,
> {
let addr = self.node_url();
let query_param = format!("start_index={}&max={}", start_height, max_outputs);
let mut query_param = format!("start_index={}&max={}", start_index, max_outputs);
if let Some(e) = end_index {
query_param = format!("{}&end_index={}", query_param, e);
};
let url = format!("{}/v1/txhashset/outputs?{}", addr, query_param,);
@@ -279,6 +284,33 @@ impl NodeClient for HTTPNodeClient {
}
}
}
fn height_range_to_pmmr_indices(
&self,
start_height: u64,
end_height: Option<u64>,
) -> Result<(u64, u64), libwallet::Error> {
debug!("Indices start");
let addr = self.node_url();
let mut query_param = format!("start_height={}", start_height);
if let Some(e) = end_height {
query_param = format!("{}&end_height={}", query_param, e);
};
let url = format!("{}/v1/txhashset/heightstopmmr?{}", addr, query_param,);
let client = Client::new();
match client.get::<api::OutputListing>(url.as_str(), self.node_api_secret()) {
Ok(o) => Ok((o.last_retrieved_index, o.highest_index)),
Err(e) => {
// if we got anything other than 200 back from server, bye
error!("heightstopmmr: error contacting {}. Error: {}", addr, e);
let report = format!(": {}", e);
Err(libwallet::ErrorKind::ClientCallback(report))?
}
}
}
}
/*
+18 -1
View File
@@ -73,10 +73,11 @@ fn get_kernel_local(
fn get_outputs_by_pmmr_index_local(
chain: Arc<chain::Chain>,
start_index: u64,
end_index: Option<u64>,
max: u64,
) -> api::OutputListing {
let outputs = chain
.unspent_outputs_by_insertion_index(start_index, max)
.unspent_outputs_by_pmmr_index(start_index, max, end_index)
.unwrap();
api::OutputListing {
last_retrieved_index: outputs.0,
@@ -91,6 +92,22 @@ 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>,
start_index: u64,
end_index: Option<u64>,
) -> api::OutputListing {
let indices = chain
.block_height_range_to_pmmr_indices(start_index, end_index)
.unwrap();
api::OutputListing {
last_retrieved_index: indices.0,
highest_index: indices.1,
outputs: vec![],
}
}
/// Adds a block with a given reward to the chain and mines it
pub fn add_block_with_reward(
chain: &Chain,
+82 -12
View File
@@ -146,9 +146,10 @@ where
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_chain_tip" => self.get_chain_tip(m)?,
"get_outputs_from_node" => self.get_outputs_from_node(m)?,
"get_outputs_by_pmmr_index" => self.get_outputs_by_pmmr_index(m)?,
"height_range_to_pmmr_indices" => self.height_range_to_pmmr_indices(m)?,
"send_tx_slate" => self.send_tx_slate(m)?,
"post_tx" => self.post_tx(m)?,
"get_kernel" => self.get_kernel(m)?,
@@ -243,15 +244,18 @@ where
}
/// get chain height
fn get_chain_height(
fn get_chain_tip(
&mut self,
m: WalletProxyMessage,
) -> Result<WalletProxyMessage, libwallet::Error> {
let height = self.chain.head().unwrap().height;
let hash = util::to_hex(self.chain.head().unwrap().last_block_h.to_vec());
Ok(WalletProxyMessage {
sender_id: "node".to_owned(),
dest: m.sender_id,
method: m.method,
body: format!("{}", self.chain.head().unwrap().height).to_owned(),
body: format!("{},{}", height, hash),
})
}
@@ -291,7 +295,35 @@ where
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);
let end_index = split[2].parse::<u64>().unwrap();
let end_index = match end_index {
0 => None,
e => Some(e),
};
let ol =
super::get_outputs_by_pmmr_index_local(self.chain.clone(), start_index, end_index, max);
Ok(WalletProxyMessage {
sender_id: "node".to_owned(),
dest: m.sender_id,
method: m.method,
body: serde_json::to_string(&ol).unwrap(),
})
}
/// get api outputs by height
fn height_range_to_pmmr_indices(
&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 end_index = split[1].parse::<u64>().unwrap();
let end_index = match end_index {
0 => None,
e => Some(e),
};
let ol =
super::height_range_to_pmmr_indices_local(self.chain.clone(), start_index, end_index);
Ok(WalletProxyMessage {
sender_id: "node".to_owned(),
dest: m.sender_id,
@@ -412,11 +444,11 @@ impl NodeClient for LocalWalletClient {
}
/// Return the chain tip from a given node
fn get_chain_height(&self) -> Result<u64, libwallet::Error> {
fn get_chain_tip(&self) -> Result<(u64, String), libwallet::Error> {
let m = WalletProxyMessage {
sender_id: self.id.clone(),
dest: self.node_url().to_owned(),
method: "get_chain_height".to_owned(),
method: "get_chain_tip".to_owned(),
body: "".to_owned(),
};
{
@@ -427,12 +459,15 @@ impl NodeClient for LocalWalletClient {
}
let r = self.rx.lock();
let m = r.recv().unwrap();
trace!("Received get_chain_height response: {:?}", m.clone());
Ok(m.body
.parse::<u64>()
trace!("Received get_chain_tip response: {:?}", m.clone());
let res = m
.body
.parse::<String>()
.context(libwallet::ErrorKind::ClientCallback(
"Parsing get_height response".to_owned(),
))?)
))?;
let split: Vec<&str> = res.split(",").collect();
Ok((split[0].parse::<u64>().unwrap(), split[1].to_owned()))
}
/// Retrieve outputs from node
@@ -513,7 +548,8 @@ impl NodeClient for LocalWalletClient {
fn get_outputs_by_pmmr_index(
&self,
start_height: u64,
start_index: u64,
end_index: Option<u64>,
max_outputs: u64,
) -> Result<
(
@@ -524,7 +560,11 @@ impl NodeClient for LocalWalletClient {
libwallet::Error,
> {
// start index, max
let query_str = format!("{},{}", start_height, max_outputs);
let mut query_str = format!("{},{}", start_index, max_outputs);
match end_index {
Some(e) => query_str = format!("{},{}", query_str, e),
None => query_str = format!("{},0", query_str),
};
let m = WalletProxyMessage {
sender_id: self.id.clone(),
dest: self.node_url().to_owned(),
@@ -560,6 +600,36 @@ impl NodeClient for LocalWalletClient {
}
Ok((o.highest_index, o.last_retrieved_index, api_outputs))
}
fn height_range_to_pmmr_indices(
&self,
start_height: u64,
end_height: Option<u64>,
) -> Result<(u64, u64), libwallet::Error> {
// start index, max
let mut query_str = format!("{}", start_height);
match end_height {
Some(e) => query_str = format!("{},{}", query_str, e),
None => query_str = format!("{},0", query_str),
};
let m = WalletProxyMessage {
sender_id: self.id.clone(),
dest: self.node_url().to_owned(),
method: "height_range_to_pmmr_indices".to_owned(),
body: query_str,
};
{
let p = self.proxy_tx.lock();
p.send(m).context(libwallet::ErrorKind::ClientCallback(
"Get outputs within height range send".to_owned(),
))?;
}
let r = self.rx.lock();
let m = r.recv().unwrap();
let o: api::OutputListing = serde_json::from_str(&m.body).unwrap();
Ok((o.last_retrieved_index, o.highest_index))
}
}
unsafe impl<'a, L, C, K> Send for WalletProxy<'a, L, C, K>
where