Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ jobs:
- run: rustup toolchain install stable --profile minimal --component rustfmt,clippy
- run: cargo fmt --check
- run: cargo clippy --all-targets --locked -- -D warnings
# The host tool's mainnet key lending (wizard#61); never in an app build.
- run: cargo clippy --all-targets --locked --features host-mainnet-alerts -- -D warnings
# Tests that need a lightwalletd server are #[ignore]d.
- run: cargo test --locked
- run: cargo test --locked --lib --features host-mainnet-alerts

rust-msrv:
name: Engine on Rust 1.89 (minimum)
Expand Down
4 changes: 4 additions & 0 deletions engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ ohttp = { version = "0.8", default-features = false, features = ["client", "serv
[features]
# The `uniffi-bindgen` binary, for generating Swift and Kotlin. Never linked into an app.
bindgen = ["uniffi/cli", "uniffi/cargo-metadata"]
# Host tool only (wizard#61): lets `examples/lantern --mainnet --lend-key`
# lend a throwaway mainnet wallet's viewing key, for Lantern Zero's production
# key-storage check. Never enabled in an app build.
host-mainnet-alerts = []

[[bin]]
name = "uniffi-bindgen"
Expand Down
68 changes: 61 additions & 7 deletions engine/examples/lantern.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Host tool for Wizard's Lantern Zero flow against a real server (testnet).
//! Host tool for Wizard's Lantern Zero flow against a real server.
//!
//! cargo run --example lantern -- [--wallet NAME] connect [--scan] [--instant]
//! cargo run --example lantern -- [--wallet NAME] wake | status | alerts | scan on|off
Expand All @@ -10,14 +10,39 @@
//! folder is git-ignored); the app keeps it in the Keychain or Keystore.
//! No pushes here: the host has no push token, so it connects without a
//! device, as the app does before the gateway exists.
//!
//! `--mainnet` uses the wallet in `data/mainnet/<NAME>/` (made with `smoke
//! --mainnet ... view`) and production: relay `lz-api`, gateway
//! push.lanternzero.com. Wake-ups only, as in the app (wizard#13).
//!
//! For Lantern Zero's production key-storage check (wizard#61) a throwaway
//! mainnet wallet can lend its viewing key, which the app never does:
//!
//! smoke --mainnet throwaway-ufvk | smoke --mainnet --wallet lend view --birthday H
//! cargo run --features host-mainnet-alerts --example lantern -- \
//! --mainnet --lend-key --wallet lend connect --scan
//!
//! Never pass `--lend-key` for a wallet that watches real money.

use std::path::PathBuf;

use anyhow::{bail, Context, Result};
use wizard_wallet::ffi::{LanternSecrets, WalletConfig, WalletEngine};
use wizard_wallet::server::TESTNET_DEFAULT_SERVER;
use wizard_wallet::server::{MAINNET_DEFAULT_SERVER, TESTNET_DEFAULT_SERVER};

const STAGING_RELAY: &str = "https://relay.oblivious.network/lz-staging";
const PRODUCTION_RELAY: &str = "https://relay.oblivious.network/lz-api";
const STAGING_GATEWAY: &str = "https://push.staging.lanternzero.com";
const PRODUCTION_GATEWAY: &str = "https://push.lanternzero.com";

/// Removes `flag` from `args`, saying whether it was there.
fn take_flag(args: &mut Vec<String>, flag: &str) -> bool {
let at = args.iter().position(|a| a == flag);
if let Some(i) = at {
args.remove(i);
}
at.is_some()
}

fn main() -> Result<()> {
let mut args: Vec<String> = std::env::args().skip(1).collect();
Expand All @@ -26,13 +51,31 @@ fn main() -> Result<()> {
wallet = args.get(i + 1).context("--wallet needs a name")?.clone();
args.drain(i..=i + 1);
}
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("data").join(&wallet);
let relay = std::env::var("LZ_RELAY").unwrap_or_else(|_| STAGING_RELAY.to_owned());
let mainnet = take_flag(&mut args, "--mainnet");
let lend_key = take_flag(&mut args, "--lend-key");
let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("data");
if mainnet {
dir = dir.join("mainnet");
}
let dir = dir.join(&wallet);
let (network, server, relay, gateway) = if mainnet {
("mainnet", MAINNET_DEFAULT_SERVER, PRODUCTION_RELAY, PRODUCTION_GATEWAY)
} else {
("testnet", TESTNET_DEFAULT_SERVER, STAGING_RELAY, STAGING_GATEWAY)
};
let relay = std::env::var("LZ_RELAY").unwrap_or_else(|_| relay.to_owned());
let engine = WalletEngine::open(WalletConfig {
network: "testnet".into(),
network: network.into(),
data_dir: dir.to_string_lossy().into_owned(),
server_url: std::env::var("WIZARD_SERVER").unwrap_or_else(|_| TESTNET_DEFAULT_SERVER.to_owned()),
server_url: std::env::var("WIZARD_SERVER").unwrap_or_else(|_| server.to_owned()),
})?;
if lend_key {
if !mainnet {
bail!("--lend-key is for --mainnet; testnet wallets lend with `connect --scan`");
}
lend_mainnet_key(&engine)?;
eprintln!("--lend-key: wallet {wallet}'s mainnet viewing key may be lent. Throwaway wallets only.");
}
// Push keys for the host, kept beside the URL (git-ignored), made on first use.
let push_file = dir.join("lantern-push.secret");
let secrets = || -> Result<LanternSecrets> {
Expand Down Expand Up @@ -92,7 +135,7 @@ fn main() -> Result<()> {
b.extend_from_slice(&*r.auth_bytes());
std::fs::write(&push_file, b)?;
}
let gateway = std::env::var("LZ_GATEWAY").unwrap_or_else(|_| "https://push.staging.lanternzero.com".into());
let gateway = std::env::var("LZ_GATEWAY").unwrap_or_else(|_| gateway.to_owned());
let changed = engine.lantern_update_push(
secrets()?,
wizard_wallet::ffi::LanternPushTarget {
Expand All @@ -112,3 +155,14 @@ fn main() -> Result<()> {
}
Ok(())
}

#[cfg(feature = "host-mainnet-alerts")]
fn lend_mainnet_key(engine: &WalletEngine) -> Result<()> {
engine.host_lend_mainnet_key();
Ok(())
}

#[cfg(not(feature = "host-mainnet-alerts"))]
fn lend_mainnet_key(_: &WalletEngine) -> Result<()> {
bail!("--lend-key needs `cargo run --features host-mainnet-alerts --example lantern`")
}
65 changes: 64 additions & 1 deletion engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ pub struct WalletEngine {
lantern: Mutex<Lantern>,
/// Bumped to stop a running long-poll without waiting for its lock.
lantern_stop: AtomicU64,
/// Host tool only (wizard#61): see `host_lend_mainnet_key`.
#[cfg(feature = "host-mainnet-alerts")]
host_lend_mainnet: AtomicBool,
}

impl std::fmt::Debug for WalletEngine {
Expand Down Expand Up @@ -257,6 +260,8 @@ impl WalletEngine {
names: zns::registry(&network).map(|r| Names::new(HttpTransport::new(&r), r)),
lantern,
lantern_stop: AtomicU64::new(0),
#[cfg(feature = "host-mainnet-alerts")]
host_lend_mainnet: AtomicBool::new(false),
})
}

Expand All @@ -279,6 +284,9 @@ impl WalletEngine {
/// keep. Refuses turning alerts on there; wake-ups lend nothing. A
/// view-only wallet on testnet never lends its key either (issue #11).
fn alerts_allowed(&self, scanning: bool) -> Result<(), EngineError> {
if self.host_lends_mainnet() {
return Ok(());
}
if scanning && self.network == Network::MainNetwork {
return Err(EngineError::MainnetViewOnly("Payment alerts"));
}
Expand All @@ -288,6 +296,22 @@ impl WalletEngine {
Ok(())
}

/// Host tool only (wizard#61, feature `host-mainnet-alerts`, never in an
/// app): lifts the mainnet and view-only rules above so a throwaway
/// mainnet wallet can lend its viewing key, for Lantern Zero's
/// production key-storage check. Lasts until this engine closes.
#[cfg(feature = "host-mainnet-alerts")]
pub fn host_lend_mainnet_key(&self) {
self.host_lend_mainnet.store(true, Ordering::SeqCst);
}

fn host_lends_mainnet(&self) -> bool {
#[cfg(feature = "host-mainnet-alerts")]
return self.host_lend_mainnet.load(Ordering::SeqCst);
#[cfg(not(feature = "host-mainnet-alerts"))]
false
}

/// A connected client, after checking once that the server is on this
/// engine's network.
fn client(&self) -> Result<Client, EngineError> {
Expand Down Expand Up @@ -840,7 +864,7 @@ impl WalletEngine {
/// viewing key is ever lent from a mainnet wallet.
fn lantern_wake_keys(&self) -> lantern::WakeKeys {
let db = lock(&self.db);
let lend = self.network == Network::TestNetwork;
let lend = self.network == Network::TestNetwork || self.host_lends_mainnet();
lantern::WakeKeys {
ivk: if lend { store::orchard_uivk(&db).ok() } else { None },
scanned_height: store::balance(&db).ok().and_then(|b| b.fully_scanned_height).map(u64::from),
Expand Down Expand Up @@ -1049,6 +1073,45 @@ mod tests {
}
}

/// A mainnet engine holding a view-only account for a throwaway phrase.
fn mainnet_view_only() -> (WalletEngine, PathBuf) {
let (e, dir) = temp_engine("mainnet");
let net = Network::MainNetwork;
let seed = crate::keys::seed_from_mnemonic(&crate::keys::generate_mnemonic()).unwrap();
let key = crate::keys::spending_key(&net, &seed).unwrap().to_unified_full_viewing_key();
let birthday = zcash_client_backend::data_api::AccountBirthday::from_parts(
zcash_client_backend::data_api::chain::ChainState::empty(
3_500_000.into(),
zcash_primitives::block::BlockHash([0; 32]),
),
None,
);
store::import_viewing_key(&mut lock(&e.db), &key, &birthday).unwrap();
(e, dir)
}

#[test]
fn a_mainnet_view_only_wallet_never_lends_its_key() {
// The rule the app ships with (wizard#61 keeps it): even with an
// account whose key could be lent, nothing is.
let (e, dir) = mainnet_view_only();
assert!(store::orchard_uivk(&lock(&e.db)).is_ok());
assert!(e.lantern_wake_keys().ivk.is_none());
assert!(matches!(e.lantern_set_scanning(true), Err(EngineError::MainnetViewOnly(_))));
let _ = std::fs::remove_dir_all(dir);
}

#[cfg(feature = "host-mainnet-alerts")]
#[test]
fn the_host_tool_can_lend_a_throwaway_mainnet_key() {
let (e, dir) = mainnet_view_only();
e.host_lend_mainnet_key();
assert!(e.alerts_allowed(true).is_ok());
let ivk = e.lantern_wake_keys().ivk.expect("lent");
assert!(ivk.starts_with("uivk1"), "a mainnet Orchard IVK");
let _ = std::fs::remove_dir_all(dir);
}

#[test]
fn mainnet_allows_wakeups_but_never_lends_a_key() {
let (e, dir) = temp_engine("mainnet");
Expand Down
9 changes: 9 additions & 0 deletions engine/src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,15 @@ pub struct WalletEngine {
inner: engine::WalletEngine,
}

/// Not exported to Swift or Kotlin.
#[cfg(feature = "host-mainnet-alerts")]
impl WalletEngine {
/// Host tool only (wizard#61): `engine::WalletEngine::host_lend_mainnet_key`.
pub fn host_lend_mainnet_key(&self) {
self.inner.host_lend_mainnet_key();
}
}

#[uniffi::export]
impl WalletEngine {
#[uniffi::constructor]
Expand Down
2 changes: 2 additions & 0 deletions scripts/check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ if [ "$what" = all ] || [ "$what" = rust ]; then
cargo fmt --check
step "cargo clippy"
cargo clippy --all-targets -- -D warnings
cargo clippy --all-targets --features host-mainnet-alerts -- -D warnings
step "cargo test"
cargo test
cargo test --lib --features host-mainnet-alerts
if command -v cargo-deny >/dev/null; then
step "cargo deny"
cargo deny check
Expand Down
Loading