forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
taker_swap.rs
2970 lines (2700 loc) · 174 KB
/
taker_swap.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 super::check_balance::{check_my_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult,
TakerFeeAdditionalInfo};
use super::pubkey_banning::ban_pubkey_on_failed_swap;
use super::swap_lock::{SwapLock, SwapLockOps};
use super::swap_watcher::{watcher_topic, SwapWatcherMsg};
use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult};
use super::{broadcast_my_swap_status, broadcast_swap_message, broadcast_swap_message_every,
check_other_coin_balance_for_swap, dex_fee_amount_from_taker_coin, dex_fee_rate, dex_fee_threshold,
get_locked_amount, recv_swap_msg, swap_topic, wait_for_maker_payment_conf_until, AtomicSwap, LockedAmount,
MySwapInfo, NegotiationDataMsg, NegotiationDataV2, NegotiationDataV3, RecoveredSwap, RecoveredSwapAction,
SavedSwap, SavedSwapIo, SavedTradeFee, SwapConfirmationsSettings, SwapError, SwapMsg, SwapTxDataMsg,
SwapsContext, TransactionIdentifier, WAIT_CONFIRM_INTERVAL};
use crate::mm2::lp_network::subscribe_to_topic;
use crate::mm2::lp_ordermatch::{MatchBy, OrderConfirmationsSettings, TakerAction, TakerOrderBuilder};
use crate::mm2::lp_price::fetch_swap_coins_price;
use crate::mm2::lp_swap::{broadcast_p2p_tx_msg, tx_helper_topic, wait_for_maker_payment_conf_duration,
TakerSwapWatcherData};
use coins::{lp_coinfind, CanRefundHtlc, CheckIfMyPaymentSentArgs, FeeApproxStage, FoundSwapTxSpend, MmCoinEnum,
PaymentInstructions, PaymentInstructionsErr, SearchForSwapTxSpendInput, SendSpendPaymentArgs,
SendTakerPaymentArgs, SendTakerRefundsPaymentArgs, SendTakerSpendsMakerPaymentArgs, TradeFee,
TradePreimageValue, ValidatePaymentInput};
use common::executor::Timer;
use common::log::{debug, error, info, warn};
use common::{bits256, now_ms, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::{privkey::SerializableSecp256k1Keypair, CryptoCtx};
use futures::{compat::Future01CompatExt, future::try_join, select, FutureExt};
use http::Response;
use keys::KeyPair;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
use mm2_number::{BigDecimal, MmNumber};
use parking_lot::Mutex as PaMutex;
use primitives::hash::H264;
use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json, H264 as H264Json};
use serde_json::{self as json, Value as Json};
use std::convert::TryFrom;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use uuid::Uuid;
const TAKER_PAYMENT_SPEND_SEARCH_INTERVAL: f64 = 10.;
pub const TAKER_SUCCESS_EVENTS: [&str; 11] = [
"Started",
"Negotiated",
"TakerFeeSent",
"TakerPaymentInstructionsReceived",
"MakerPaymentReceived",
"MakerPaymentWaitConfirmStarted",
"MakerPaymentValidatedAndConfirmed",
"TakerPaymentSent",
"TakerPaymentSpent",
"MakerPaymentSpent",
"Finished",
];
pub const TAKER_USING_WATCHERS_SUCCESS_EVENTS: [&str; 12] = [
"Started",
"Negotiated",
"TakerFeeSent",
"TakerPaymentInstructionsReceived",
"MakerPaymentReceived",
"MakerPaymentWaitConfirmStarted",
"MakerPaymentValidatedAndConfirmed",
"TakerPaymentSent",
"WatcherMessageSent",
"TakerPaymentSpent",
"MakerPaymentSpent",
"Finished",
];
pub const TAKER_ERROR_EVENTS: [&str; 15] = [
"StartFailed",
"NegotiateFailed",
"TakerFeeSendFailed",
"MakerPaymentValidateFailed",
"MakerPaymentWaitConfirmFailed",
"TakerPaymentTransactionFailed",
"TakerPaymentWaitConfirmFailed",
"TakerPaymentDataSendFailed",
"TakerPaymentWaitForSpendFailed",
"MakerPaymentSpendFailed",
"TakerPaymentWaitRefundStarted",
"TakerPaymentRefundStarted",
"TakerPaymentRefunded",
"TakerPaymentRefundFailed",
"TakerPaymentRefundFinished",
];
pub const WATCHER_MESSAGE_SENT_LOG: &str = "Watcher message sent...";
#[cfg(not(target_arch = "wasm32"))]
pub fn stats_taker_swap_dir(ctx: &MmArc) -> PathBuf { ctx.dbdir().join("SWAPS").join("STATS").join("TAKER") }
#[cfg(not(target_arch = "wasm32"))]
pub fn stats_taker_swap_file_path(ctx: &MmArc, uuid: &Uuid) -> PathBuf {
stats_taker_swap_dir(ctx).join(format!("{}.json", uuid))
}
async fn save_my_taker_swap_event(ctx: &MmArc, swap: &TakerSwap, event: TakerSavedEvent) -> Result<(), String> {
let swap = match SavedSwap::load_my_swap_from_db(ctx, swap.uuid).await {
Ok(Some(swap)) => swap,
Ok(None) => SavedSwap::Taker(TakerSavedSwap {
uuid: swap.uuid,
my_order_uuid: swap.my_order_uuid,
maker_amount: Some(swap.maker_amount.to_decimal()),
maker_coin: Some(swap.maker_coin.ticker().to_owned()),
maker_coin_usd_price: None,
taker_amount: Some(swap.taker_amount.to_decimal()),
taker_coin: Some(swap.taker_coin.ticker().to_owned()),
taker_coin_usd_price: None,
gui: ctx.gui().map(|g| g.to_owned()),
mm_version: Some(ctx.mm_version.to_owned()),
events: vec![],
success_events: match ctx.use_watchers() {
true => TAKER_USING_WATCHERS_SUCCESS_EVENTS
.iter()
.map(|event| event.to_string())
.collect(),
false => TAKER_SUCCESS_EVENTS.iter().map(|event| event.to_string()).collect(),
},
error_events: TAKER_ERROR_EVENTS.iter().map(|event| event.to_string()).collect(),
}),
Err(e) => return ERR!("{}", e),
};
if let SavedSwap::Taker(mut taker_swap) = swap {
taker_swap.events.push(event);
if taker_swap.is_success().unwrap_or(false) {
taker_swap.fetch_and_set_usd_prices().await;
}
let new_swap = SavedSwap::Taker(taker_swap);
try_s!(new_swap.save_to_db(ctx).await);
Ok(())
} else {
ERR!("Expected SavedSwap::Taker, got {:?}", swap)
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct TakerSavedEvent {
pub timestamp: u64,
pub event: TakerSwapEvent,
}
impl TakerSavedEvent {
/// get the next swap command that must be executed after swap restore
fn get_command(&self) -> Option<TakerSwapCommand> {
match self.event {
TakerSwapEvent::Started(_) => Some(TakerSwapCommand::Negotiate),
TakerSwapEvent::StartFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::Negotiated(_) => Some(TakerSwapCommand::SendTakerFee),
TakerSwapEvent::NegotiateFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::TakerFeeSent(_) => Some(TakerSwapCommand::WaitForMakerPayment),
TakerSwapEvent::TakerFeeSendFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::TakerPaymentInstructionsReceived(_) => Some(TakerSwapCommand::ValidateMakerPayment),
TakerSwapEvent::MakerPaymentReceived(_) => Some(TakerSwapCommand::ValidateMakerPayment),
TakerSwapEvent::MakerPaymentWaitConfirmStarted => Some(TakerSwapCommand::ValidateMakerPayment),
TakerSwapEvent::MakerPaymentValidatedAndConfirmed => Some(TakerSwapCommand::SendTakerPayment),
TakerSwapEvent::MakerPaymentValidateFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::MakerPaymentWaitConfirmFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::TakerPaymentSent(_) => Some(TakerSwapCommand::WaitForTakerPaymentSpend),
TakerSwapEvent::WatcherMessageSent(_, _) => Some(TakerSwapCommand::WaitForTakerPaymentSpend),
TakerSwapEvent::TakerPaymentTransactionFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::TakerPaymentDataSendFailed(_) => Some(TakerSwapCommand::PrepareForTakerPaymentRefund),
TakerSwapEvent::TakerPaymentSpent(_) => Some(TakerSwapCommand::SpendMakerPayment),
TakerSwapEvent::TakerPaymentWaitForSpendFailed(_) => Some(TakerSwapCommand::PrepareForTakerPaymentRefund),
TakerSwapEvent::TakerPaymentWaitConfirmFailed(_) => Some(TakerSwapCommand::PrepareForTakerPaymentRefund),
TakerSwapEvent::MakerPaymentSpent(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::MakerPaymentSpendFailed(_) => Some(TakerSwapCommand::PrepareForTakerPaymentRefund),
TakerSwapEvent::TakerPaymentWaitRefundStarted { .. } => {
Some(TakerSwapCommand::PrepareForTakerPaymentRefund)
},
TakerSwapEvent::TakerPaymentRefundStarted => Some(TakerSwapCommand::RefundTakerPayment),
TakerSwapEvent::TakerPaymentRefunded(_) => Some(TakerSwapCommand::FinalizeTakerPaymentRefund),
TakerSwapEvent::TakerPaymentRefundFailed(_) => Some(TakerSwapCommand::Finish),
TakerSwapEvent::TakerPaymentRefundFinished => Some(TakerSwapCommand::Finish),
TakerSwapEvent::Finished => None,
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct TakerSavedSwap {
pub uuid: Uuid,
pub my_order_uuid: Option<Uuid>,
pub events: Vec<TakerSavedEvent>,
pub maker_amount: Option<BigDecimal>,
pub maker_coin: Option<String>,
pub maker_coin_usd_price: Option<BigDecimal>,
pub taker_amount: Option<BigDecimal>,
pub taker_coin: Option<String>,
pub taker_coin_usd_price: Option<BigDecimal>,
pub gui: Option<String>,
pub mm_version: Option<String>,
pub success_events: Vec<String>,
pub error_events: Vec<String>,
}
impl TakerSavedSwap {
pub fn maker_coin(&self) -> Result<String, String> {
match self.events.first() {
Some(event) => match &event.event {
TakerSwapEvent::Started(data) => Ok(data.maker_coin.clone()),
_ => ERR!("First swap event must be Started"),
},
None => ERR!("Can't get maker coin, events are empty"),
}
}
pub fn taker_coin(&self) -> Result<String, String> {
match self.events.first() {
Some(event) => match &event.event {
TakerSwapEvent::Started(data) => Ok(data.taker_coin.clone()),
_ => ERR!("First swap event must be Started"),
},
None => ERR!("Can't get maker coin, events are empty"),
}
}
pub fn is_finished(&self) -> bool {
match self.events.last() {
Some(event) => event.event == TakerSwapEvent::Finished,
None => false,
}
}
pub fn get_my_info(&self) -> Option<MySwapInfo> {
match self.events.first() {
Some(event) => match &event.event {
TakerSwapEvent::Started(data) => Some(MySwapInfo {
my_coin: data.taker_coin.clone(),
other_coin: data.maker_coin.clone(),
my_amount: data.taker_amount.clone(),
other_amount: data.maker_amount.clone(),
started_at: data.started_at,
}),
_ => None,
},
None => None,
}
}
pub fn is_recoverable(&self) -> bool {
if !self.is_finished() {
return false;
};
for event in self.events.iter() {
match event.event {
TakerSwapEvent::StartFailed(_)
| TakerSwapEvent::NegotiateFailed(_)
| TakerSwapEvent::TakerFeeSendFailed(_)
| TakerSwapEvent::MakerPaymentValidateFailed(_)
| TakerSwapEvent::TakerPaymentRefunded(_)
| TakerSwapEvent::MakerPaymentSpent(_)
| TakerSwapEvent::MakerPaymentWaitConfirmFailed(_) => {
return false;
},
_ => (),
}
}
true
}
pub fn swap_data(&self) -> Result<&TakerSwapData, String> {
match self.events.first() {
Some(event) => match &event.event {
TakerSwapEvent::Started(data) => Ok(data),
_ => ERR!("First swap event must be Started"),
},
None => ERR!("Can't get swap_data, events are empty"),
}
}
pub fn finished_at(&self) -> Result<u64, String> {
match self.events.last() {
Some(event) => match &event.event {
TakerSwapEvent::Finished => Ok(event.timestamp / 1000),
_ => ERR!("Last swap event must be Finished"),
},
None => ERR!("Can't get finished_at, events are empty"),
}
}
pub fn is_success(&self) -> Result<bool, String> {
if !self.is_finished() {
return ERR!("Can not determine is_success state for not finished swap");
}
for event in self.events.iter() {
if event.event.is_error() {
return Ok(false);
}
}
Ok(true)
}
pub async fn fetch_and_set_usd_prices(&mut self) {
if let Some(rates) = fetch_swap_coins_price(self.maker_coin.clone(), self.taker_coin.clone()).await {
self.maker_coin_usd_price = Some(rates.base);
self.taker_coin_usd_price = Some(rates.rel);
}
}
}
#[allow(clippy::large_enum_variant)]
pub enum RunTakerSwapInput {
StartNew(TakerSwap),
KickStart {
maker_coin: MmCoinEnum,
taker_coin: MmCoinEnum,
swap_uuid: Uuid,
},
}
impl RunTakerSwapInput {
fn uuid(&self) -> &Uuid {
match self {
RunTakerSwapInput::StartNew(swap) => &swap.uuid,
RunTakerSwapInput::KickStart { swap_uuid, .. } => swap_uuid,
}
}
}
/// Starts the taker swap and drives it to completion (until None next command received).
/// Panics in case of command or event apply fails, not sure yet how to handle such situations
/// because it's usually means that swap is in invalid state which is possible only if there's developer error
/// Every produced event is saved to local DB. Swap status is broadcast to P2P network after completion.
pub async fn run_taker_swap(swap: RunTakerSwapInput, ctx: MmArc) {
let uuid = swap.uuid().to_owned();
let mut attempts = 0;
let swap_lock = loop {
match SwapLock::lock(&ctx, uuid, 40.).await {
Ok(Some(l)) => break l,
Ok(None) => {
if attempts >= 1 {
warn!(
"Swap {} file lock is acquired by another process/thread, aborting",
uuid
);
return;
} else {
attempts += 1;
Timer::sleep(40.).await;
}
},
Err(e) => {
error!("Swap {} file lock error: {}", uuid, e);
return;
},
}
};
let (swap, mut command) = match swap {
RunTakerSwapInput::StartNew(swap) => (swap, TakerSwapCommand::Start),
RunTakerSwapInput::KickStart {
maker_coin,
taker_coin,
swap_uuid,
} => match TakerSwap::load_from_db_by_uuid(ctx, maker_coin, taker_coin, &swap_uuid).await {
Ok((swap, command)) => match command {
Some(c) => {
info!("Swap {} kick started.", uuid);
(swap, c)
},
None => {
warn!("Swap {} has been finished already, aborting.", uuid);
return;
},
},
Err(e) => {
error!("Error loading swap {}: {}", uuid, e);
return;
},
},
};
let mut touch_loop = Box::pin(
async move {
loop {
match swap_lock.touch().await {
Ok(_) => (),
Err(e) => warn!("Swap {} file lock error: {}", uuid, e),
};
Timer::sleep(30.).await;
}
}
.fuse(),
);
let ctx = swap.ctx.clone();
subscribe_to_topic(&ctx, swap_topic(&swap.uuid));
let mut status = ctx.log.status_handle();
let uuid = swap.uuid.to_string();
let to_broadcast = !(swap.maker_coin.is_privacy() || swap.taker_coin.is_privacy());
let running_swap = Arc::new(swap);
let weak_ref = Arc::downgrade(&running_swap);
let swap_ctx = SwapsContext::from_ctx(&ctx).unwrap();
swap_ctx.init_msg_store(running_swap.uuid, running_swap.maker);
swap_ctx.running_swaps.lock().unwrap().push(weak_ref);
let mut swap_fut = Box::pin(
async move {
let mut events;
loop {
let res = running_swap.handle_command(command).await.expect("!handle_command");
events = res.1;
for event in events {
let to_save = TakerSavedEvent {
timestamp: now_ms(),
event: event.clone(),
};
save_my_taker_swap_event(&ctx, &running_swap, to_save)
.await
.expect("!save_my_taker_swap_event");
if event.should_ban_maker() {
ban_pubkey_on_failed_swap(
&ctx,
running_swap.maker.bytes.into(),
&running_swap.uuid,
event.clone().into(),
)
}
#[cfg(target_arch = "wasm32")]
if event.is_error() {
error!("[swap uuid={uuid}] {event:?}");
}
status.status(&[&"swap", &("uuid", uuid.as_str())], &event.status_str());
running_swap.apply_event(event);
}
match res.0 {
Some(c) => {
command = c;
},
None => {
if to_broadcast {
if let Err(e) = broadcast_my_swap_status(&ctx, running_swap.uuid).await {
error!("!broadcast_my_swap_status({}): {}", uuid, e);
}
}
break;
},
}
}
}
.fuse(),
);
select! {
_swap = swap_fut => (), // swap finished normally
_touch = touch_loop => unreachable!("Touch loop can not stop!"),
};
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct TakerSwapData {
pub taker_coin: String,
pub maker_coin: String,
pub maker: H256Json,
pub my_persistent_pub: H264Json,
pub lock_duration: u64,
pub maker_amount: BigDecimal,
pub taker_amount: BigDecimal,
pub maker_payment_confirmations: u64,
pub maker_payment_requires_nota: Option<bool>,
pub taker_payment_confirmations: u64,
pub taker_payment_requires_nota: Option<bool>,
pub taker_payment_lock: u64,
/// Allows to recognize one SWAP from the other in the logs. #274.
pub uuid: Uuid,
pub started_at: u64,
pub maker_payment_wait: u64,
pub maker_coin_start_block: u64,
pub taker_coin_start_block: u64,
/// A transaction fee that should be paid to send a `TakerFee`.
/// Note this value is used to calculate locked amount only.
pub fee_to_send_taker_fee: Option<SavedTradeFee>,
/// A `TakerPayment` transaction fee.
/// Note this value is used to calculate locked amount only.
pub taker_payment_trade_fee: Option<SavedTradeFee>,
/// A transaction fee that should be paid to spend a `MakerPayment`.
/// Note this value is used to calculate locked amount only.
pub maker_payment_spend_trade_fee: Option<SavedTradeFee>,
#[serde(skip_serializing_if = "Option::is_none")]
pub maker_coin_swap_contract_address: Option<BytesJson>,
#[serde(skip_serializing_if = "Option::is_none")]
pub taker_coin_swap_contract_address: Option<BytesJson>,
/// Temporary pubkey used in HTLC redeem script when applicable for maker coin
pub maker_coin_htlc_pubkey: Option<H264Json>,
/// Temporary pubkey used in HTLC redeem script when applicable for taker coin
pub taker_coin_htlc_pubkey: Option<H264Json>,
/// Temporary privkey used to sign P2P messages when applicable
pub p2p_privkey: Option<SerializableSecp256k1Keypair>,
}
pub struct TakerSwapMut {
data: TakerSwapData,
other_maker_coin_htlc_pub: H264,
other_taker_coin_htlc_pub: H264,
taker_fee: Option<TransactionIdentifier>,
maker_payment: Option<TransactionIdentifier>,
taker_payment: Option<TransactionIdentifier>,
maker_payment_spend: Option<TransactionIdentifier>,
taker_payment_spend: Option<TransactionIdentifier>,
maker_payment_spend_preimage: Option<Vec<u8>>,
taker_payment_refund_preimage: Option<Vec<u8>>,
taker_payment_refund: Option<TransactionIdentifier>,
secret_hash: BytesJson,
secret: H256Json,
payment_instructions: Option<PaymentInstructions>,
}
#[cfg(test)]
#[derive(Eq, PartialEq)]
pub(super) enum FailAt {
TakerPayment,
MakerPaymentSpend,
TakerPaymentRefund,
}
#[cfg(test)]
impl From<String> for FailAt {
fn from(str: String) -> Self {
match str.as_str() {
"taker_payment" => FailAt::TakerPayment,
"maker_payment_spend" => FailAt::MakerPaymentSpend,
"taker_payment_refund" => FailAt::TakerPaymentRefund,
_ => panic!("Invalid TAKER_FAIL_AT value"),
}
}
}
pub struct TakerSwap {
ctx: MmArc,
maker_coin: MmCoinEnum,
taker_coin: MmCoinEnum,
maker_amount: MmNumber,
taker_amount: MmNumber,
my_persistent_pub: H264,
maker: bits256,
uuid: Uuid,
my_order_uuid: Option<Uuid>,
maker_payment_lock: AtomicU64,
maker_payment_confirmed: AtomicBool,
errors: PaMutex<Vec<SwapError>>,
finished_at: AtomicU64,
mutable: RwLock<TakerSwapMut>,
conf_settings: SwapConfirmationsSettings,
payment_locktime: u64,
p2p_privkey: Option<KeyPair>,
#[cfg(test)]
pub(super) fail_at: Option<FailAt>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct TakerPaymentSpentData {
pub transaction: TransactionIdentifier,
pub secret: H256Json,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct MakerNegotiationData {
pub maker_payment_locktime: u64,
pub maker_pubkey: H264Json,
pub secret_hash: BytesJson,
pub maker_coin_swap_contract_addr: Option<BytesJson>,
pub taker_coin_swap_contract_addr: Option<BytesJson>,
pub maker_coin_htlc_pubkey: Option<H264Json>,
pub taker_coin_htlc_pubkey: Option<H264Json>,
}
impl MakerNegotiationData {
fn other_maker_coin_htlc_pub(&self) -> H264 { self.maker_coin_htlc_pubkey.unwrap_or(self.maker_pubkey).into() }
fn other_taker_coin_htlc_pub(&self) -> H264 { self.taker_coin_htlc_pubkey.unwrap_or(self.maker_pubkey).into() }
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", content = "data")]
#[allow(clippy::large_enum_variant)]
pub enum TakerSwapEvent {
Started(TakerSwapData),
StartFailed(SwapError),
Negotiated(MakerNegotiationData),
NegotiateFailed(SwapError),
TakerFeeSent(TransactionIdentifier),
TakerFeeSendFailed(SwapError),
TakerPaymentInstructionsReceived(Option<PaymentInstructions>),
MakerPaymentReceived(TransactionIdentifier),
MakerPaymentWaitConfirmStarted,
MakerPaymentValidatedAndConfirmed,
MakerPaymentValidateFailed(SwapError),
MakerPaymentWaitConfirmFailed(SwapError),
TakerPaymentSent(TransactionIdentifier),
WatcherMessageSent(Option<Vec<u8>>, Option<Vec<u8>>),
TakerPaymentTransactionFailed(SwapError),
TakerPaymentDataSendFailed(SwapError),
TakerPaymentWaitConfirmFailed(SwapError),
TakerPaymentSpent(TakerPaymentSpentData),
TakerPaymentWaitForSpendFailed(SwapError),
MakerPaymentSpent(TransactionIdentifier),
MakerPaymentSpendFailed(SwapError),
TakerPaymentWaitRefundStarted { wait_until: u64 },
TakerPaymentRefundStarted,
TakerPaymentRefunded(Option<TransactionIdentifier>),
TakerPaymentRefundFailed(SwapError),
TakerPaymentRefundFinished,
Finished,
}
impl TakerSwapEvent {
pub fn status_str(&self) -> String {
match self {
TakerSwapEvent::Started(_) => "Started...".to_owned(),
TakerSwapEvent::StartFailed(_) => "Start failed...".to_owned(),
TakerSwapEvent::Negotiated(_) => "Negotiated...".to_owned(),
TakerSwapEvent::NegotiateFailed(_) => "Negotiate failed...".to_owned(),
TakerSwapEvent::TakerFeeSent(_) => "Taker fee sent...".to_owned(),
TakerSwapEvent::TakerFeeSendFailed(_) => "Taker fee send failed...".to_owned(),
TakerSwapEvent::TakerPaymentInstructionsReceived(_) => "Taker payment instructions received...".to_owned(),
TakerSwapEvent::MakerPaymentReceived(_) => "Maker payment received...".to_owned(),
TakerSwapEvent::MakerPaymentWaitConfirmStarted => "Maker payment wait confirm started...".to_owned(),
TakerSwapEvent::MakerPaymentValidatedAndConfirmed => "Maker payment validated and confirmed...".to_owned(),
TakerSwapEvent::MakerPaymentValidateFailed(_) => "Maker payment validate failed...".to_owned(),
TakerSwapEvent::MakerPaymentWaitConfirmFailed(_) => {
"Maker payment wait for confirmation failed...".to_owned()
},
TakerSwapEvent::TakerPaymentSent(_) => "Taker payment sent...".to_owned(),
TakerSwapEvent::WatcherMessageSent(_, _) => WATCHER_MESSAGE_SENT_LOG.to_owned(),
TakerSwapEvent::TakerPaymentTransactionFailed(_) => "Taker payment transaction failed...".to_owned(),
TakerSwapEvent::TakerPaymentDataSendFailed(_) => "Taker payment data send failed...".to_owned(),
TakerSwapEvent::TakerPaymentWaitConfirmFailed(_) => {
"Taker payment wait for confirmation failed...".to_owned()
},
TakerSwapEvent::TakerPaymentSpent(_) => "Taker payment spent...".to_owned(),
TakerSwapEvent::TakerPaymentWaitForSpendFailed(_) => "Taker payment wait for spend failed...".to_owned(),
TakerSwapEvent::MakerPaymentSpent(_) => "Maker payment spent...".to_owned(),
TakerSwapEvent::MakerPaymentSpendFailed(_) => "Maker payment spend failed...".to_owned(),
TakerSwapEvent::TakerPaymentWaitRefundStarted { wait_until } => {
format!("Taker payment wait refund till {} started...", wait_until)
},
TakerSwapEvent::TakerPaymentRefundStarted => "Taker payment refund started...".to_owned(),
TakerSwapEvent::TakerPaymentRefunded(_) => "Taker payment refunded...".to_owned(),
TakerSwapEvent::TakerPaymentRefundFailed(_) => "Taker payment refund failed...".to_owned(),
TakerSwapEvent::TakerPaymentRefundFinished => "Taker payment refund finished...".to_owned(),
TakerSwapEvent::Finished => "Finished".to_owned(),
}
}
fn should_ban_maker(&self) -> bool {
matches!(
self,
TakerSwapEvent::MakerPaymentValidateFailed(_) | TakerSwapEvent::TakerPaymentWaitForSpendFailed(_)
)
}
fn is_success(&self) -> bool {
matches!(
self,
TakerSwapEvent::Started(_)
| TakerSwapEvent::Negotiated(_)
| TakerSwapEvent::TakerFeeSent(_)
| TakerSwapEvent::TakerPaymentInstructionsReceived(_)
| TakerSwapEvent::MakerPaymentReceived(_)
| TakerSwapEvent::MakerPaymentWaitConfirmStarted
| TakerSwapEvent::WatcherMessageSent(_, _)
| TakerSwapEvent::MakerPaymentValidatedAndConfirmed
| TakerSwapEvent::TakerPaymentSent(_)
| TakerSwapEvent::TakerPaymentSpent(_)
| TakerSwapEvent::MakerPaymentSpent(_)
| TakerSwapEvent::Finished
)
}
fn is_error(&self) -> bool { !self.is_success() }
}
#[derive(Debug)]
pub enum TakerSwapCommand {
Start,
Negotiate,
SendTakerFee,
WaitForMakerPayment,
ValidateMakerPayment,
SendTakerPayment,
WaitForTakerPaymentSpend,
SpendMakerPayment,
PrepareForTakerPaymentRefund,
RefundTakerPayment,
FinalizeTakerPaymentRefund,
Finish,
}
impl TakerSwap {
#[inline]
fn w(&self) -> RwLockWriteGuard<TakerSwapMut> { self.mutable.write().unwrap() }
#[inline]
fn r(&self) -> RwLockReadGuard<TakerSwapMut> { self.mutable.read().unwrap() }
#[inline]
fn my_maker_coin_htlc_pub(&self) -> H264Json {
self.r()
.data
.maker_coin_htlc_pubkey
.unwrap_or_else(|| self.my_persistent_pub.into())
}
#[inline]
fn my_taker_coin_htlc_pub(&self) -> H264Json {
self.r()
.data
.taker_coin_htlc_pubkey
.unwrap_or_else(|| self.my_persistent_pub.into())
}
#[inline]
fn wait_refund_until(&self) -> u64 { self.r().data.taker_payment_lock + 3700 }
fn apply_event(&self, event: TakerSwapEvent) {
match event {
TakerSwapEvent::Started(data) => {
self.w().data = data;
log_tag!(
self.ctx,
"";
fmt = "Taker swap {} has successfully started",
self.uuid
);
},
TakerSwapEvent::StartFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::Negotiated(data) => {
self.maker_payment_lock
.store(data.maker_payment_locktime, Ordering::Relaxed);
self.w().other_maker_coin_htlc_pub = data.other_maker_coin_htlc_pub();
self.w().other_taker_coin_htlc_pub = data.other_taker_coin_htlc_pub();
self.w().secret_hash = data.secret_hash;
if data.maker_coin_swap_contract_addr.is_some() {
self.w().data.maker_coin_swap_contract_address = data.maker_coin_swap_contract_addr;
}
if data.taker_coin_swap_contract_addr.is_some() {
self.w().data.taker_coin_swap_contract_address = data.taker_coin_swap_contract_addr;
}
},
TakerSwapEvent::NegotiateFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerFeeSent(tx) => self.w().taker_fee = Some(tx),
TakerSwapEvent::TakerFeeSendFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentInstructionsReceived(instructions) => {
self.w().payment_instructions = instructions
},
TakerSwapEvent::MakerPaymentReceived(tx) => self.w().maker_payment = Some(tx),
TakerSwapEvent::MakerPaymentWaitConfirmStarted => (),
TakerSwapEvent::MakerPaymentValidatedAndConfirmed => {
self.maker_payment_confirmed.store(true, Ordering::Relaxed)
},
TakerSwapEvent::MakerPaymentValidateFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::MakerPaymentWaitConfirmFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentSent(tx) => self.w().taker_payment = Some(tx),
TakerSwapEvent::WatcherMessageSent(maker_payment_spend_preimage, taker_payment_refund_preimage) => {
self.w().maker_payment_spend_preimage = maker_payment_spend_preimage;
self.w().taker_payment_refund_preimage = taker_payment_refund_preimage;
},
TakerSwapEvent::TakerPaymentTransactionFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentDataSendFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentWaitConfirmFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentSpent(data) => {
self.w().taker_payment_spend = Some(data.transaction);
self.w().secret = data.secret;
},
TakerSwapEvent::TakerPaymentWaitForSpendFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::MakerPaymentSpent(tx) => self.w().maker_payment_spend = Some(tx),
TakerSwapEvent::MakerPaymentSpendFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentWaitRefundStarted { .. } => (),
TakerSwapEvent::TakerPaymentRefundStarted => (),
TakerSwapEvent::TakerPaymentRefunded(tx) => self.w().taker_payment_refund = tx,
TakerSwapEvent::TakerPaymentRefundFailed(err) => self.errors.lock().push(err),
TakerSwapEvent::TakerPaymentRefundFinished => (),
TakerSwapEvent::Finished => self.finished_at.store(now_ms() / 1000, Ordering::Relaxed),
}
}
async fn handle_command(
&self,
command: TakerSwapCommand,
) -> Result<(Option<TakerSwapCommand>, Vec<TakerSwapEvent>), String> {
match command {
TakerSwapCommand::Start => self.start().await,
TakerSwapCommand::Negotiate => self.negotiate().await,
TakerSwapCommand::SendTakerFee => self.send_taker_fee().await,
TakerSwapCommand::WaitForMakerPayment => self.wait_for_maker_payment().await,
TakerSwapCommand::ValidateMakerPayment => self.validate_maker_payment().await,
TakerSwapCommand::SendTakerPayment => self.send_taker_payment().await,
TakerSwapCommand::WaitForTakerPaymentSpend => self.wait_for_taker_payment_spend().await,
TakerSwapCommand::SpendMakerPayment => self.spend_maker_payment().await,
TakerSwapCommand::PrepareForTakerPaymentRefund => self.prepare_for_taker_payment_refund().await,
TakerSwapCommand::RefundTakerPayment => self.refund_taker_payment().await,
TakerSwapCommand::FinalizeTakerPaymentRefund => self.finalize_taker_payment_refund().await,
TakerSwapCommand::Finish => Ok((None, vec![TakerSwapEvent::Finished])),
}
}
#[allow(clippy::too_many_arguments)]
pub fn new(
ctx: MmArc,
maker: bits256,
maker_amount: MmNumber,
taker_amount: MmNumber,
my_persistent_pub: H264,
uuid: Uuid,
my_order_uuid: Option<Uuid>,
conf_settings: SwapConfirmationsSettings,
maker_coin: MmCoinEnum,
taker_coin: MmCoinEnum,
payment_locktime: u64,
p2p_privkey: Option<KeyPair>,
) -> Self {
TakerSwap {
maker_coin,
taker_coin,
maker_amount,
taker_amount,
my_persistent_pub,
maker,
uuid,
my_order_uuid,
maker_payment_confirmed: AtomicBool::new(false),
finished_at: AtomicU64::new(0),
maker_payment_lock: AtomicU64::new(0),
errors: PaMutex::new(Vec::new()),
conf_settings,
payment_locktime,
p2p_privkey,
mutable: RwLock::new(TakerSwapMut {
data: TakerSwapData::default(),
other_maker_coin_htlc_pub: H264::default(),
other_taker_coin_htlc_pub: H264::default(),
taker_fee: None,
maker_payment: None,
taker_payment: None,
taker_payment_spend: None,
maker_payment_spend_preimage: None,
taker_payment_refund_preimage: None,
maker_payment_spend: None,
taker_payment_refund: None,
secret_hash: BytesJson::default(),
secret: H256Json::default(),
payment_instructions: None,
}),
ctx,
#[cfg(test)]
fail_at: None,
}
}
fn get_my_negotiation_data(
&self,
secret_hash: Vec<u8>,
maker_coin_swap_contract: Vec<u8>,
taker_coin_swap_contract: Vec<u8>,
) -> NegotiationDataMsg {
let r = self.r();
let equal = r.data.maker_coin_htlc_pubkey == r.data.taker_coin_htlc_pubkey;
let same_as_persistent = r.data.maker_coin_htlc_pubkey == Some(r.data.my_persistent_pub);
if equal && same_as_persistent {
NegotiationDataMsg::V2(NegotiationDataV2 {
started_at: r.data.started_at,
secret_hash,
payment_locktime: r.data.taker_payment_lock,
persistent_pubkey: self.my_persistent_pub.to_vec(),
maker_coin_swap_contract,
taker_coin_swap_contract,
})
} else {
NegotiationDataMsg::V3(NegotiationDataV3 {
started_at: r.data.started_at,
payment_locktime: r.data.taker_payment_lock,
secret_hash,
maker_coin_swap_contract,
taker_coin_swap_contract,
maker_coin_htlc_pub: self.my_maker_coin_htlc_pub().into(),
taker_coin_htlc_pub: self.my_taker_coin_htlc_pub().into(),
})
}
}
/// # Panic
///
/// Panic if taker_fee of [`TakerSwapMut`] is [`Option::None`].
async fn get_taker_fee_data(&self) -> Result<SwapTxDataMsg, MmError<PaymentInstructionsErr>> {
// If taker fee is a lightning payment the payment hash will be sent in the message
let taker_fee_data = self
.r()
.taker_fee
.as_ref()
.expect("TakerSwapMut::taker_fee must be some value to use get_taker_fee_data")
.tx_hex
.0
.clone();
let secret_hash = self.r().secret_hash.0.clone();
let maker_amount = self.maker_amount.clone().into();
let maker_lock_duration =
(self.r().data.lock_duration as f64 * self.taker_coin.maker_locktime_multiplier()).ceil() as u64;
let expires_in = wait_for_maker_payment_conf_duration(self.r().data.lock_duration);
let instructions = self
.maker_coin
.maker_payment_instructions(&secret_hash, &maker_amount, maker_lock_duration, expires_in)
.await?;
Ok(SwapTxDataMsg::new(taker_fee_data, instructions))
}
async fn start(&self) -> Result<(Option<TakerSwapCommand>, Vec<TakerSwapEvent>), String> {
// do not use self.r().data here as it is not initialized at this step yet
let stage = FeeApproxStage::StartSwap;
let dex_fee = dex_fee_amount_from_taker_coin(&self.taker_coin, self.maker_coin.ticker(), &self.taker_amount);
let preimage_value = TradePreimageValue::Exact(self.taker_amount.to_decimal());
let fee_to_send_dex_fee_fut = self
.taker_coin
.get_fee_to_send_taker_fee(dex_fee.to_decimal(), stage.clone());
let fee_to_send_dex_fee = match fee_to_send_dex_fee_fut.await {
Ok(fee) => fee,
Err(e) => {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!taker_coin.get_fee_to_send_taker_fee {}", e).into(),
)]))
},
};
let get_sender_trade_fee_fut = self.taker_coin.get_sender_trade_fee(preimage_value, stage.clone());
let taker_payment_trade_fee = match get_sender_trade_fee_fut.await {
Ok(fee) => fee,
Err(e) => {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!taker_coin.get_sender_trade_fee {}", e).into(),
)]))
},
};
let maker_payment_spend_trade_fee_fut = self
.maker_coin
.get_receiver_trade_fee(self.taker_amount.to_decimal(), stage.clone());
let maker_payment_spend_trade_fee = match maker_payment_spend_trade_fee_fut.compat().await {
Ok(fee) => fee,
Err(e) => {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!maker_coin.get_receiver_trade_fee {}", e).into(),
)]))
},
};
let params = TakerSwapPreparedParams {
dex_fee: dex_fee.clone(),
fee_to_send_dex_fee: fee_to_send_dex_fee.clone(),
taker_payment_trade_fee: taker_payment_trade_fee.clone(),
maker_payment_spend_trade_fee: maker_payment_spend_trade_fee.clone(),
};
let check_balance_f = check_balance_for_taker_swap(
&self.ctx,
&self.taker_coin,
&self.maker_coin,
self.taker_amount.clone(),
Some(&self.uuid),
Some(params),
stage,
);
if let Err(e) = check_balance_f.await {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!check_balance_for_taker_swap {}", e).into(),
)]));
}
let started_at = now_ms() / 1000;
let maker_coin_start_block = match self.maker_coin.current_block().compat().await {
Ok(b) => b,
Err(e) => {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!maker_coin.current_block {}", e).into(),
)]))
},
};
let taker_coin_start_block = match self.taker_coin.current_block().compat().await {
Ok(b) => b,
Err(e) => {
return Ok((Some(TakerSwapCommand::Finish), vec![TakerSwapEvent::StartFailed(
ERRL!("!taker_coin.current_block {}", e).into(),
)]))
},
};
let maker_coin_swap_contract_address = self.maker_coin.swap_contract_address();
let taker_coin_swap_contract_address = self.taker_coin.swap_contract_address();