-
Notifications
You must be signed in to change notification settings - Fork 222
/
qtc.rs
1471 lines (1325 loc) · 53.1 KB
/
qtc.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use bincode::{deserialize, serialize};
use bs58;
use fin_plan_program::FinPlanState;
use fin_plan_transaction::FinPlanTransaction;
use chrono::prelude::*;
use clap::ArgMatches;
use blockthread::NodeInfo;
use faucet::DroneRequest;
use fullnode::Config;
use hash::Hash;
use reqwest;
use reqwest::header::CONTENT_TYPE;
use ring::rand::SystemRandom;
use ring::signature::Ed25519KeyPair;
use serde_json::{self, Value};
use signature::{Keypair, KeypairUtil, Signature};
use xpz_program_interface::pubkey::Pubkey;
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{Error, ErrorKind, Write};
use std::mem::size_of;
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use std::{error, fmt, mem};
use builtin_tansaction::SystemTransaction;
use transaction::Transaction;
#[derive(Debug, PartialEq)]
pub enum QtcCommand {
Address,
AirDrop(i64),
Balance,
Cancel(Pubkey),
Confirm(Signature),
Pay(
i64,
Pubkey,
Option<DateTime<Utc>>,
Option<Pubkey>,
Option<Vec<Pubkey>>,
Option<Pubkey>,
),
TimeElapsed(Pubkey, Pubkey, DateTime<Utc>),
Witness(Pubkey, Pubkey),
}
#[derive(Debug, Clone)]
pub enum QtcError {
CommandNotRecognized(String),
BadParameter(String),
RpcRequestError(String),
}
impl fmt::Display for QtcError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "invalid")
}
}
impl error::Error for QtcError {
fn description(&self) -> &str {
"invalid"
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
pub struct QtcConfig {
pub leader: NodeInfo,
pub id: Keypair,
pub faucet_addr: SocketAddr,
pub rpc_addr: String,
pub command: QtcCommand,
}
impl Default for QtcConfig {
fn default() -> QtcConfig {
let default_addr = socketaddr!(0, 8000);
QtcConfig {
leader: NodeInfo::new_with_socketaddr(&default_addr),
id: Keypair::new(),
faucet_addr: default_addr,
rpc_addr: default_addr.to_string(),
command: QtcCommand::Balance,
}
}
}
pub fn parse_command(
pubkey: Pubkey,
matches: &ArgMatches,
) -> Result<QtcCommand, Box<error::Error>> {
let response = match matches.subcommand() {
("address", Some(_address_matches)) => Ok(QtcCommand::Address),
("airdrop", Some(airdrop_matches)) => {
let tokens = airdrop_matches.value_of("tokens").unwrap().parse()?;
Ok(QtcCommand::AirDrop(tokens))
}
("balance", Some(_balance_matches)) => Ok(QtcCommand::Balance),
("cancel", Some(cancel_matches)) => {
let pubkey_vec = bs58::decode(cancel_matches.value_of("process-id").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", cancel_matches.usage());
Err(QtcError::BadParameter("Invalid public key".to_string()))?;
}
let process_id = Pubkey::new(&pubkey_vec);
Ok(QtcCommand::Cancel(process_id))
}
("confirm", Some(confirm_matches)) => {
let signatures = bs58::decode(confirm_matches.value_of("signature").unwrap())
.into_vec()
.expect("base58-encoded signature");
if signatures.len() == mem::size_of::<Signature>() {
let signature = Signature::new(&signatures);
Ok(QtcCommand::Confirm(signature))
} else {
eprintln!("{}", confirm_matches.usage());
Err(QtcError::BadParameter("Invalid signature".to_string()))
}
}
("pay", Some(pay_matches)) => {
let tokens = pay_matches.value_of("tokens").unwrap().parse()?;
let to = if pay_matches.is_present("to") {
let pubkey_vec = bs58::decode(pay_matches.value_of("to").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", pay_matches.usage());
Err(QtcError::BadParameter(
"Invalid to public key".to_string(),
))?;
}
Pubkey::new(&pubkey_vec)
} else {
pubkey
};
let timestamp = if pay_matches.is_present("timestamp") {
let date_string = if !pay_matches.value_of("timestamp").unwrap().contains('Z') {
format!("\"{}Z\"", pay_matches.value_of("timestamp").unwrap())
} else {
format!("\"{}\"", pay_matches.value_of("timestamp").unwrap())
};
Some(serde_json::from_str(&date_string)?)
} else {
None
};
let timestamp_pubkey = if pay_matches.is_present("timestamp-pubkey") {
let pubkey_vec = bs58::decode(pay_matches.value_of("timestamp-pubkey").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", pay_matches.usage());
Err(QtcError::BadParameter(
"Invalid timestamp public key".to_string(),
))?;
}
Some(Pubkey::new(&pubkey_vec))
} else {
None
};
let witness_vec = if pay_matches.is_present("witness") {
let witnesses = pay_matches.values_of("witness").unwrap();
let mut collection = Vec::new();
for witness in witnesses {
let pubkey_vec = bs58::decode(witness)
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", pay_matches.usage());
Err(QtcError::BadParameter(
"Invalid witness public key".to_string(),
))?;
}
collection.push(Pubkey::new(&pubkey_vec));
}
Some(collection)
} else {
None
};
let cancelable = if pay_matches.is_present("cancelable") {
Some(pubkey)
} else {
None
};
Ok(QtcCommand::Pay(
tokens,
to,
timestamp,
timestamp_pubkey,
witness_vec,
cancelable,
))
}
("send-signature", Some(sig_matches)) => {
let pubkey_vec = bs58::decode(sig_matches.value_of("to").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", sig_matches.usage());
Err(QtcError::BadParameter("Invalid public key".to_string()))?;
}
let to = Pubkey::new(&pubkey_vec);
let pubkey_vec = bs58::decode(sig_matches.value_of("process-id").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", sig_matches.usage());
Err(QtcError::BadParameter("Invalid public key".to_string()))?;
}
let process_id = Pubkey::new(&pubkey_vec);
Ok(QtcCommand::Witness(to, process_id))
}
("send-timestamp", Some(timestamp_matches)) => {
let pubkey_vec = bs58::decode(timestamp_matches.value_of("to").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", timestamp_matches.usage());
Err(QtcError::BadParameter("Invalid public key".to_string()))?;
}
let to = Pubkey::new(&pubkey_vec);
let pubkey_vec = bs58::decode(timestamp_matches.value_of("process-id").unwrap())
.into_vec()
.expect("base58-encoded public key");
if pubkey_vec.len() != mem::size_of::<Pubkey>() {
eprintln!("{}", timestamp_matches.usage());
Err(QtcError::BadParameter("Invalid public key".to_string()))?;
}
let process_id = Pubkey::new(&pubkey_vec);
let dt = if timestamp_matches.is_present("datetime") {
// Parse input for serde_json
let date_string = if !timestamp_matches
.value_of("datetime")
.unwrap()
.contains('Z')
{
format!("\"{}Z\"", timestamp_matches.value_of("datetime").unwrap())
} else {
format!("\"{}\"", timestamp_matches.value_of("datetime").unwrap())
};
serde_json::from_str(&date_string)?
} else {
Utc::now()
};
Ok(QtcCommand::TimeElapsed(to, process_id, dt))
}
("", None) => {
eprintln!("{}", matches.usage());
Err(QtcError::CommandNotRecognized(
"no subcommand given".to_string(),
))
}
_ => unreachable!(),
}?;
Ok(response)
}
pub fn process_command(config: &QtcConfig) -> Result<String, Box<error::Error>> {
match config.command {
QtcCommand::Address => Ok(format!("{}", config.id.pubkey())),
QtcCommand::AirDrop(tokens) => {
println!(
"Requesting airdrop of {:?} tokens from {}",
tokens, config.faucet_addr
);
let params = json!(format!("{}", config.id.pubkey()));
let previous_balance = match QtcRpcRequest::GetBalance
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_i64()
{
Some(tokens) => tokens,
None => Err(QtcError::RpcRequestError(
"Received result of an unexpected type".to_string(),
))?,
};
request_airdrop(&config.faucet_addr, &config.id.pubkey(), tokens as u64)?;
let mut current_balance = previous_balance;
for _ in 0..20 {
sleep(Duration::from_millis(500));
let params = json!(format!("{}", config.id.pubkey()));
current_balance = QtcRpcRequest::GetBalance
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_i64()
.unwrap_or(previous_balance);
if previous_balance != current_balance {
break;
}
println!(".");
}
if current_balance - previous_balance != tokens {
Err("Airdrop failed!")?;
}
Ok(format!("Your balance is: {:?}", current_balance))
}
QtcCommand::Balance => {
println!("Balance requested...");
let params = json!(format!("{}", config.id.pubkey()));
let balance = QtcRpcRequest::GetBalance
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_i64();
match balance {
Some(0) => Ok("No account found! Request an airdrop to get started.".to_string()),
Some(tokens) => Ok(format!("Your balance is: {:?}", tokens)),
None => Err(QtcError::RpcRequestError(
"Received result of an unexpected type".to_string(),
))?,
}
}
QtcCommand::Cancel(pubkey) => {
let last_id = get_last_id(&config)?;
let tx =
Transaction::fin_plan_new_signature(&config.id, pubkey, config.id.pubkey(), last_id);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(signature_str.to_string())
}
QtcCommand::Confirm(signature) => {
let params = json!(format!("{}", signature));
let confirmation = QtcRpcRequest::ConfirmTransaction
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_bool();
match confirmation {
Some(b) => {
if b {
Ok("Confirmed".to_string())
} else {
Ok("Not found".to_string())
}
}
None => Err(QtcError::RpcRequestError(
"Received result of an unexpected type".to_string(),
))?,
}
}
QtcCommand::Pay(tokens, to, timestamp, timestamp_pubkey, ref witnesses, cancelable) => {
let last_id = get_last_id(&config)?;
if timestamp == None && *witnesses == None {
let tx = Transaction::system_new(&config.id, to, tokens, last_id);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(signature_str.to_string())
} else if *witnesses == None {
let dt = timestamp.unwrap();
let dt_pubkey = match timestamp_pubkey {
Some(pubkey) => pubkey,
None => config.id.pubkey(),
};
let contract_funds = Keypair::new();
let contract_state = Keypair::new();
let fin_plan_program_id = FinPlanState::id();
let tx = Transaction::system_create(
&config.id,
contract_funds.pubkey(),
last_id,
tokens,
0,
fin_plan_program_id,
0,
);
let _signature_str = serialize_and_send_tx(&config, &tx)?;
let tx = Transaction::system_create(
&config.id,
contract_state.pubkey(),
last_id,
1,
196,
fin_plan_program_id,
0,
);
let _signature_str = serialize_and_send_tx(&config, &tx)?;
let tx = Transaction::fin_plan_new_on_date(
&contract_funds,
to,
contract_state.pubkey(),
dt,
dt_pubkey,
cancelable,
tokens,
last_id,
);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(json!({
"signature": signature_str,
"processId": format!("{}", contract_state.pubkey()),
}).to_string())
} else if timestamp == None {
let last_id = get_last_id(&config)?;
let witness = if let Some(ref witness_vec) = *witnesses {
witness_vec[0]
} else {
Err(QtcError::BadParameter(
"Could not parse required signature pubkey(s)".to_string(),
))?
};
let contract_funds = Keypair::new();
let contract_state = Keypair::new();
let fin_plan_program_id = FinPlanState::id();
let tx = Transaction::system_create(
&config.id,
contract_funds.pubkey(),
last_id,
tokens,
0,
fin_plan_program_id,
0,
);
let _signature_str = serialize_and_send_tx(&config, &tx)?;
let tx = Transaction::system_create(
&config.id,
contract_state.pubkey(),
last_id,
1,
196,
fin_plan_program_id,
0,
);
let _signature_str = serialize_and_send_tx(&config, &tx)?;
let tx = Transaction::fin_plan_new_when_signed(
&contract_funds,
to,
contract_state.pubkey(),
witness,
cancelable,
tokens,
last_id,
);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(json!({
"signature": signature_str,
"processId": format!("{}", contract_state.pubkey()),
}).to_string())
} else {
Ok("Combo transactions not yet handled".to_string())
}
}
QtcCommand::TimeElapsed(to, pubkey, dt) => {
let params = json!(format!("{}", config.id.pubkey()));
let balance = QtcRpcRequest::GetBalance
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_i64();
if let Some(0) = balance {
request_airdrop(&config.faucet_addr, &config.id.pubkey(), 1)?;
}
let last_id = get_last_id(&config)?;
let tx = Transaction::fin_plan_new_timestamp(&config.id, pubkey, to, dt, last_id);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(signature_str.to_string())
}
QtcCommand::Witness(to, pubkey) => {
let last_id = get_last_id(&config)?;
let params = json!(format!("{}", config.id.pubkey()));
let balance = QtcRpcRequest::GetBalance
.make_rpc_request(&config.rpc_addr, 1, Some(params))?
.as_i64();
if let Some(0) = balance {
request_airdrop(&config.faucet_addr, &config.id.pubkey(), 1)?;
}
let tx = Transaction::fin_plan_new_signature(&config.id, pubkey, to, last_id);
let signature_str = serialize_and_send_tx(&config, &tx)?;
Ok(signature_str.to_string())
}
}
}
pub fn read_leader(path: &str) -> Result<Config, QtcError> {
let file = File::open(path.to_string()).or_else(|err| {
Err(QtcError::BadParameter(format!(
"{}: Unable to open leader file: {}",
err, path
)))
})?;
serde_json::from_reader(file).or_else(|err| {
Err(QtcError::BadParameter(format!(
"{}: Failed to parse leader file: {}",
err, path
)))
})
}
pub fn request_airdrop(
faucet_addr: &SocketAddr,
id: &Pubkey,
tokens: u64,
) -> Result<Signature, Error> {
// TODO: make this async tokio client
let mut stream = TcpStream::connect(faucet_addr)?;
let req = DroneRequest::GetAirdrop {
airdrop_request_amount: tokens,
client_pubkey: *id,
};
let tx = serialize(&req).expect("serialize faucet request");
stream.write_all(&tx)?;
let mut buffer = [0; size_of::<Signature>()];
stream
.read_exact(&mut buffer)
.or_else(|_| Err(Error::new(ErrorKind::Other, "Airdrop failed")))?;
let signature: Signature = deserialize(&buffer).or_else(|err| {
Err(Error::new(
ErrorKind::Other,
format!("deserialize signature in request_airdrop: {:?}", err),
))
})?;
// TODO: add timeout to this function, in case of unresponsive faucet
Ok(signature)
}
pub fn gen_keypair_file(outfile: String) -> Result<String, Box<error::Error>> {
let rnd = SystemRandom::new();
let pkcs8_bytes = Ed25519KeyPair::generate_pkcs8(&rnd)?;
let serialized = serde_json::to_string(&pkcs8_bytes.to_vec())?;
if outfile != "-" {
if let Some(outdir) = Path::new(&outfile).parent() {
fs::create_dir_all(outdir)?;
}
let mut f = File::create(outfile)?;
f.write_all(&serialized.clone().into_bytes())?;
}
Ok(serialized)
}
pub enum QtcRpcRequest {
ConfirmTransaction,
GetAccountInfo,
GetBalance,
GetFinality,
GetLastId,
GetTransactionCount,
RequestAirdrop,
SendTransaction,
}
impl QtcRpcRequest {
fn make_rpc_request(
&self,
rpc_addr: &str,
id: u64,
params: Option<Value>,
) -> Result<Value, Box<error::Error>> {
let jsonrpc = "2.0";
let method = match self {
QtcRpcRequest::ConfirmTransaction => "confirmTransaction",
QtcRpcRequest::GetAccountInfo => "getAccountInfo",
QtcRpcRequest::GetBalance => "getBalance",
QtcRpcRequest::GetFinality => "getFinality",
QtcRpcRequest::GetLastId => "getLastId",
QtcRpcRequest::GetTransactionCount => "getTransactionCount",
QtcRpcRequest::RequestAirdrop => "requestAirdrop",
QtcRpcRequest::SendTransaction => "sendTransaction",
};
let client = reqwest::Client::new();
let mut request = json!({
"jsonrpc": jsonrpc,
"id": id,
"method": method,
});
if let Some(param_string) = params {
request["params"] = json!(vec![param_string]);
}
let mut response = client
.post(rpc_addr)
.header(CONTENT_TYPE, "application/json")
.body(request.to_string())
.send()?;
let json: Value = serde_json::from_str(&response.text()?)?;
if json["error"].is_object() {
Err(QtcError::RpcRequestError(format!(
"RPC Error response: {}",
serde_json::to_string(&json["error"]).unwrap()
)))?
}
Ok(json["result"].clone())
}
}
fn get_last_id(config: &QtcConfig) -> Result<Hash, Box<error::Error>> {
let result = QtcRpcRequest::GetLastId.make_rpc_request(&config.rpc_addr, 1, None)?;
if result.as_str().is_none() {
Err(QtcError::RpcRequestError(
"Received bad last_id".to_string(),
))?
}
let last_id_str = result.as_str().unwrap();
let last_id_vec = bs58::decode(last_id_str)
.into_vec()
.map_err(|_| QtcError::RpcRequestError("Received bad last_id".to_string()))?;
Ok(Hash::new(&last_id_vec))
}
fn serialize_and_send_tx(
config: &QtcConfig,
tx: &Transaction,
) -> Result<String, Box<error::Error>> {
let serialized = serialize(tx).unwrap();
let params = json!(serialized);
let signature =
QtcRpcRequest::SendTransaction.make_rpc_request(&config.rpc_addr, 2, Some(params))?;
if signature.as_str().is_none() {
Err(QtcError::RpcRequestError(
"Received result of an unexpected type".to_string(),
))?
}
Ok(signature.as_str().unwrap().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use transaction_processor::TransactionProcessor;
use clap::{App, Arg, SubCommand};
use blockthread::Node;
use faucet::run_local_faucet;
use fullnode::Fullnode;
use ledger::LedgerWriter;
use mint::Mint;
use signature::{read_keypair, read_pkcs8, Keypair, KeypairUtil};
use std::fs::remove_dir_all;
use std::sync::mpsc::channel;
fn tmp_ledger(name: &str, mint: &Mint) -> String {
use std::env;
let out_dir = env::var("OUT_DIR").unwrap_or_else(|_| "target".to_string());
let keypair = Keypair::new();
let path = format!("{}/tmp-ledger-{}-{}", out_dir, name, keypair.pubkey());
let mut writer = LedgerWriter::open(&path, true).unwrap();
writer.write_entries(mint.create_entries()).unwrap();
path
}
#[test]
fn test_qtc_parse_command() {
let test_commands = App::new("test")
.subcommand(SubCommand::with_name("address").about("Get your public key"))
.subcommand(
SubCommand::with_name("airdrop")
.about("Request a batch of tokens")
.arg(
Arg::with_name("tokens")
.index(1)
.value_name("NUM")
.takes_value(true)
.required(true)
.help("The number of tokens to request"),
),
).subcommand(SubCommand::with_name("balance").about("Get your balance"))
.subcommand(
SubCommand::with_name("cancel")
.about("Cancel a transfer")
.arg(
Arg::with_name("process-id")
.index(1)
.value_name("PROCESS_ID")
.takes_value(true)
.required(true)
.help("The process id of the transfer to cancel"),
),
).subcommand(
SubCommand::with_name("confirm")
.about("Confirm transaction by signature")
.arg(
Arg::with_name("signature")
.index(1)
.value_name("SIGNATURE")
.takes_value(true)
.required(true)
.help("The transaction signature to confirm"),
),
).subcommand(
SubCommand::with_name("pay")
.about("Send a payment")
.arg(
Arg::with_name("to")
.index(1)
.value_name("PUBKEY")
.takes_value(true)
.required(true)
.help("The pubkey of recipient"),
).arg(
Arg::with_name("tokens")
.index(2)
.value_name("NUM")
.takes_value(true)
.required(true)
.help("The number of tokens to send"),
).arg(
Arg::with_name("timestamp")
.long("after")
.value_name("DATETIME")
.takes_value(true)
.help("A timestamp after which transaction will execute"),
).arg(
Arg::with_name("timestamp-pubkey")
.long("require-timestamp-from")
.value_name("PUBKEY")
.takes_value(true)
.requires("timestamp")
.help("Require timestamp from this third party"),
).arg(
Arg::with_name("witness")
.long("require-signature-from")
.value_name("PUBKEY")
.takes_value(true)
.multiple(true)
.use_delimiter(true)
.help("Any third party signatures required to unlock the tokens"),
).arg(
Arg::with_name("cancelable")
.long("cancelable")
.takes_value(false),
),
).subcommand(
SubCommand::with_name("send-signature")
.about("Send a signature to authorize a transfer")
.arg(
Arg::with_name("to")
.index(1)
.value_name("PUBKEY")
.takes_value(true)
.required(true)
.help("The pubkey of recipient"),
).arg(
Arg::with_name("process-id")
.index(2)
.value_name("PROCESS_ID")
.takes_value(true)
.required(true)
.help("The process id of the transfer to authorize"),
),
).subcommand(
SubCommand::with_name("send-timestamp")
.about("Send a timestamp to unlock a transfer")
.arg(
Arg::with_name("to")
.index(1)
.value_name("PUBKEY")
.takes_value(true)
.required(true)
.help("The pubkey of recipient"),
).arg(
Arg::with_name("process-id")
.index(2)
.value_name("PROCESS_ID")
.takes_value(true)
.required(true)
.help("The process id of the transfer to unlock"),
).arg(
Arg::with_name("datetime")
.long("date")
.value_name("DATETIME")
.takes_value(true)
.help("Optional arbitrary timestamp to apply"),
),
);
let pubkey = Keypair::new().pubkey();
let pubkey_string = format!("{}", pubkey);
let witness0 = Keypair::new().pubkey();
let witness0_string = format!("{}", witness0);
let witness1 = Keypair::new().pubkey();
let witness1_string = format!("{}", witness1);
let dt = Utc.ymd(2018, 9, 19).and_hms(17, 30, 59);
let test_airdrop = test_commands
.clone()
.get_matches_from(vec!["test", "airdrop", "50"]);
assert_eq!(
parse_command(pubkey, &test_airdrop).unwrap(),
QtcCommand::AirDrop(50)
);
let test_bad_airdrop = test_commands
.clone()
.get_matches_from(vec!["test", "airdrop", "notint"]);
assert!(parse_command(pubkey, &test_bad_airdrop).is_err());
let test_cancel =
test_commands
.clone()
.get_matches_from(vec!["test", "cancel", &pubkey_string]);
assert_eq!(
parse_command(pubkey, &test_cancel).unwrap(),
QtcCommand::Cancel(pubkey)
);
let signature = Signature::new(&vec![1; 64]);
let signature_string = format!("{:?}", signature);
let test_confirm =
test_commands
.clone()
.get_matches_from(vec!["test", "confirm", &signature_string]);
assert_eq!(
parse_command(pubkey, &test_confirm).unwrap(),
QtcCommand::Confirm(signature)
);
let test_bad_signature = test_commands
.clone()
.get_matches_from(vec!["test", "confirm", "deadbeef"]);
assert!(parse_command(pubkey, &test_bad_signature).is_err());
let test_pay =
test_commands
.clone()
.get_matches_from(vec!["test", "pay", &pubkey_string, "50"]);
assert_eq!(
parse_command(pubkey, &test_pay).unwrap(),
QtcCommand::Pay(50, pubkey, None, None, None, None)
);
let test_bad_pubkey = test_commands
.clone()
.get_matches_from(vec!["test", "pay", "deadbeef", "50"]);
assert!(parse_command(pubkey, &test_bad_pubkey).is_err());
let test_pay_multiple_witnesses = test_commands.clone().get_matches_from(vec![
"test",
"pay",
&pubkey_string,
"50",
"--require-signature-from",
&witness0_string,
"--require-signature-from",
&witness1_string,
]);
assert_eq!(
parse_command(pubkey, &test_pay_multiple_witnesses).unwrap(),
QtcCommand::Pay(50, pubkey, None, None, Some(vec![witness0, witness1]), None)
);
let test_pay_single_witness = test_commands.clone().get_matches_from(vec![
"test",
"pay",
&pubkey_string,
"50",
"--require-signature-from",
&witness0_string,
]);
assert_eq!(
parse_command(pubkey, &test_pay_single_witness).unwrap(),
QtcCommand::Pay(50, pubkey, None, None, Some(vec![witness0]), None)
);
let test_pay_timestamp = test_commands.clone().get_matches_from(vec![
"test",
"pay",
&pubkey_string,
"50",
"--after",
"2018-09-19T17:30:59",
"--require-timestamp-from",
&witness0_string,
]);
assert_eq!(
parse_command(pubkey, &test_pay_timestamp).unwrap(),
QtcCommand::Pay(50, pubkey, Some(dt), Some(witness0), None, None)
);
let test_send_signature = test_commands.clone().get_matches_from(vec![
"test",
"send-signature",
&pubkey_string,
&pubkey_string,
]);
assert_eq!(
parse_command(pubkey, &test_send_signature).unwrap(),
QtcCommand::Witness(pubkey, pubkey)
);
let test_pay_multiple_witnesses = test_commands.clone().get_matches_from(vec![
"test",
"pay",
&pubkey_string,
"50",
"--after",
"2018-09-19T17:30:59",
"--require-signature-from",
&witness0_string,
"--require-timestamp-from",
&witness0_string,
"--require-signature-from",
&witness1_string,
]);
assert_eq!(
parse_command(pubkey, &test_pay_multiple_witnesses).unwrap(),
QtcCommand::Pay(
50,
pubkey,
Some(dt),
Some(witness0),
Some(vec![witness0, witness1]),
None
)
);
let test_send_timestamp = test_commands.clone().get_matches_from(vec![
"test",
"send-timestamp",
&pubkey_string,
&pubkey_string,
"--date",
"2018-09-19T17:30:59",
]);
assert_eq!(
parse_command(pubkey, &test_send_timestamp).unwrap(),
QtcCommand::TimeElapsed(pubkey, pubkey, dt)
);
let test_bad_timestamp = test_commands.clone().get_matches_from(vec![
"test",
"send-timestamp",
&pubkey_string,
&pubkey_string,
"--date",
"20180919T17:30:59",
]);
assert!(parse_command(pubkey, &test_bad_timestamp).is_err());
}
#[test]
#[ignore]
fn test_qtc_process_command() {
let leader_keypair = Keypair::new();
let leader = Node::new_localhost_with_pubkey(leader_keypair.pubkey());
let alice = Mint::new(10_000_000);
let transaction_processor = TransactionProcessor::new(&alice);
let bob_pubkey = Keypair::new().pubkey();
let leader_data = leader.info.clone();
let leader_data1 = leader.info.clone();
let ledger_path = tmp_ledger("qtc_process_command", &alice);
let mut config = QtcConfig::default();
let rpc_port = 12345; // Needs to be distinct known number to not conflict with other tests
let server = Fullnode::new_with_transaction_processor(
leader_keypair,
transaction_processor,
0,
&[],
leader,
None,
&ledger_path,