Browse Source

merge some upstream improvements, set new checkpoint blockhigh

checkpoints
DenioD 4 years ago
parent
commit
8f64f9e0df
  1. 2692
      Cargo.lock
  2. 2
      cli/Cargo.toml
  3. 2
      cli/src/main.rs
  4. 28
      lib/Cargo.toml
  5. 17
      lib/build.rs
  6. 1
      lib/res/lightwalletd-zecwallet-co-chain.pem
  7. 34
      lib/src/commands.rs
  8. 448
      lib/src/grpcconnector.rs
  9. 8
      lib/src/lib.rs
  10. 34
      lib/src/lightclient.rs
  11. 27
      lib/src/lightclient/checkpoints.rs
  12. 36
      lib/src/lightwallet.rs
  13. 19
      lib/src/lightwallet/extended_key.rs
  14. 65
      res/lightwalletd-lite.myhush.pem

2692
Cargo.lock

File diff suppressed because it is too large

2
cli/Cargo.toml

@ -10,7 +10,7 @@ log = "0.4"
log4rs = "0.8.3"
shellwords = "1.0.0"
json = "0.12.0"
http = "0.1"
http = "0.2"
byteorder = "1"
tiny-bip39 = "0.6.2"

2
cli/src/main.rs

@ -44,7 +44,7 @@ pub fn main() {
let server = LightClientConfig::get_server_or_default(maybe_server);
// Test to make sure the server has all of scheme, host and port
if server.scheme_str().is_none() || server.host().is_none() || server.port_part().is_none() {
if server.scheme_str().is_none() || server.host().is_none() || server.port().is_none() {
eprintln!("Please provide the --server parameter as [scheme]://[host]:[port].\nYou provided: {}", server);
return;
}

28
lib/Cargo.toml

@ -4,18 +4,11 @@ version = "0.1.0"
edition = "2018"
[dependencies]
tower-grpc = "0.1.1"
futures = "0.1"
bytes = "0.4"
base58 = "0.1.0"
log = "0.4"
log4rs = "0.8.3"
dirs = "2.0.2"
http = "0.1"
prost = "0.5"
tokio = "0.1"
tower-request-modifier = "0.1.0"
tower-util = "0.1"
http = "0.2"
hex = "0.3"
protobuf = "2"
byteorder = "1"
@ -24,17 +17,20 @@ tiny-bip39 = "0.6.2"
secp256k1 = "=0.15.0"
sha2 = "0.8.0"
ripemd160 = "0.8.0"
ring = "0.14.0"
lazy_static = "1.2.0"
tower-service = "0.2"
tokio-rustls = "0.10.0-alpha.3"
rustls = { version = "0.15.2", features = ["dangerous_configuration"] }
webpki = "0.19.1"
webpki-roots = "0.16.0"
tower-h2 = { git = "https://github.com/tower-rs/tower-h2", rev="0865040d699697bbaf1c3b77b3f256b72f98cdf4" }
rust-embed = { version = "5.1.0", features = ["debug-embed"] }
rand = "0.7.2"
sodiumoxide = "0.2.5"
ring = "0.16.9"
tonic = { version = "0.1.1", features = ["tls", "tls-roots"] }
bytes = "0.4"
prost = "0.6"
prost-types = "0.6"
tokio = { version = "0.2", features = ["rt-threaded", "time", "stream", "fs", "macros", "uds", "full"] }
tokio-rustls = { version = "0.12.1", features = ["dangerous_configuration"] }
webpki = "0.21.0"
webpki-roots = "0.18.0"
[dependencies.bellman]
git = "https://github.com/DenioD/librustzcash.git"
@ -69,7 +65,7 @@ rev= "caaee693c47c2ee9ecd1e1546b8fe3c714f342bc"
features = ["ff_derive"]
[build-dependencies]
tower-grpc-build = { git = "https://github.com/tower-rs/tower-grpc", features = ["tower-hyper"] }
tonic-build = "0.1.1"
[dev-dependencies]
tempdir = "0.3.7"

17
lib/build.rs

@ -1,12 +1,11 @@
fn main() {
// Build proto files
tower_grpc_build::Config::new()
.enable_server(false)
.enable_client(true)
.build(
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.build_server(false)
.compile(
&["proto/service.proto", "proto/compact_formats.proto"],
&["proto"],
)
.unwrap_or_else(|e| panic!("protobuf compilation failed: {}", e));
)?;
println!("cargo:rerun-if-changed=proto/service.proto");
}
Ok(())
}

1
lib/res/lightwalletd-zecwallet-co-chain.pem

@ -0,0 +1 @@

34
lib/src/commands.rs

@ -479,12 +479,13 @@ struct SendCommand {}
impl Command for SendCommand {
fn help(&self) -> String {
let mut h = vec![];
h.push("Send HUSH to a given address");
h.push("Send HUSH to a given address(es)");
h.push("Usage:");
h.push("send <address> <amount in puposhis> \"optional_memo\"");
h.push("OR");
h.push("send '[{'address': <address>, 'amount': <amount in puposhis>, 'memo': <optional memo>}, ...]'");
h.push("");
h.push("NOTE: The fee required to send this transaction (currently HUSH 0.0001) is additionally detected from your balance.");
h.push("Example:");
h.push("send ztestsapling1x65nq4dgp0qfywgxcwk9n0fvm4fysmapgr2q00p85ju252h6l7mmxu2jg9cqqhtvzd69jwhgv8d 200000 \"Hello from the command line\"");
h.push("");
@ -721,36 +722,6 @@ impl Command for NewAddressCommand {
}
}
struct NewSietchAddressCommand {}
impl Command for NewSietchAddressCommand {
fn help(&self) -> String {
let mut h = vec![];
h.push("New Sietch Address");
h.push("Usage:");
h.push("sietch [zs]");
h.push("");
h.push("Example:");
h.push("To create a new zdust:");
h.push("sietch zs");
h.join("\n")
}
fn short_help(&self) -> String {
"Create a sietch Address".to_string()
}
fn exec(&self, args: &[&str], lightclient: &LightClient) -> String {
if args.len() != 1 {
return format!("No address type specified\n{}", self.help());
}
match lightclient.do_new_sietchaddress(args[0]) {
Ok(j) => j,
Err(e) => object!{ "error" => e }
}.pretty(2)
}
}
struct NotesCommand {}
impl Command for NotesCommand {
fn help(&self) -> String {
@ -861,7 +832,6 @@ pub fn get_commands() -> Box<HashMap<String, Box<dyn Command>>> {
map.insert("list".to_string(), Box::new(TransactionsCommand{}));
map.insert("notes".to_string(), Box::new(NotesCommand{}));
map.insert("new".to_string(), Box::new(NewAddressCommand{}));
map.insert("sietch".to_string(), Box::new(NewSietchAddressCommand{}));
map.insert("seed".to_string(), Box::new(SeedCommand{}));
map.insert("encrypt".to_string(), Box::new(EncryptCommand{}));
map.insert("decrypt".to_string(), Box::new(DecryptCommand{}));

448
lib/src/grpcconnector.rs

@ -1,30 +1,18 @@
use log::{error};
use std::sync::{Arc};
use std::net::ToSocketAddrs;
use std::net::SocketAddr;
use futures::{Future};
use futures::stream::Stream;
use tower_h2;
use tower_util::MakeService;
use tower_grpc::Request;
use tokio_rustls::client::TlsStream;
use tokio_rustls::{rustls::ClientConfig, TlsConnector};
use tokio::executor::DefaultExecutor;
use tokio::net::tcp::TcpStream;
use std::sync::Arc;
use zcash_primitives::transaction::{TxId};
use crate::grpc_client::{ChainSpec, BlockId, BlockRange, RawTransaction,
TransparentAddressBlockFilter, TxFilter, Empty, LightdInfo,Coinsupply};
use crate::grpc_client::client::CompactTxStreamer;
TransparentAddressBlockFilter, TxFilter, Empty, LightdInfo, Coinsupply};
use tonic::transport::{Channel, ClientTlsConfig};
use tokio_rustls::{rustls::ClientConfig};
use tonic::{Request};
use crate::PubCertificate;
use crate::grpc_client::compact_tx_streamer_client::CompactTxStreamerClient;
mod danger {
use rustls;
use tokio_rustls::rustls;
use webpki;
pub struct NoCertificateVerification {}
@ -40,295 +28,237 @@ mod danger {
}
}
/// A Secure (https) grpc destination.
struct Dst {
addr: SocketAddr,
host: String,
no_cert: bool,
}
impl tower_service::Service<()> for Dst {
type Response = TlsStream<TcpStream>;
type Error = ::std::io::Error;
type Future = Box<dyn Future<Item = TlsStream<TcpStream>, Error = ::std::io::Error> + Send>;
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
Ok(().into())
}
fn call(&mut self, _: ()) -> Self::Future {
async fn get_client(uri: &http::Uri, no_cert: bool) -> Result<CompactTxStreamerClient<Channel>, Box<dyn std::error::Error>> {
let channel = if uri.scheme_str() == Some("http") {
//println!("http");
Channel::builder(uri.clone()).connect().await?
} else {
//println!("https");
let mut config = ClientConfig::new();
config.alpn_protocols.push(b"h2".to_vec());
config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
config.root_store.add_pem_file(
&mut PubCertificate::get("lightwalletd-lite.myhush.pem").unwrap().as_ref()).unwrap();
if self.no_cert {
if no_cert {
config.dangerous()
.set_certificate_verifier(Arc::new(danger::NoCertificateVerification {}));
}
let config = Arc::new(config);
let tls_connector = TlsConnector::from(config);
let tls = ClientTlsConfig::new()
.rustls_client_config(config)
.domain_name(uri.host().unwrap());
Channel::builder(uri.clone())
.tls_config(tls)
.connect()
.await?
};
let addr_string_local = self.host.clone();
Ok(CompactTxStreamerClient::new(channel))
}
let domain = match webpki::DNSNameRef::try_from_ascii_str(&addr_string_local) {
Ok(d) => d,
Err(_) => webpki::DNSNameRef::try_from_ascii_str("localhost").unwrap()
};
let domain_local = domain.to_owned();
// ==============
// GRPC code
// ==============
async fn get_lightd_info(uri: &http::Uri, no_cert: bool) -> Result<LightdInfo, Box<dyn std::error::Error>> {
let mut client = get_client(uri, no_cert).await?;
let stream = TcpStream::connect(&self.addr).and_then(move |sock| {
sock.set_nodelay(true).unwrap();
tls_connector.connect(domain_local.as_ref(), sock)
})
.map(move |tcp| tcp);
let request = Request::new(Empty {});
Box::new(stream)
}
let response = client.get_lightd_info(request).await?;
Ok(response.into_inner())
}
// Same implementation but without TLS. Should make it straightforward to run without TLS
// when testing on local machine
//
// impl tower_service::Service<()> for Dst {
// type Response = TcpStream;
// type Error = ::std::io::Error;
// type Future = Box<dyn Future<Item = TcpStream, Error = ::std::io::Error> + Send>;
//
// fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
// Ok(().into())
// }
//
// fn call(&mut self, _: ()) -> Self::Future {
// let mut config = ClientConfig::new();
// config.alpn_protocols.push(b"h2".to_vec());
// config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
//
// let stream = TcpStream::connect(&self.addr)
// .and_then(move |sock| {
// sock.set_nodelay(true).unwrap();
// Ok(sock)
// });
// Box::new(stream)
// }
// }
macro_rules! make_grpc_client {
($protocol:expr, $host:expr, $port:expr, $nocert:expr) => {{
let uri: http::Uri = format!("{}://{}", $protocol, $host).parse().unwrap();
let addr = format!("{}:{}", $host, $port)
.to_socket_addrs()
.unwrap()
.next()
.unwrap();
let h2_settings = Default::default();
let mut make_client = tower_h2::client::Connect::new(Dst {addr, host: $host.to_string(), no_cert: $nocert}, h2_settings, DefaultExecutor::current());
make_client
.make_service(())
.map_err(|e| { format!("HTTP/2 connection failed; err={:?}.\nIf you're connecting to a local server, please pass --dangerous to trust the server without checking its TLS certificate", e) })
.and_then(move |conn| {
let conn = tower_request_modifier::Builder::new()
.set_origin(uri)
.build(conn)
.unwrap();
CompactTxStreamer::new(conn)
// Wait until the client is ready...
.ready()
.map_err(|e| { format!("client closed: {:?}", e) })
})
}};
pub fn get_info(uri: &http::Uri, no_cert: bool) -> Result<LightdInfo, String> {
let mut rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
rt.block_on(get_lightd_info(uri, no_cert)).map_err( |e| e.to_string())
}
async fn get_coinsupply_info(uri: &http::Uri, no_cert: bool) -> Result<Coinsupply, Box<dyn std::error::Error>> {
let mut client = get_client(uri, no_cert).await?;
// ==============
// GRPC code
// ==============
let request = Request::new(Empty {});
pub fn get_info(uri: http::Uri, no_cert: bool) -> Result<LightdInfo, String> {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
client.get_lightd_info(Request::new(Empty{}))
.map_err(|e| {
format!("ERR = {:?}", e)
})
.and_then(move |response| {
Ok(response.into_inner())
})
.map_err(|e| {
format!("ERR = {:?}", e)
})
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
}
let response = client.get_coinsupply(request).await?;
Ok(response.into_inner())
}
pub fn get_coinsupply(uri: http::Uri, no_cert: bool) -> Result<Coinsupply, String> {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
client.get_coinsupply(Request::new(Empty{}))
.map_err(|e| {
format!("ERR = {:?}", e)
})
.and_then(move |response| {
Ok(response.into_inner())
})
.map_err(|e| {
format!("ERR = {:?}", e)
})
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
let mut rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
rt.block_on(get_coinsupply_info(&uri, no_cert)).map_err( |e| e.to_string())
// tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
}
pub fn fetch_blocks<F : 'static + std::marker::Send>(uri: &http::Uri, start_height: u64, end_height: u64, no_cert: bool, mut c: F)
async fn get_block_range<F : 'static + std::marker::Send>(uri: &http::Uri, start_height: u64, end_height: u64, no_cert: bool, mut c: F)
-> Result<(), Box<dyn std::error::Error>>
where F : FnMut(&[u8], u64) {
let mut client = get_client(uri, no_cert).await?;
let bs = BlockId{ height: start_height, hash: vec!()};
let be = BlockId{ height: end_height, hash: vec!()};
let request = Request::new(BlockRange{ start: Some(bs), end: Some(be) });
let mut response = client.get_block_range(request).await?.into_inner();
//println!("{:?}", response);
while let Some(block) = response.message().await? {
use prost::Message;
let mut encoded_buf = vec![];
block.encode(&mut encoded_buf).unwrap();
c(&encoded_buf, block.height);
}
Ok(())
}
pub fn fetch_blocks<F : 'static + std::marker::Send>(uri: &http::Uri, start_height: u64, end_height: u64, no_cert: bool, c: F)
where F : FnMut(&[u8], u64) {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
let bs = BlockId{ height: start_height, hash: vec!()};
let be = BlockId{ height: end_height, hash: vec!()};
let br = Request::new(BlockRange{ start: Some(bs), end: Some(be)});
client
.get_block_range(br)
.map_err(|e| {
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
let inbound = response.into_inner();
inbound.for_each(move |b| {
use prost::Message;
let mut encoded_buf = vec![];
b.encode(&mut encoded_buf).unwrap();
c(&encoded_buf, b.height);
Ok(())
})
.map_err(|e| format!("gRPC inbound stream error: {:?}", e))
})
});
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
let mut rt = match tokio::runtime::Runtime::new() {
Ok(r) => r,
Err(e) => {
error!("Error while executing fetch_blocks: {}", e);
error!("Error fetching blocks {}", e.to_string());
eprintln!("{}", e);
return;
}
};
rt.block_on(get_block_range(uri, start_height, end_height, no_cert, c)).unwrap();
}
// get_address_txids GRPC call
async fn get_address_txids<F : 'static + std::marker::Send>(uri: &http::Uri, address: String,
start_height: u64, end_height: u64, no_cert: bool, c: F) -> Result<(), Box<dyn std::error::Error>>
where F : Fn(&[u8], u64) {
let mut client = get_client(uri, no_cert).await?;
let start = Some(BlockId{ height: start_height, hash: vec!()});
let end = Some(BlockId{ height: end_height, hash: vec!()});
let request = Request::new(TransparentAddressBlockFilter{ address, range: Some(BlockRange{start, end}) });
let maybe_response = client.get_address_txids(request).await?;
let mut response = maybe_response.into_inner();
while let Some(tx) = response.message().await? {
c(&tx.data, tx.height);
}
Ok(())
}
pub fn fetch_transparent_txids<F : 'static + std::marker::Send>(uri: &http::Uri, address: String,
start_height: u64, end_height: u64, no_cert: bool, c: F)
where F : Fn(&[u8], u64) {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
let start = Some(BlockId{ height: start_height, hash: vec!()});
let end = Some(BlockId{ height: end_height, hash: vec!()});
let br = Request::new(TransparentAddressBlockFilter{ address, range: Some(BlockRange{start, end}) });
client
.get_address_txids(br)
.map_err(|e| {
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
let inbound = response.into_inner();
inbound.for_each(move |tx| {
//let tx = Transaction::read(&tx.into_inner().data[..]).unwrap();
c(&tx.data, tx.height);
Ok(())
})
.map_err(|e| format!("gRPC inbound stream error: {:?}", e))
})
});
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
start_height: u64, end_height: u64, no_cert: bool, c: F)
where F : Fn(&[u8], u64) {
let mut rt = match tokio::runtime::Runtime::new() {
Ok(r) => r,
Err(e) => {
error!("Error while executing fetch_transparent_txids: {}", e);
error!("Error creating runtime {}", e.to_string());
eprintln!("{}", e);
return;
}
};
rt.block_on(get_address_txids(uri, address, start_height, end_height, no_cert, c)).unwrap();
}
// get_transaction GRPC call
async fn get_transaction(uri: &http::Uri, txid: TxId, no_cert: bool)
-> Result<RawTransaction, Box<dyn std::error::Error>> {
let mut client = get_client(uri, no_cert).await?;
let request = Request::new(TxFilter { block: None, index: 0, hash: txid.0.to_vec() });
let response = client.get_transaction(request).await?;
Ok(response.into_inner())
}
pub fn fetch_full_tx<F : 'static + std::marker::Send>(uri: &http::Uri, txid: TxId, no_cert: bool, c: F)
where F : Fn(&[u8]) {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
let txfilter = TxFilter { block: None, index: 0, hash: txid.0.to_vec() };
client.get_transaction(Request::new(txfilter))
.map_err(|e| {
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
c(&response.into_inner().data);
Ok(())
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
let mut rt = match tokio::runtime::Runtime::new() {
Ok(r) => r,
Err(e) => {
error!("Error while executing fetch_full_tx: {}", e);
error!("Error creating runtime {}", e.to_string());
eprintln!("{}", e);
return;
}
};
match rt.block_on(get_transaction(uri, txid, no_cert)) {
Ok(rawtx) => c(&rawtx.data),
Err(e) => {
error!("Error in get_transaction runtime {}", e.to_string());
eprintln!("{}", e);
}
}
}
// send_transaction GRPC call
async fn send_transaction(uri: &http::Uri, no_cert: bool, tx_bytes: Box<[u8]>) -> Result<String, Box<dyn std::error::Error>> {
let mut client = get_client(uri, no_cert).await?;
let request = Request::new(RawTransaction {data: tx_bytes.to_vec(), height: 0});
let response = client.send_transaction(request).await?;
let sendresponse = response.into_inner();
if sendresponse.error_code == 0 {
let mut txid = sendresponse.error_message;
if txid.starts_with("\"") && txid.ends_with("\"") {
txid = txid[1..txid.len()-1].to_string();
}
Ok(txid)
} else {
Err(Box::from(format!("Error: {:?}", sendresponse)))
}
}
pub fn broadcast_raw_tx(uri: &http::Uri, no_cert: bool, tx_bytes: Box<[u8]>) -> Result<String, String> {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(move |mut client| {
client.send_transaction(Request::new(RawTransaction {data: tx_bytes.to_vec(), height: 0}))
.map_err(|e| {
format!("ERR = {:?}", e)
})
.and_then(move |response| {
let sendresponse = response.into_inner();
if sendresponse.error_code == 0 {
let mut txid = sendresponse.error_message;
if txid.starts_with("\"") && txid.ends_with("\"") {
txid = txid[1..txid.len()-1].to_string();
}
Ok(txid)
} else {
Err(format!("Error: {:?}", sendresponse))
}
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
let mut rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?;
rt.block_on(send_transaction(uri, no_cert, tx_bytes)).map_err( |e| e.to_string())
}
// get_latest_block GRPC call
async fn get_latest_block(uri: &http::Uri, no_cert: bool) -> Result<BlockId, Box<dyn std::error::Error>> {
let mut client = get_client(uri, no_cert).await?;
let request = Request::new(ChainSpec {});
let response = client.get_latest_block(request).await?;
Ok(response.into_inner())
}
pub fn fetch_latest_block<F : 'static + std::marker::Send>(uri: &http::Uri, no_cert: bool, mut c : F)
where F : FnMut(BlockId) {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap(), no_cert)
.and_then(|mut client| {
client.get_latest_block(Request::new(ChainSpec {}))
.map_err(|e| { format!("ERR = {:?}", e) })
.and_then(move |response| {
c(response.into_inner());
Ok(())
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
let mut rt = match tokio::runtime::Runtime::new() {
Ok(r) => r,
Err(e) => {
error!("Error creating runtime {}", e.to_string());
eprintln!("{}", e);
return;
}
};
match rt.block_on(get_latest_block(uri, no_cert)) {
Ok(b) => c(b),
Err(e) => {
error!("Error while executing fetch_latest_block: {}", e);
error!("Error getting latest block {}", e.to_string());
eprintln!("{}", e);
}
};

8
lib/src/lib.rs

@ -11,9 +11,13 @@ pub mod commands;
#[folder = "zcash-params/"]
pub struct SaplingParams;
pub const ANCHOR_OFFSET: u32 = 2;
#[derive(RustEmbed)]
#[folder = "res/"]
pub struct PubCertificate;
pub const ANCHOR_OFFSET: u32 = 4;
pub mod grpc_client {
include!(concat!(env!("OUT_DIR"), "/cash.z.wallet.sdk.rpc.rs"));
tonic::include_proto!("cash.z.wallet.sdk.rpc");
}

34
lib/src/lightclient.rs

@ -33,6 +33,7 @@ use log4rs::append::rolling_file::policy::compound::{
use crate::grpc_client::{BlockId};
use crate::grpcconnector::{self, *};
use crate::SaplingParams;
use crate::ANCHOR_OFFSET;
mod checkpoints;
@ -87,13 +88,13 @@ impl LightClientConfig {
pub fn create(server: http::Uri, dangerous: bool) -> io::Result<(LightClientConfig, u64)> {
use std::net::ToSocketAddrs;
// Test for a connection first
format!("{}:{}", server.host().unwrap(), server.port_part().unwrap())
format!("{}:{}", server.host().unwrap(), server.port().unwrap())
.to_socket_addrs()?
.next()
.ok_or(std::io::Error::new(ErrorKind::ConnectionRefused, "Couldn't resolve server!"))?;
// Do a getinfo first, before opening the wallet
let info = grpcconnector::get_info(server.clone(), dangerous)
let info = grpcconnector::get_info(&server, dangerous)
.map_err(|e| std::io::Error::new(ErrorKind::ConnectionRefused, e))?;
// Create a Light Client Config
@ -199,7 +200,7 @@ impl LightClientConfig {
Some(s) => {
let mut s = if s.starts_with("http") {s} else { "http://".to_string() + &s};
let uri: http::Uri = s.parse().unwrap();
if uri.port_part().is_none() {
if uri.port().is_none() {
s = s + ":443";
}
s
@ -583,7 +584,7 @@ impl LightClient {
}
pub fn do_info(&self) -> String {
match get_info(self.get_server_uri(), self.config.no_cert_verification) {
match get_info(&self.get_server_uri(), self.config.no_cert_verification) {
Ok(i) => {
let o = object!{
"version" => i.version,
@ -867,31 +868,6 @@ impl LightClient {
Ok(array![new_address])
}
pub fn do_new_sietchaddress(&self, addr_type: &str) -> Result<JsonValue, String> {
if !self.wallet.read().unwrap().is_unlocked_for_spending() {
error!("Wallet is locked");
return Err("Wallet is locked".to_string());
}
let new_address = {
let wallet = self.wallet.write().unwrap();
match addr_type {
"zs" => wallet.add_zaddrdust(),
_ => {
let e = format!("Unrecognized address type: {}", addr_type);
error!("{}", e);
return Err(e);
}
}
};
self.do_save()?;
Ok(array!["sietch",new_address])
}
pub fn clear_state(&self) {
// First, clear the state from the wallet
self.wallet.read().unwrap().clear_blocks();

27
lib/src/lightclient/checkpoints.rs

@ -1,3 +1,4 @@
pub fn get_closest_checkpoint(chain_name: &str, height: u64) -> Option<(u64, &'static str, &'static str)> {
match chain_name {
"test" => get_test_checkpoint(height),
@ -8,10 +9,10 @@ pub fn get_closest_checkpoint(chain_name: &str, height: u64) -> Option<(u64, &'
fn get_test_checkpoint(height: u64) -> Option<(u64, &'static str, &'static str)> {
let checkpoints: Vec<(u64, &str, &str)> = vec![
(105942, "",
(130000, "000000001c4a5aa11e6c142931463fcf7a9f5b9fb41061d26c18ff1860431881",
""
),
(105943, "",
(152000, "00000000d7c0f7d63b7e628cfcb9fdd45c9d2a244326532c61dfff7fb0d4af45",
""
)
];
@ -22,8 +23,8 @@ fn get_test_checkpoint(height: u64) -> Option<(u64, &'static str, &'static str)
fn get_main_checkpoint(height: u64) -> Option<(u64, &'static str, &'static str)> {
let checkpoints: Vec<(u64, &str, &str)> = vec![
(105942, "00000001c0199f329ee03379bf1387856dbab23765da508bf9b9d8d544f212c0",
"004f80404f103cd92802630f047e8f451ca20bdf1e247b4edf854fac990f544253a96ea7a17741388c8e04b29eee23d51a1f3f45a281c7e7331d2b258f8be2108494d0471d29a9624702cde0e75a294b955a0e95144d4e84fa0ffe20b4e1b558caec6255667233c1c833fc6226eb7a7ce1d95c83ed6ccae5a69abe19f75722463fd3e15b1271e2f9c86e27e54526a90137a4e22bc86722e80b0341fe6cd31a685d21d12ab9acd9c402afedd6ad295b75bfc530c3bedfcf5494af8cbd011a9a31fb66c745d2da32e62f527c8012c6e416917009b1f2fcf2d4732f16ed14a5d3304fda22fcf43947278437143ce2c5731b9e7b4bf6fd206be2385f69370417f3113822be6f4d22259649d54a86119b9a24390f485f0453696679f9a640fe62e40d0102148e96e30c68f5173a1d695b3f03b0e522db53d2af281e72aa1e4deea89660019ba6ea92071b53c07f7b62deb508065cb785411019711933a3c99049f68a703813dd92486622d57996adf99f8094b2945cc0bf09039a70cc16a49e1f924963ddb302d3faef374ef15a0a191cae44babb02e653a373dff177e0236650427d5458c1a30e269e1a4a9bcfb16f7031c3eb54967cb5a9339d341d79be9a54103fdaebcfd29c47b1e6a4dc57150f81293c8a5ce6e167b59b38192bf17adbaa5cf47effdb41e24a339617ccdb3cdfb51d26ec0761d012191bca0a407d9ea88e30f5b5dff13305393828677fcf13a410709fb9a9908553b032726b89162a08bd28ac6f130a6e74ab728b7cd0a70e1389a91e9aaf0f129f9a6540d9ffe0933a5f0dda5114cbb2fa04e5a39a6e345f0a8b646034c73e9db9ff42cd6dcd03a203913539b21c7746c5daa2f8e5fa73267f143b967e0615f8583919866158b6570afac715b53375cfdbde372d3d0e9131cc53084f559eab9d09e3a5fed6c647093578f0e700b48c01acb2ab79bb5b3501405965161f331c2da8112548f2b02c308dc26f86a896d15cddd61f8f3eb309efe46b082847ddd72aa918dbdbc1e6bfbbbc7cf90e81429cd18af174bee97586d16e8e4624b2975bc2034d5abc63232b89f93a51626f4f1031cfc57594f11b52771db0c72d684e9cf26a59947c12c1037b1a09058e2215e22efb8990beb3d8e55c9dc5fdf555037c5e5254705d9999f1d91736e0a23c7f61be33f0b05204dd6b5d44051b1ba08891b27db5fbfe0ff0bcb00b19eeaa279e554b1fbbaac5e6574d722238009d4fd406fd0abe8e48d9b1040e41cedb7d14c2bc9bf8040f26e785122dcb3b41be1fe3084c5f2961277b5e7cac17f587cf7edf53f3bac8664cfc66d187b8957f854e2842cf31518dcc24cebfd38cb97308fd4d66950b743c0d23f06815e4f31a3667d9a7fddf8b0b4f1fe0945233ed8fd0d7b5cf5e173863875665b228cf7bfcbf0258cb198eeb8607a690f4365925ddae0dd3f6123313ec40b886c79a4fc7df692db5714c7b3c3a7c8863080e8b212c634f8769d4f44c3d412769aa00371a9a21fe62847b4aa588e07d0223a8c8f60aebeb5db76404da24d0a2e75ea7a40ba2450c1c24167e61b8ce30064b637f9a82b3dd047a557888f6b5797a01d5c95e0b571e298a95877d75fc00bf10686621a8df18c106363536e40a989d716a8c874dc3e891066c8d5fea2102fe273e80ad3ced95819045e81c9e70570b977ca92a43f9c9fc186f659930a481f4fbc596d3b19ae2e913af6678a4c7103d7bd872f0c9a4770a446a35547d245a0716ed4ca360fcc5c7d21457f05e7493d847931195073ab9d487f593cfb72873f2cb57887e7fc87c1fff7ce92894f107da19442f4cb9a961b6535a6104122491825a4d9395d9568140bd7547fcafa2e89f2d12f1e53a3e53f557e36b6582e862dbce0c11d78a3e"
(170947, "0000000269bfc4db6f23aff43dba54afe20398018082cd8b5e90644257b5adc9",
"0000000269bfc4db6f23aff43dba54afe20398018082cd8b5e90644257b5adc9"
)
];
@ -76,15 +77,15 @@ pub mod tests {
#[test]
fn test_checkpoints() {
assert_eq!(get_test_checkpoint(990000), None);
assert_eq!(get_test_checkpoint(100000).unwrap().0, 100000);
assert_eq!(get_test_checkpoint(110000).unwrap().0, 100000);
assert_eq!(get_test_checkpoint(111000).unwrap().0, 1100000);
assert_eq!(get_test_checkpoint(112000).unwrap().0, 1100000);
assert_eq!(get_main_checkpoint(990000), None);
assert_eq!(get_main_checkpoint(110000).unwrap().0, 110000);
assert_eq!(get_main_checkpoint(111000).unwrap().0, 110000);
assert_eq!(get_test_checkpoint(100000), None);
assert_eq!(get_test_checkpoint(120000).unwrap().0, 120000);
assert_eq!(get_test_checkpoint(125000).unwrap().0, 120000);
assert_eq!(get_test_checkpoint(157000).unwrap().0, 157000);
assert_eq!(get_test_checkpoint(175000).unwrap().0, 157000);
assert_eq!(get_main_checkpoint(100000), None);
assert_eq!(get_main_checkpoint(170947).unwrap().0, 170947);
assert_eq!(get_main_checkpoint(170949).unwrap().0, 170947);
}
}

36
lib/src/lightwallet.rs

@ -4,7 +4,9 @@ use std::cmp;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::io::{Error, ErrorKind};
use rand::{Rng, rngs::OsRng};
use log::{info, warn, error};
use protobuf::parse_from_bytes;
@ -197,7 +199,7 @@ impl LightWallet {
seed_bytes.copy_from_slice(&phrase.entropy());
}
// The seed bytes is the raw entropy. To pass it to HD wallet generation,
// we need to get the 64 byte bip39 entropy
let bip39_seed = bip39::Seed::new(&Mnemonic::from_entropy(&seed_bytes, Language::English).unwrap(), "");
@ -456,38 +458,6 @@ impl LightWallet {
self.extfvks.write().unwrap().push(extfvk);
self.zaddress.write().unwrap().push(address);
zaddr
}
pub fn add_zaddrdust(&self) -> String {
if !self.unlocked {
return "".to_string();
}
let pos = self.extsks.read().unwrap().len() as u32;
// Radnom Generator benutzen!!!!!!
let mut rng = rand::thread_rng();
let letter: String = rng.gen_range(b'A', b'Z').to_string();
let number: String = rng.gen_range(0, 999999).to_string();
// let combi: String = letter.to_string() + number.to_string();
let s = format!("{}{:06}", letter, number);
//println!("{}", s);
let my_string = String::from(s);
// let my_immutable_string = &my_string; //This is a &String type
let dust: &str = &my_string; //This is an &str type
let bip39_seed = bip39::Seed::new(&Mnemonic::from_entropy(&self.seed, Language::English).unwrap(), dust);
let (_extsk, _extfvk, address) =
LightWallet::get_zaddr_from_bip39seed(&self.config, &bip39_seed.as_bytes(), pos);
let zaddr = encode_payment_address(self.config.hrp_sapling_address(), &address);
zaddr
}

19
lib/src/lightwallet/extended_key.rs

@ -1,6 +1,5 @@
use ring::{
digest,
hmac::{SigningContext, SigningKey},
hmac::{self, Context, Key},
};
use lazy_static::lazy_static;
use secp256k1::{PublicKey, Secp256k1, SecretKey, SignOnly, VerifyOnly, Error};
@ -74,8 +73,8 @@ impl ExtendedPrivKey {
/// Generate an ExtendedPrivKey from seed
pub fn with_seed(seed: &[u8]) -> Result<ExtendedPrivKey, Error> {
let signature = {
let signing_key = SigningKey::new(&digest::SHA512, b"Bitcoin seed");
let mut h = SigningContext::with_key(&signing_key);
let signing_key = Key::new(hmac::HMAC_SHA512, b"Bitcoin seed");
let mut h = Context::with_key(&signing_key);
h.update(&seed);
h.sign()
};
@ -88,18 +87,18 @@ impl ExtendedPrivKey {
})
}
fn sign_hardended_key(&self, index: u32) -> ring::hmac::Signature {
let signing_key = SigningKey::new(&digest::SHA512, &self.chain_code);
let mut h = SigningContext::with_key(&signing_key);
fn sign_hardended_key(&self, index: u32) -> ring::hmac::Tag {
let signing_key = Key::new(hmac::HMAC_SHA512, &self.chain_code);
let mut h = Context::with_key(&signing_key);
h.update(&[0x00]);
h.update(&self.private_key[..]);
h.update(&index.to_be_bytes());
h.sign()
}
fn sign_normal_key(&self, index: u32) -> ring::hmac::Signature {
let signing_key = SigningKey::new(&digest::SHA512, &self.chain_code);
let mut h = SigningContext::with_key(&signing_key);
fn sign_normal_key(&self, index: u32) -> ring::hmac::Tag {
let signing_key = Key::new(hmac::HMAC_SHA512, &self.chain_code);
let mut h = Context::with_key(&signing_key);
let public_key = PublicKey::from_secret_key(&SECP256K1_SIGN_ONLY, &self.private_key);
h.update(&public_key.serialize());
h.update(&index.to_be_bytes());

65
res/lightwalletd-lite.myhush.pem

@ -0,0 +1,65 @@
-----BEGIN CERTIFICATE-----
MIIFlTCCA32gAwIBAgIUCU7sjrIbYfA+bc2qWlyUo0dCU7swDQYJKoZIhvcNAQEL
BQAwWjELMAkGA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxDTALBgNVBAoM
BEh1c2gxDTALBgNVBAsMBEh1c2gxGDAWBgNVBAMMD2xpdGUubXlodXNoLm9yZzAe
Fw0xOTEyMDIxNDUyMzBaFw0yMDEyMDExNDUyMzBaMFoxCzAJBgNVBAYTAlVTMRMw
EQYDVQQIDApTb21lLVN0YXRlMQ0wCwYDVQQKDARIdXNoMQ0wCwYDVQQLDAR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