Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Begin wallet implementation #233

Merged
merged 29 commits into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
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
621 changes: 436 additions & 185 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ autotests = false
anyhow = { version = "1.0.56", features = ["backtrace"] }
axum = "0.5.6"
axum-server = "0.4.0"
bdk = { version = "0.20.0", features = ["keys-bip39", "sqlite"] }
bech32 = "0.9.0"
bitcoin = "0.28.1"
bitcoin_hashes = "0.10.0"
Expand Down
8 changes: 8 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ use {
anyhow::{anyhow, Context, Error},
axum::{extract, http::StatusCode, response::IntoResponse, routing::get, Json, Router},
axum_server::Handle,
bdk::{
database::SqliteDatabase,
keys::bip39::{Language, Mnemonic},
template::Bip84,
wallet::AddressIndex::LastUnused,
KeychainKind,
},
bech32::{FromBase32, ToBase32},
bitcoin::{
blockdata::constants::COIN_VALUE, consensus::Decodable, consensus::Encodable,
Expand All @@ -17,6 +24,7 @@ use {
chrono::{DateTime, NaiveDateTime, Utc},
clap::Parser,
derive_more::{Display, FromStr},
dirs::data_dir,
lazy_static::lazy_static,
qrcode_generator::QrCodeEcc,
redb::{Database, ReadableTable, Table, TableDefinition, WriteTransaction},
Expand Down
16 changes: 10 additions & 6 deletions src/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ mod server;
mod supply;
mod traits;
mod verify;
mod wallet;

#[derive(Parser)]
pub(crate) enum Subcommand {
Epochs,
Find(find::Find),
GeneratePrivateKey,
GeneratePaperWallets,
GeneratePrivateKey,
Index,
Info,
List(list::List),
Expand All @@ -31,25 +32,28 @@ pub(crate) enum Subcommand {
Supply,
Traits(traits::Traits),
Verify(verify::Verify),
#[clap(subcommand)]
Wallet(wallet::Wallet),
}

impl Subcommand {
pub(crate) fn run(self, options: Options) -> Result<()> {
match self {
Self::Epochs => epochs::run(),
Self::GeneratePrivateKey => generate_private_key::run(),
Self::GeneratePaperWallets => generate_paper_wallets::run(),
Self::Find(find) => find.run(options),
Self::GeneratePaperWallets => generate_paper_wallets::run(),
Self::GeneratePrivateKey => generate_private_key::run(),
Self::Index => index::run(options),
Self::Info => info::run(options),
Self::List(list) => list.run(options),
Self::Name(name) => name.run(),
Self::Mint(mint) => mint.run(),
Self::Name(name) => name.run(),
Self::Range(range) => range.run(),
Self::Supply => supply::run(),
Self::Server(server) => server.run(options),
Self::Info => info::run(options),
Self::Supply => supply::run(),
Self::Traits(traits) => traits.run(),
Self::Verify(verify) => verify.run(),
Self::Wallet(wallet) => wallet.run(),
}
}
}
19 changes: 19 additions & 0 deletions src/subcommand/wallet.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use super::*;

mod fund;
mod init;

#[derive(Parser)]
pub(crate) enum Wallet {
Init,
Fund,
}

impl Wallet {
pub(crate) fn run(self) -> Result {
match self {
Self::Init => init::run(),
Self::Fund => fund::run(),
}
}
}
33 changes: 33 additions & 0 deletions src/subcommand/wallet/fund.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use super::*;

pub(crate) fn run() -> Result {
let path = data_dir()
.ok_or_else(|| anyhow!("Failed to retrieve data dir"))?
.join("ord");

if !path.exists() {
return Err(anyhow!("Wallet doesn't exist."));
}

let entropy = fs::read(path.join("entropy"))?;

let wallet = bdk::wallet::Wallet::new(
Bip84(
(Mnemonic::from_entropy(&entropy)?, None),
KeychainKind::External,
),
None,
Network::Signet,
SqliteDatabase::new(
path
.join("wallet.sqlite")
.to_str()
.ok_or_else(|| anyhow!("Failed to convert path to str"))?
.to_string(),
),
)?;

println!("{}", wallet.get_address(LastUnused)?);

Ok(())
}
34 changes: 34 additions & 0 deletions src/subcommand/wallet/init.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use super::*;

pub(crate) fn run() -> Result {
let path = data_dir()
.ok_or_else(|| anyhow!("Failed to retrieve data dir"))?
.join("ord");

if path.exists() {
return Err(anyhow!("Wallet already exists."));
}

fs::create_dir_all(&path)?;

let seed = Mnemonic::generate_in_with(&mut rand::thread_rng(), Language::English, 12)?;

fs::write(path.join("entropy"), seed.to_entropy())?;

bdk::wallet::Wallet::new(
Bip84((seed, None), KeychainKind::External),
None,
Network::Signet,
SqliteDatabase::new(
path
.join("wallet.sqlite")
.to_str()
.ok_or_else(|| anyhow!("Failed to convert path to str"))?
.to_string(),
),
)?;

eprintln!("Wallet initialized.");

Ok(())
}
17 changes: 15 additions & 2 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use {
std::{
collections::BTreeMap,
error::Error,
ffi::OsString,
fs,
net::TcpListener,
process::{Command, Stdio},
Expand All @@ -40,6 +41,7 @@ mod server;
mod supply;
mod traits;
mod version;
mod wallet;

type Result<T = ()> = std::result::Result<T, Box<dyn Error>>;

Expand Down Expand Up @@ -84,10 +86,11 @@ struct TransactionOptions<'a> {

struct Test {
args: Vec<String>,
envs: Vec<(OsString, OsString)>,
events: Vec<Event>,
expected_status: i32,
expected_stderr: Option<String>,
expected_stdout: Expected,
events: Vec<Event>,
tempdir: TempDir,
}

Expand All @@ -99,10 +102,11 @@ impl Test {
fn with_tempdir(tempdir: TempDir) -> Self {
Self {
args: Vec::new(),
envs: Vec::new(),
events: Vec::new(),
expected_status: 0,
expected_stderr: None,
expected_stdout: Expected::String(String::new()),
events: Vec::new(),
tempdir,
}
}
Expand Down Expand Up @@ -141,6 +145,14 @@ impl Test {
}
}

fn set_home_to_tempdir(mut self) -> Self {
self
.envs
.push((OsString::from("HOME"), OsString::from(self.tempdir.path())));

self
}

fn expected_stderr(self, expected_stderr: &str) -> Self {
Self {
expected_stderr: Some(expected_stderr.to_owned()),
Expand Down Expand Up @@ -204,6 +216,7 @@ impl Test {
};

let child = Command::new(executable_path("ord"))
.envs(self.envs)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(if self.expected_stderr.is_some() {
Expand Down
105 changes: 105 additions & 0 deletions tests/wallet.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use super::*;

fn path(path: &str) -> String {
if cfg!(target_os = "macos") {
format!("Library/Application Support/{}", path)
} else {
format!(".local/share/{}", path)
}
}

#[test]
fn init_existing_wallet() -> Result {
let tempdir = Test::new()?
.command("wallet init")
.set_home_to_tempdir()
.expected_status(0)
.expected_stderr("Wallet initialized.\n")
.output()?
.tempdir;

assert!(tempdir.path().join(path("ord/wallet.sqlite")).exists());

assert!(tempdir.path().join(path("ord/entropy")).exists());

Test::with_tempdir(tempdir)
.command("wallet init")
.set_home_to_tempdir()
.expected_status(1)
.expected_stderr("error: Wallet already exists.\n")
.run()
}

#[test]
fn init_nonexistent_wallet() -> Result {
let tempdir = Test::new()?
.command("wallet init")
.set_home_to_tempdir()
.expected_status(0)
.expected_stderr("Wallet initialized.\n")
.output()?
.tempdir;

assert!(tempdir.path().join(path("ord/wallet.sqlite")).exists());

assert!(tempdir.path().join(path("ord/entropy")).exists());

Ok(())
}

#[test]
fn load_corrupted_entropy() -> Result {
let tempdir = Test::new()?
.command("wallet init")
.set_home_to_tempdir()
.expected_status(0)
.expected_stderr("Wallet initialized.\n")
.output()?
.tempdir;

let entropy_path = tempdir.path().join(path("ord/entropy"));

assert!(entropy_path.exists());

let mut entropy = fs::read(&entropy_path)?;
entropy[0] ^= 0b0000_1000;

fs::write(&entropy_path, entropy)?;

Test::with_tempdir(tempdir)
.command("wallet fund")
.set_home_to_tempdir()
.expected_status(1)
.expected_stderr("error: ChecksumMismatch\n")
.run()?;

Ok(())
}

#[test]
fn fund_existing_wallet() -> Result {
let tempdir = Test::new()?
.command("wallet init")
.set_home_to_tempdir()
.expected_status(0)
.expected_stderr("Wallet initialized.\n")
.set_home_to_tempdir()
.output()?
.tempdir;

Test::with_tempdir(tempdir)
.command("wallet fund")
.set_home_to_tempdir()
.stdout_regex("^tb1.*\n")
.run()
}

#[test]
fn fund_nonexistent_wallet() -> Result {
Test::new()?
.command("wallet fund")
.set_home_to_tempdir()
.expected_status(1)
.expected_stderr("error: Wallet doesn't exist.\n")
.run()
}