-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathsent_payable_dao.rs
More file actions
1666 lines (1504 loc) · 62.8 KB
/
sent_payable_dao.rs
File metadata and controls
1666 lines (1504 loc) · 62.8 KB
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
// Copyright (c) 2025, MASQ (https://masq.ai) and/or its affiliates. All rights reserved.
use crate::accountant::db_access_objects::utils::{
sql_values_of_sent_tx, DaoFactoryReal, TxHash, TxIdentifiers,
};
use crate::accountant::db_access_objects::Transaction;
use crate::accountant::db_big_integer::big_int_divider::BigIntDivider;
use crate::accountant::{checked_conversion, join_with_commas, join_with_separator};
use crate::blockchain::blockchain_interface::data_structures::TxBlock;
use crate::blockchain::errors::validation_status::ValidationStatus;
use crate::database::rusqlite_wrappers::ConnectionWrapper;
use ethereum_types::H256;
use itertools::Itertools;
use masq_lib::utils::ExpectValue;
use serde_derive::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap};
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use web3::types::Address;
#[derive(Debug, PartialEq, Eq)]
pub enum SentPayableDaoError {
EmptyInput,
NoChange,
InvalidInput(String),
PartialExecution(String),
SqlExecutionFailed(String),
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct SentTx {
pub hash: TxHash,
pub receiver_address: Address,
pub amount_minor: u128,
pub timestamp: i64,
pub gas_price_minor: u128,
pub nonce: u64,
pub status: TxStatus,
}
impl Transaction for SentTx {
fn hash(&self) -> TxHash {
self.hash
}
fn receiver_address(&self) -> Address {
self.receiver_address
}
fn amount(&self) -> u128 {
self.amount_minor
}
fn timestamp(&self) -> i64 {
self.timestamp
}
fn gas_price_wei(&self) -> u128 {
self.gas_price_minor
}
fn nonce(&self) -> u64 {
self.nonce
}
fn is_failed(&self) -> bool {
false
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TxStatus {
Pending(ValidationStatus),
Confirmed {
block_hash: String,
block_number: u64,
detection: Detection,
},
}
impl PartialOrd for TxStatus {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// Manual impl of Ord for enums makes sense because the derive macro determines the ordering
// by the order of the enum variants in its declaration, not only alphabetically. Swiping
// the position of the variants makes a difference, which is counter-intuitive. Structs are not
// implemented the same way and are safe to be used with derive.
impl Ord for TxStatus {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(TxStatus::Pending(status1), TxStatus::Pending(status2)) => status1.cmp(status2),
(TxStatus::Pending(_), TxStatus::Confirmed { .. }) => Ordering::Greater,
(TxStatus::Confirmed { .. }, TxStatus::Pending(_)) => Ordering::Less,
(
TxStatus::Confirmed {
block_hash: block_hash1,
block_number: block_num1,
detection: detection1,
},
TxStatus::Confirmed {
block_hash: block_hash2,
block_number: block_num2,
detection: detection2,
},
) => block_hash1
.cmp(block_hash2)
.then_with(|| block_num1.cmp(block_num2))
.then_with(|| detection1.cmp(detection2)),
}
}
}
impl FromStr for TxStatus {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(s).map_err(|e| format!("{} in '{}'", e, s))
}
}
impl Display for TxStatus {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match serde_json::to_string(self) {
Ok(json) => write!(f, "{}", json),
// Untestable
Err(_) => write!(f, "<invalid TxStatus>"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub enum Detection {
Normal,
Reclaim,
}
impl From<TxBlock> for TxStatus {
fn from(tx_block: TxBlock) -> Self {
TxStatus::Confirmed {
block_hash: format!("{:?}", tx_block.block_hash),
block_number: u64::try_from(tx_block.block_number).expect("block number too big"),
detection: Detection::Normal,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RetrieveCondition {
IsPending,
ByHash(BTreeSet<TxHash>),
ByNonce(Vec<u64>),
}
impl Display for RetrieveCondition {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RetrieveCondition::IsPending => {
write!(f, r#"WHERE status LIKE '%"Pending":%'"#)
}
RetrieveCondition::ByHash(tx_hashes) => {
write!(
f,
"WHERE tx_hash IN ({})",
join_with_commas(tx_hashes, |hash| format!("'{:?}'", hash))
)
}
RetrieveCondition::ByNonce(nonces) => {
write!(
f,
"WHERE nonce IN ({})",
join_with_commas(nonces, |nonce| nonce.to_string())
)
}
}
}
}
pub trait SentPayableDao {
fn get_tx_identifiers(&self, hashes: &BTreeSet<TxHash>) -> TxIdentifiers;
fn insert_new_records(&self, txs: &BTreeSet<SentTx>) -> Result<(), SentPayableDaoError>;
fn retrieve_txs(&self, condition: Option<RetrieveCondition>) -> BTreeSet<SentTx>;
//TODO potentially atomically
fn confirm_txs(&self, hash_map: &HashMap<TxHash, TxBlock>) -> Result<(), SentPayableDaoError>;
fn replace_records(&self, new_txs: &BTreeSet<SentTx>) -> Result<(), SentPayableDaoError>;
fn update_statuses(
&self,
hash_map: &HashMap<TxHash, TxStatus>,
) -> Result<(), SentPayableDaoError>;
//TODO potentially atomically
fn delete_records(&self, hashes: &BTreeSet<TxHash>) -> Result<(), SentPayableDaoError>;
}
#[derive(Debug)]
pub struct SentPayableDaoReal<'a> {
conn: Box<dyn ConnectionWrapper + 'a>,
}
impl<'a> SentPayableDaoReal<'a> {
pub fn new(conn: Box<dyn ConnectionWrapper + 'a>) -> Self {
Self { conn }
}
}
impl SentPayableDao for SentPayableDaoReal<'_> {
fn get_tx_identifiers(&self, hashes: &BTreeSet<TxHash>) -> TxIdentifiers {
let sql = format!(
"SELECT tx_hash, rowid FROM sent_payable WHERE tx_hash IN ({})",
join_with_commas(hashes, |hash| format!("'{:?}'", hash))
);
let mut stmt = self
.conn
.prepare(&sql)
.expect("Failed to prepare SQL statement");
stmt.query_map([], |row| {
let tx_hash_str: String = row.get(0).expectv("tx_hash");
let tx_hash = H256::from_str(&tx_hash_str[2..]).expect("Failed to parse H256");
let row_id: u64 = row.get(1).expectv("rowid");
Ok((tx_hash, row_id))
})
.expect("Failed to execute query")
.filter_map(Result::ok)
.collect()
}
fn insert_new_records(&self, txs: &BTreeSet<SentTx>) -> Result<(), SentPayableDaoError> {
if txs.is_empty() {
return Err(SentPayableDaoError::EmptyInput);
}
let unique_hashes: BTreeSet<TxHash> = txs.iter().map(|tx| tx.hash).collect();
if unique_hashes.len() != txs.len() {
return Err(SentPayableDaoError::InvalidInput(format!(
"Duplicate hashes found in the input. Input Transactions: {:?}",
txs
)));
}
let duplicates = self.get_tx_identifiers(&unique_hashes);
if !duplicates.is_empty() {
return Err(SentPayableDaoError::InvalidInput(format!(
"Duplicates detected in the database: {:?}",
duplicates,
)));
}
let sql = format!(
"INSERT INTO sent_payable (\
tx_hash, \
receiver_address, \
amount_high_b, \
amount_low_b, \
timestamp, \
gas_price_wei_high_b, \
gas_price_wei_low_b, \
nonce, \
status \
) VALUES {}",
join_with_commas(txs, |tx| sql_values_of_sent_tx(tx))
);
match self.conn.prepare(&sql).expect("Internal error").execute([]) {
Ok(inserted_rows) => {
if inserted_rows == txs.len() {
Ok(())
} else {
Err(SentPayableDaoError::PartialExecution(format!(
"Only {} out of {} records inserted",
inserted_rows,
txs.len()
)))
}
}
Err(e) => Err(SentPayableDaoError::SqlExecutionFailed(e.to_string())),
}
}
fn retrieve_txs(&self, condition_opt: Option<RetrieveCondition>) -> BTreeSet<SentTx> {
let raw_sql = "SELECT tx_hash, receiver_address, amount_high_b, amount_low_b, \
timestamp, gas_price_wei_high_b, gas_price_wei_low_b, nonce, status FROM sent_payable"
.to_string();
let sql = match condition_opt {
None => raw_sql,
Some(condition) => format!("{} {}", raw_sql, condition),
};
let mut stmt = self
.conn
.prepare(&sql)
.expect("Failed to prepare SQL statement");
stmt.query_map([], |row| {
let tx_hash_str: String = row.get(0).expectv("tx_hash");
let hash = H256::from_str(&tx_hash_str[2..]).expect("Failed to parse H256");
let receiver_address_str: String = row.get(1).expectv("receivable_address");
let receiver_address =
Address::from_str(&receiver_address_str[2..]).expect("Failed to parse H160");
let amount_high_b = row.get(2).expectv("amount_high_b");
let amount_low_b = row.get(3).expectv("amount_low_b");
let amount_minor = BigIntDivider::reconstitute(amount_high_b, amount_low_b) as u128;
let timestamp = row.get(4).expectv("timestamp");
let gas_price_wei_high_b = row.get(5).expectv("gas_price_wei_high_b");
let gas_price_wei_low_b = row.get(6).expectv("gas_price_wei_low_b");
let gas_price_minor =
BigIntDivider::reconstitute(gas_price_wei_high_b, gas_price_wei_low_b) as u128;
let nonce = row.get(7).expectv("nonce");
let status_str: String = row.get(8).expectv("status");
let status = TxStatus::from_str(&status_str).expect("Failed to parse TxStatus");
Ok(SentTx {
hash,
receiver_address,
amount_minor,
timestamp,
gas_price_minor,
nonce,
status,
})
})
.expect("Failed to execute query")
.filter_map(Result::ok)
.collect()
}
fn confirm_txs(&self, hash_map: &HashMap<TxHash, TxBlock>) -> Result<(), SentPayableDaoError> {
if hash_map.is_empty() {
return Err(SentPayableDaoError::EmptyInput);
}
for (hash, tx_block) in hash_map {
let sql = format!(
"UPDATE sent_payable SET status = '{}' WHERE tx_hash = '{:?}'",
TxStatus::from(*tx_block),
hash
);
match self.conn.prepare(&sql).expect("Internal error").execute([]) {
Ok(updated_rows) => {
if updated_rows == 1 {
continue;
} else {
return Err(SentPayableDaoError::PartialExecution(format!(
"Failed to update status for hash {:?}",
hash
)));
}
}
Err(e) => {
return Err(SentPayableDaoError::SqlExecutionFailed(e.to_string()));
}
}
}
Ok(())
}
fn replace_records(&self, new_txs: &BTreeSet<SentTx>) -> Result<(), SentPayableDaoError> {
if new_txs.is_empty() {
return Err(SentPayableDaoError::EmptyInput);
}
let build_case = |value_fn: fn(&SentTx) -> String| {
join_with_separator(
new_txs,
|tx| format!("WHEN nonce = {} THEN {}", tx.nonce, value_fn(tx)),
" ",
)
};
let tx_hash_cases = build_case(|tx| format!("'{:?}'", tx.hash));
let receiver_address_cases = build_case(|tx| format!("'{:?}'", tx.receiver_address));
let amount_high_b_cases = build_case(|tx| {
let amount_checked = checked_conversion::<u128, i128>(tx.amount_minor);
let (high, _) = BigIntDivider::deconstruct(amount_checked);
high.to_string()
});
let amount_low_b_cases = build_case(|tx| {
let amount_checked = checked_conversion::<u128, i128>(tx.amount_minor);
let (_, low) = BigIntDivider::deconstruct(amount_checked);
low.to_string()
});
let timestamp_cases = build_case(|tx| tx.timestamp.to_string());
let gas_price_wei_high_b_cases = build_case(|tx| {
let gas_price_wei_checked = checked_conversion::<u128, i128>(tx.gas_price_minor);
let (high, _) = BigIntDivider::deconstruct(gas_price_wei_checked);
high.to_string()
});
let gas_price_wei_low_b_cases = build_case(|tx| {
let gas_price_wei_checked = checked_conversion::<u128, i128>(tx.gas_price_minor);
let (_, low) = BigIntDivider::deconstruct(gas_price_wei_checked);
low.to_string()
});
let status_cases = build_case(|tx| format!("'{}'", tx.status));
let nonces = join_with_commas(new_txs, |tx| tx.nonce.to_string());
let sql = format!(
"UPDATE sent_payable \
SET \
tx_hash = CASE \
{tx_hash_cases} \
END, \
receiver_address = CASE \
{receiver_address_cases} \
END, \
amount_high_b = CASE \
{amount_high_b_cases} \
END, \
amount_low_b = CASE \
{amount_low_b_cases} \
END, \
timestamp = CASE \
{timestamp_cases} \
END, \
gas_price_wei_high_b = CASE \
{gas_price_wei_high_b_cases} \
END, \
gas_price_wei_low_b = CASE \
{gas_price_wei_low_b_cases} \
END, \
status = CASE \
{status_cases} \
END \
WHERE nonce IN ({nonces})",
);
match self.conn.prepare(&sql).expect("Internal error").execute([]) {
Ok(updated_rows) => match updated_rows {
0 => Err(SentPayableDaoError::NoChange),
count if count == new_txs.len() => Ok(()),
_ => Err(SentPayableDaoError::PartialExecution(format!(
"Only {} out of {} records updated",
updated_rows,
new_txs.len()
))),
},
Err(e) => Err(SentPayableDaoError::SqlExecutionFailed(e.to_string())),
}
}
fn update_statuses(
&self,
status_updates: &HashMap<TxHash, TxStatus>,
) -> Result<(), SentPayableDaoError> {
if status_updates.is_empty() {
return Err(SentPayableDaoError::EmptyInput);
}
let case_statements = status_updates
.iter()
.map(|(hash, status)| format!("WHEN tx_hash = '{:?}' THEN '{}'", hash, status))
.join(" ");
let tx_hashes = join_with_commas(&status_updates.keys().collect_vec(), |hash| {
format!("'{:?}'", hash)
});
let sql = format!(
"UPDATE sent_payable \
SET \
status = CASE \
{case_statements} \
END \
WHERE tx_hash IN ({tx_hashes})"
);
match self.conn.prepare(&sql).expect("Internal error").execute([]) {
Ok(rows_changed) => {
if rows_changed == status_updates.len() {
Ok(())
} else {
Err(SentPayableDaoError::PartialExecution(format!(
"Only {} of {} records had their status updated.",
rows_changed,
status_updates.len(),
)))
}
}
Err(e) => Err(SentPayableDaoError::SqlExecutionFailed(e.to_string())),
}
}
fn delete_records(&self, hashes: &BTreeSet<TxHash>) -> Result<(), SentPayableDaoError> {
if hashes.is_empty() {
return Err(SentPayableDaoError::EmptyInput);
}
let sql = format!(
"DELETE FROM sent_payable WHERE tx_hash IN ({})",
join_with_commas(hashes, |hash| { format!("'{:?}'", hash) })
);
match self.conn.prepare(&sql).expect("Internal error").execute([]) {
Ok(deleted_rows) => {
if deleted_rows == hashes.len() {
Ok(())
} else if deleted_rows == 0 {
Err(SentPayableDaoError::NoChange)
} else {
Err(SentPayableDaoError::PartialExecution(format!(
"Only {} of the {} hashes has been deleted.",
deleted_rows,
hashes.len(),
)))
}
}
Err(e) => Err(SentPayableDaoError::SqlExecutionFailed(e.to_string())),
}
}
}
pub trait SentPayableDaoFactory {
fn make(&self) -> Box<dyn SentPayableDao>;
}
impl SentPayableDaoFactory for DaoFactoryReal {
fn make(&self) -> Box<dyn SentPayableDao> {
Box::new(SentPayableDaoReal::new(self.make_connection()))
}
}
#[cfg(test)]
mod tests {
use crate::accountant::db_access_objects::sent_payable_dao::RetrieveCondition::{
ByHash, ByNonce, IsPending,
};
use crate::accountant::db_access_objects::sent_payable_dao::SentPayableDaoError::{
EmptyInput, PartialExecution,
};
use crate::accountant::db_access_objects::sent_payable_dao::{
Detection, RetrieveCondition, SentPayableDao, SentPayableDaoError, SentPayableDaoReal,
SentTx, TxStatus,
};
use crate::accountant::db_access_objects::test_utils::{
make_read_only_db_connection, make_sent_tx, TxBuilder,
};
use crate::accountant::db_access_objects::Transaction;
use crate::blockchain::blockchain_interface::data_structures::TxBlock;
use crate::blockchain::errors::internal_errors::InternalErrorKind;
use crate::blockchain::errors::rpc_errors::{AppRpcErrorKind, LocalErrorKind, RemoteErrorKind};
use crate::blockchain::errors::validation_status::{PreviousAttempts, ValidationStatus};
use crate::blockchain::errors::BlockchainErrorKind;
use crate::blockchain::test_utils::{make_address, make_block_hash, make_tx_hash};
use crate::database::db_initializer::{
DbInitializationConfig, DbInitializer, DbInitializerReal,
};
use crate::database::test_utils::ConnectionWrapperMock;
use ethereum_types::{H256, U64};
use masq_lib::simple_clock::SimpleClockReal;
use masq_lib::test_utils::simple_clock::SimpleClockMock;
use masq_lib::test_utils::utils::ensure_node_home_directory_exists;
use rusqlite::Connection;
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap};
use std::ops::{Add, Sub};
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[test]
fn insert_new_records_works() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "insert_new_records_works");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let tx1 = TxBuilder::default().hash(make_tx_hash(1)).build();
let tx2 = TxBuilder::default()
.hash(make_tx_hash(2))
.status(TxStatus::Pending(ValidationStatus::Reattempting(
PreviousAttempts::new(
BlockchainErrorKind::AppRpc(AppRpcErrorKind::Remote(
RemoteErrorKind::Unreachable,
)),
&SimpleClockReal::default(),
)
.add_attempt(
BlockchainErrorKind::AppRpc(AppRpcErrorKind::Remote(
RemoteErrorKind::Unreachable,
)),
&SimpleClockReal::default(),
),
)))
.build();
let subject = SentPayableDaoReal::new(wrapped_conn);
let txs = BTreeSet::from([tx1, tx2]);
let result = subject.insert_new_records(&txs);
let retrieved_txs = subject.retrieve_txs(None);
assert_eq!(result, Ok(()));
assert_eq!(retrieved_txs, txs);
}
#[test]
fn insert_new_records_throws_err_for_empty_input() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"insert_new_records_throws_err_for_empty_input",
);
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let empty_input = BTreeSet::new();
let result = subject.insert_new_records(&empty_input);
assert_eq!(result, Err(SentPayableDaoError::EmptyInput));
}
#[test]
fn insert_new_records_throws_error_when_two_txs_with_same_hash_are_present_in_the_input() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"insert_new_records_throws_error_when_two_txs_with_same_hash_are_present_in_the_input",
);
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let hash = make_tx_hash(1234);
let tx1 = TxBuilder::default()
.hash(hash)
.timestamp(1749204017)
.status(TxStatus::Pending(ValidationStatus::Waiting))
.build();
let tx2 = TxBuilder::default()
.hash(hash)
.timestamp(1749204020)
.status(TxStatus::Confirmed {
block_hash: format!("{:?}", make_block_hash(456)),
block_number: 7890123,
detection: Detection::Reclaim,
})
.build();
let subject = SentPayableDaoReal::new(wrapped_conn);
let result = subject.insert_new_records(&BTreeSet::from([tx1, tx2]));
assert_eq!(
result,
Err(SentPayableDaoError::InvalidInput(
"Duplicate hashes found in the input. Input Transactions: \
{\
SentTx { hash: 0x00000000000000000000000000000000000000000000000000000000000004d2, \
receiver_address: 0x0000000000000000000000000000000000000000, \
amount_minor: 0, timestamp: 1749204017, gas_price_minor: 0, \
nonce: 0, status: Pending(Waiting) }, \
SentTx { \
hash: 0x00000000000000000000000000000000000000000000000000000000000004d2, \
receiver_address: 0x0000000000000000000000000000000000000000, \
amount_minor: 0, timestamp: 1749204020, gas_price_minor: 0, \
nonce: 0, status: Confirmed { block_hash: \
\"0x000000000000000000000000000000000000000000000000000000003b9acbc8\", \
block_number: 7890123, detection: Reclaim } }\
}"
.to_string()
))
);
}
#[test]
fn insert_new_records_throws_error_when_input_tx_hash_is_already_present_in_the_db() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"insert_new_records_throws_error_when_input_tx_hash_is_already_present_in_the_db",
);
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let hash = make_tx_hash(1234);
let tx1 = TxBuilder::default().hash(hash).build();
let tx2 = TxBuilder::default().hash(hash).build();
let subject = SentPayableDaoReal::new(wrapped_conn);
let initial_insertion_result = subject.insert_new_records(&BTreeSet::from([tx1]));
let result = subject.insert_new_records(&BTreeSet::from([tx2]));
assert_eq!(initial_insertion_result, Ok(()));
assert_eq!(
result,
Err(SentPayableDaoError::InvalidInput(
"Duplicates detected in the database: \
{0x00000000000000000000000000000000000000000000000000000000000004d2: 1}"
.to_string()
))
);
}
#[test]
fn insert_new_records_returns_err_if_partially_executed() {
let setup_conn = Connection::open_in_memory().unwrap();
setup_conn
.execute("CREATE TABLE example (id integer)", [])
.unwrap();
let get_tx_identifiers_stmt = setup_conn.prepare("SELECT id FROM example").unwrap();
let faulty_insert_stmt = { setup_conn.prepare("SELECT id FROM example").unwrap() };
let wrapped_conn = ConnectionWrapperMock::default()
.prepare_result(Ok(get_tx_identifiers_stmt))
.prepare_result(Ok(faulty_insert_stmt));
let tx = TxBuilder::default().build();
let subject = SentPayableDaoReal::new(Box::new(wrapped_conn));
let result = subject.insert_new_records(&BTreeSet::from([tx]));
assert_eq!(
result,
Err(SentPayableDaoError::PartialExecution(
"Only 0 out of 1 records inserted".to_string()
))
);
}
#[test]
fn insert_new_records_can_throw_error() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"insert_new_records_can_throw_error",
);
let tx = TxBuilder::default().build();
let wrapped_conn = make_read_only_db_connection(home_dir);
let subject = SentPayableDaoReal::new(Box::new(wrapped_conn));
let result = subject.insert_new_records(&BTreeSet::from([tx]));
assert_eq!(
result,
Err(SentPayableDaoError::SqlExecutionFailed(
"attempt to write a readonly database".to_string()
))
)
}
#[test]
fn get_tx_identifiers_works() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "get_tx_identifiers_works");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let present_hash = make_tx_hash(1);
let absent_hash = make_tx_hash(2);
let another_present_hash = make_tx_hash(3);
let hashset = BTreeSet::from([present_hash, absent_hash, another_present_hash]);
let present_tx = TxBuilder::default().hash(present_hash).build();
let another_present_tx = TxBuilder::default().hash(another_present_hash).build();
subject
.insert_new_records(&BTreeSet::from([present_tx, another_present_tx]))
.unwrap();
let result = subject.get_tx_identifiers(&hashset);
assert_eq!(result.get(&present_hash), Some(&1u64));
assert_eq!(result.get(&absent_hash), None);
assert_eq!(result.get(&another_present_hash), Some(&2u64));
}
#[test]
fn retrieve_condition_display_works() {
assert_eq!(IsPending.to_string(), "WHERE status LIKE '%\"Pending\":%'");
// 0x0000000000000000000000000000000000000000000000000000000123456789
assert_eq!(
ByHash(BTreeSet::from([
H256::from_low_u64_be(0x123456789),
H256::from_low_u64_be(0x987654321),
]))
.to_string(),
"WHERE tx_hash IN (\
'0x0000000000000000000000000000000000000000000000000000000123456789', \
'0x0000000000000000000000000000000000000000000000000000000987654321'\
)"
);
assert_eq!(ByNonce(vec![45, 47]).to_string(), "WHERE nonce IN (45, 47)")
}
#[test]
fn can_retrieve_all_txs() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "can_retrieve_all_txs");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let tx1 = TxBuilder::default().hash(make_tx_hash(1)).build();
let tx2 = TxBuilder::default().hash(make_tx_hash(2)).build();
let tx3 = TxBuilder::default().hash(make_tx_hash(3)).build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2.clone()]))
.unwrap();
subject
.insert_new_records(&BTreeSet::from([tx3.clone()]))
.unwrap();
let result = subject.retrieve_txs(None);
assert_eq!(result, BTreeSet::from([tx1, tx2, tx3]));
}
#[test]
fn can_retrieve_pending_txs() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "can_retrieve_pending_txs");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let tx1 = TxBuilder::default()
.hash(make_tx_hash(1))
.status(TxStatus::Pending(ValidationStatus::Waiting))
.build();
let tx2 = TxBuilder::default()
.hash(make_tx_hash(2))
.status(TxStatus::Pending(ValidationStatus::Reattempting(
PreviousAttempts::new(
BlockchainErrorKind::AppRpc(AppRpcErrorKind::Remote(
RemoteErrorKind::Unreachable,
)),
&SimpleClockReal::default(),
),
)))
.build();
let tx3 = TxBuilder::default()
.hash(make_tx_hash(3))
.status(TxStatus::Confirmed {
block_hash: format!("{:?}", make_block_hash(456)),
block_number: 456789,
detection: Detection::Normal,
})
.build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2.clone(), tx3]))
.unwrap();
let result = subject.retrieve_txs(Some(RetrieveCondition::IsPending));
assert_eq!(result, BTreeSet::from([tx1, tx2]));
}
#[test]
fn tx_can_be_retrieved_by_hash() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "tx_can_be_retrieved_by_hash");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let tx1 = TxBuilder::default().hash(make_tx_hash(1)).build();
let tx2 = TxBuilder::default().hash(make_tx_hash(2)).build();
let tx3 = TxBuilder::default().hash(make_tx_hash(3)).build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2, tx3.clone()]))
.unwrap();
let result = subject.retrieve_txs(Some(ByHash(BTreeSet::from([tx1.hash, tx3.hash]))));
assert_eq!(result, BTreeSet::from([tx1, tx3]));
}
#[test]
fn retrieve_txs_by_hash_returns_only_existing_transactions() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"retrieve_txs_by_hash_returns_only_existing_transactions",
);
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let tx1 = TxBuilder::default().hash(make_tx_hash(1)).nonce(1).build();
let tx2 = TxBuilder::default().hash(make_tx_hash(2)).nonce(2).build();
let tx3 = TxBuilder::default().hash(make_tx_hash(3)).nonce(3).build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2.clone(), tx3.clone()]))
.unwrap();
let mut query_hashes = BTreeSet::new();
query_hashes.insert(make_tx_hash(1)); // Exists
query_hashes.insert(make_tx_hash(2)); // Exists
query_hashes.insert(make_tx_hash(4)); // Does not exist
query_hashes.insert(make_tx_hash(5)); // Does not exist
let result = subject.retrieve_txs(Some(RetrieveCondition::ByHash(query_hashes)));
assert_eq!(result.len(), 2, "Should only return 2 transactions");
assert!(result.contains(&tx1), "Should contain tx1");
assert!(result.contains(&tx2), "Should contain tx2");
assert!(!result.contains(&tx3), "Should not contain tx3");
assert!(
result.iter().all(|tx| tx.hash != make_tx_hash(4)),
"Should not contain hash 4"
);
assert!(
result.iter().all(|tx| tx.hash != make_tx_hash(5)),
"Should not contain hash 5"
);
}
#[test]
fn tx_can_be_retrieved_by_nonce() {
let home_dir =
ensure_node_home_directory_exists("sent_payable_dao", "tx_can_be_retrieved_by_nonce");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let tx1 = TxBuilder::default()
.hash(make_tx_hash(123))
.nonce(33)
.build();
let tx2 = TxBuilder::default()
.hash(make_tx_hash(456))
.nonce(34)
.build();
let tx3 = TxBuilder::default()
.hash(make_tx_hash(789))
.nonce(35)
.build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2, tx3.clone()]))
.unwrap();
let result = subject.retrieve_txs(Some(ByNonce(vec![33, 35])));
assert_eq!(result, BTreeSet::from([tx1, tx3]));
}
#[test]
fn confirm_tx_works() {
let home_dir = ensure_node_home_directory_exists("sent_payable_dao", "confirm_tx_works");
let wrapped_conn = DbInitializerReal::default()
.initialize(&home_dir, DbInitializationConfig::test_default())
.unwrap();
let subject = SentPayableDaoReal::new(wrapped_conn);
let hash1 = make_tx_hash(1);
let hash2 = make_tx_hash(2);
let tx1 = TxBuilder::default().hash(hash1).build();
let tx2 = TxBuilder::default().hash(hash2).build();
subject
.insert_new_records(&BTreeSet::from([tx1.clone(), tx2.clone()]))
.unwrap();
let updated_pre_assert_txs =
subject.retrieve_txs(Some(ByHash(BTreeSet::from([hash1, hash2]))));
let pre_assert_status_tx1 = updated_pre_assert_txs.get(&tx1).unwrap().status.clone();
let pre_assert_status_tx2 = updated_pre_assert_txs.get(&tx2).unwrap().status.clone();
let confirmed_tx_block_1 = TxBlock {
block_hash: make_block_hash(3),
block_number: U64::from(1),
};
let confirmed_tx_block_2 = TxBlock {
block_hash: make_block_hash(4),
block_number: U64::from(2),
};
let hash_map = HashMap::from([
(tx1.hash, confirmed_tx_block_1.clone()),
(tx2.hash, confirmed_tx_block_2.clone()),
]);
let result = subject.confirm_txs(&hash_map);
let updated_txs = subject.retrieve_txs(Some(ByHash(BTreeSet::from([tx1.hash, tx2.hash]))));
let updated_tx1 = updated_txs.iter().find(|tx| tx.hash == hash1).unwrap();
let updated_tx2 = updated_txs.iter().find(|tx| tx.hash == hash2).unwrap();
assert_eq!(result, Ok(()));
assert_eq!(
pre_assert_status_tx1,
TxStatus::Pending(ValidationStatus::Waiting)
);
assert_eq!(
updated_tx1.status,
TxStatus::Confirmed {
block_hash: format!("{:?}", confirmed_tx_block_1.block_hash),
block_number: confirmed_tx_block_1.block_number.as_u64(),
detection: Detection::Normal
}
);
assert_eq!(
pre_assert_status_tx2,
TxStatus::Pending(ValidationStatus::Waiting)
);
assert_eq!(
updated_tx2.status,
TxStatus::Confirmed {
block_hash: format!("{:?}", confirmed_tx_block_2.block_hash),
block_number: confirmed_tx_block_2.block_number.as_u64(),
detection: Detection::Normal
}
);
}
#[test]
fn confirm_tx_returns_error_when_input_is_empty() {
let home_dir = ensure_node_home_directory_exists(
"sent_payable_dao",
"confirm_tx_returns_error_when_input_is_empty",
);