-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.rs
259 lines (220 loc) · 8.99 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! A simple CLI wallet. For now it is a toy just to start testing things out.
use anyhow::anyhow;
use clap::Parser;
use jsonrpsee::{
core::client::ClientT,
http_client::{HttpClient, HttpClientBuilder},
rpc_params,
};
use parity_scale_codec::{Decode, Encode};
use runtime::OuterVerifier;
use std::path::PathBuf;
use tuxedo_core::{
types::{Output, OutputRef},
verifier::*,
};
use sp_core::H256;
mod amoeba;
mod cli;
mod keystore;
mod money;
mod output_filter;
mod rpc;
mod sync;
use cli::{Cli, Command};
/// The default RPC endpoint for the wallet to connect to
const DEFAULT_ENDPOINT: &str = "http://localhost:9933";
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
// Parse command line args
let cli = Cli::parse();
// Setup the data paths.
let data_path = cli.data_path.unwrap_or_else(default_data_path);
let keystore_path = data_path.join("keystore");
let db_path = data_path.join("wallet_database");
// Setup the keystore
let keystore = sc_keystore::LocalKeystore::open(keystore_path.clone(), None)?;
// Insert the example Shawn key so example transactions can be signed.
crate::keystore::insert_default_key_for_this_session(&keystore)?;
// Setup jsonrpsee and endpoint-related information.
// https://github.com/paritytech/jsonrpsee/blob/master/examples/examples/http.rs
let client = HttpClientBuilder::default().build(cli.endpoint)?;
// Read node's genesis block.
let node_genesis_hash = rpc::node_get_block_hash(0, &client)
.await?
.expect("node should be able to return some genesis hash");
let node_genesis_block = rpc::node_get_block(node_genesis_hash, &client)
.await?
.expect("node should be able to return some genesis block");
log::debug!("Node's Genesis block::{:?}", node_genesis_hash);
// Open the local database
let db = sync::open_db(db_path, node_genesis_hash, node_genesis_block)?;
let num_blocks =
sync::height(&db)?.expect("db should be initialized automatically when opening.");
log::info!("Number of blocks in the db: {num_blocks}");
// The filter function that will determine whether the local database should
// track a given utxo is based on whether that utxo is privately owned by a
// key that is in our keystore.
let keystore_filter = |v: &OuterVerifier| -> bool {
matches![
v,
OuterVerifier::SigCheck(SigCheck { owner_pubkey }) if crate::keystore::has_key(&keystore, owner_pubkey)
]
};
if !sled::Db::was_recovered(&db) {
// Before synchronizing init the database with the current Genesis utxos
sync::init_from_genesis(&db, &client, &keystore_filter).await?;
}
// Synchronize the wallet with attached node unless instructed otherwise.
if cli.no_sync {
log::warn!("Skipping sync with node. Using previously synced information.")
} else {
sync::synchronize(&db, &client, &keystore_filter).await?;
log::info!(
"Wallet database synchronized with node to height {:?}",
sync::height(&db)?.expect("We just synced, so there is a height available")
);
}
// Dispatch to proper subcommand
match cli.command {
Some(Command::AmoebaDemo) => amoeba::amoeba_demo(&client).await,
// Command::MultiSigDemo => multi_sig::multi_sig_demo(&client).await,
Some(Command::VerifyCoin { output_ref }) => {
println!("Details of coin {}:", hex::encode(output_ref.encode()));
// Print the details from storage
let (coin_from_storage, verifier_from_storage) =
money::get_coin_from_storage(&output_ref, &client).await?;
print!("Found in storage. Value: {}, ", coin_from_storage.0);
pretty_print_verifier(&verifier_from_storage);
// Print the details from the local db
match sync::get_unspent(&db, &output_ref)? {
Some((owner, amount)) => {
println!("Found in local db. Value: {amount}, owned by {owner}");
}
None => {
println!("Not found in local db");
}
}
Ok(())
}
Some(Command::SpendCoins(args)) => money::spend_coins(&db, &client, &keystore, args).await,
Some(Command::InsertKey { seed }) => crate::keystore::insert_key(&keystore, &seed),
Some(Command::GenerateKey { password }) => {
crate::keystore::generate_key(&keystore, password)?;
Ok(())
}
Some(Command::ShowKeys) => {
crate::keystore::get_keys(&keystore)?.for_each(|pubkey| {
println!("key: 0x{}", hex::encode(pubkey));
});
Ok(())
}
Some(Command::RemoveKey { pub_key }) => {
println!("CAUTION!!! About permanently remove {pub_key}. This action CANNOT BE REVERSED. Type \"proceed\" to confirm deletion.");
let mut confirmation = String::new();
std::io::stdin()
.read_line(&mut confirmation)
.expect("Failed to read line");
if confirmation.trim() == "proceed" {
crate::keystore::remove_key(&keystore_path, &pub_key)
} else {
println!("Deletion aborted. That was close.");
Ok(())
}
}
Some(Command::ShowBalance) => {
println!("Balance Summary");
let mut total = 0;
let balances = sync::get_balances(&db)?;
for (account, balance) in balances {
total += balance;
println!("{account}: {balance}");
}
println!("--------------------");
println!("total : {total}");
Ok(())
}
Some(Command::ShowAllOutputs) => {
println!("###### Unspent outputs ###########");
sync::print_unspent_tree(&db)?;
Ok(())
}
None => {
log::info!("No Wallet Command invoked. Exiting.");
Ok(())
}
}
}
//TODO move to rpc.rs
/// Fetch an output from chain storage given an OutputRef
pub async fn fetch_storage<V: Verifier>(
output_ref: &OutputRef,
client: &HttpClient,
) -> anyhow::Result<Output<V>> {
let ref_hex = hex::encode(output_ref.encode());
let params = rpc_params![ref_hex];
let rpc_response: Result<Option<String>, _> = client.request("state_getStorage", params).await;
let response_hex = rpc_response?.ok_or(anyhow!("Data cannot be retrieved from storage"))?;
let response_hex = strip_0x_prefix(&response_hex);
let response_bytes = hex::decode(response_hex)?;
let utxo = Output::decode(&mut &response_bytes[..])?;
Ok(utxo)
}
/// Parse a string into an H256 that represents a public key
pub(crate) fn h256_from_string(s: &str) -> anyhow::Result<H256> {
let s = strip_0x_prefix(s);
let mut bytes: [u8; 32] = [0; 32];
hex::decode_to_slice(s, &mut bytes as &mut [u8])
.map_err(|_| clap::Error::new(clap::error::ErrorKind::ValueValidation))?;
Ok(H256::from(bytes))
}
/// Parse an output ref from a string
fn output_ref_from_string(s: &str) -> Result<OutputRef, clap::Error> {
let s = strip_0x_prefix(s);
let bytes =
hex::decode(s).map_err(|_| clap::Error::new(clap::error::ErrorKind::ValueValidation))?;
OutputRef::decode(&mut &bytes[..])
.map_err(|_| clap::Error::new(clap::error::ErrorKind::ValueValidation))
}
/// Takes a string and checks for a 0x prefix. Returns a string without a 0x prefix.
fn strip_0x_prefix(s: &str) -> &str {
if &s[..2] == "0x" {
&s[2..]
} else {
s
}
}
/// Generate the platform-specific default data path for the wallet
fn default_data_path() -> PathBuf {
// This uses the directories crate.
// https://docs.rs/directories/latest/directories/struct.ProjectDirs.html
// Application developers may want to put actual qualifiers or organization here
let qualifier = "";
let organization = "";
let application = env!("CARGO_PKG_NAME");
directories::ProjectDirs::from(qualifier, organization, application)
.expect("app directories exist on all supported platforms; qed")
.data_dir()
.into()
}
/// Utility to pretty print an outer verifier
pub fn pretty_print_verifier(v: &OuterVerifier) {
match v {
OuterVerifier::SigCheck(sig_check) => {
println! {"owned by {}", sig_check.owner_pubkey}
}
OuterVerifier::UpForGrabs(_) => println!("that can be spent by anyone"),
OuterVerifier::ThresholdMultiSignature(multi_sig) => {
let string_sigs: Vec<_> = multi_sig
.signatories
.iter()
.map(|sig| format!("0x{}", hex::encode(sig)))
.collect();
println!(
"Owned by {:?}, with a threshold of {} sigs necessary",
string_sigs, multi_sig.threshold
);
}
}
}