forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
maker_swap.rs
2467 lines (2255 loc) · 162 KB
/
maker_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_base_coin_balance_for_swap, check_my_coin_balance_for_swap, CheckBalanceError,
CheckBalanceResult};
use super::pubkey_banning::ban_pubkey_on_failed_swap;
use super::swap_lock::{SwapLock, SwapLockOps};
use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult};
use super::{broadcast_my_swap_status, broadcast_swap_message_every, check_other_coin_balance_for_swap,
dex_fee_amount_from_taker_coin, get_locked_amount, recv_swap_msg, swap_topic, AtomicSwap, LockedAmount,
MySwapInfo, NegotiationDataMsg, NegotiationDataV2, NegotiationDataV3, RecoveredSwap, RecoveredSwapAction,
SavedSwap, SavedSwapIo, SavedTradeFee, SwapConfirmationsSettings, SwapError, SwapMsg, SwapsContext,
TransactionIdentifier, WAIT_CONFIRM_INTERVAL};
use crate::mm2::lp_dispatcher::{DispatcherContext, LpEvents};
use crate::mm2::lp_network::subscribe_to_topic;
use crate::mm2::lp_ordermatch::{MakerOrderBuilder, OrderConfirmationsSettings};
use crate::mm2::lp_price::fetch_swap_coins_price;
use crate::mm2::lp_swap::{broadcast_p2p_tx_msg, tx_helper_topic};
use crate::mm2::MM_VERSION;
use bitcrypto::dhash160;
use coins::{CanRefundHtlc, FeeApproxStage, FoundSwapTxSpend, MmCoinEnum, SearchForSwapTxSpendInput, TradeFee,
TradePreimageValue, TransactionEnum, ValidatePaymentInput};
use common::log::{debug, error, info, warn};
use common::{bits256, executor::Timer, now_ms, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::SerializableSecp256k1Keypair;
use futures::{compat::Future01CompatExt, select, FutureExt};
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::{H160, H256, H264};
use rand::Rng;
use rpc::v1::types::{Bytes as BytesJson, H160 as H160Json, H256 as H256Json, H264 as H264Json};
use std::any::TypeId;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use uuid::Uuid;
pub const MAKER_SUCCESS_EVENTS: [&str; 11] = [
"Started",
"Negotiated",
"TakerFeeValidated",
"MakerPaymentSent",
"TakerPaymentReceived",
"TakerPaymentWaitConfirmStarted",
"TakerPaymentValidatedAndConfirmed",
"TakerPaymentSpent",
"TakerPaymentSpendConfirmStarted",
"TakerPaymentSpendConfirmed",
"Finished",
];
pub const MAKER_ERROR_EVENTS: [&str; 13] = [
"StartFailed",
"NegotiateFailed",
"TakerFeeValidateFailed",
"MakerPaymentTransactionFailed",
"MakerPaymentDataSendFailed",
"MakerPaymentWaitConfirmFailed",
"TakerPaymentValidateFailed",
"TakerPaymentWaitConfirmFailed",
"TakerPaymentSpendFailed",
"TakerPaymentSpendConfirmFailed",
"MakerPaymentWaitRefundStarted",
"MakerPaymentRefunded",
"MakerPaymentRefundFailed",
];
pub fn stats_maker_swap_dir(ctx: &MmArc) -> PathBuf { ctx.dbdir().join("SWAPS").join("STATS").join("MAKER") }
pub fn stats_maker_swap_file_path(ctx: &MmArc, uuid: &Uuid) -> PathBuf {
stats_maker_swap_dir(ctx).join(format!("{}.json", uuid))
}
async fn save_my_maker_swap_event(ctx: &MmArc, swap: &MakerSwap, event: MakerSavedEvent) -> Result<(), String> {
let swap = match SavedSwap::load_my_swap_from_db(ctx, swap.uuid).await {
Ok(Some(swap)) => swap,
Ok(None) => SavedSwap::Maker(MakerSavedSwap {
uuid: swap.uuid,
my_order_uuid: swap.my_order_uuid,
maker_amount: Some(swap.maker_amount.clone()),
maker_coin: Some(swap.maker_coin.ticker().to_owned()),
maker_coin_usd_price: None,
taker_amount: Some(swap.taker_amount.clone()),
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(MM_VERSION.to_owned()),
events: vec![],
success_events: MAKER_SUCCESS_EVENTS.iter().map(|event| event.to_string()).collect(),
error_events: MAKER_ERROR_EVENTS.iter().map(|event| event.to_string()).collect(),
}),
Err(e) => return ERR!("{}", e),
};
if let SavedSwap::Maker(mut maker_swap) = swap {
maker_swap.events.push(event);
if maker_swap.is_success().unwrap_or(false) {
maker_swap.fetch_and_set_usd_prices().await;
}
let new_swap = SavedSwap::Maker(maker_swap);
try_s!(new_swap.save_to_db(ctx).await);
Ok(())
} else {
ERR!("Expected SavedSwap::Maker, got {:?}", swap)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TakerNegotiationData {
pub taker_payment_locktime: u64,
pub taker_pubkey: H264Json,
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 TakerNegotiationData {
#[inline]
fn other_maker_coin_htlc_pub(&self) -> H264 { self.maker_coin_htlc_pubkey.unwrap_or(self.taker_pubkey).into() }
#[inline]
fn other_taker_coin_htlc_pub(&self) -> H264 { self.taker_coin_htlc_pubkey.unwrap_or(self.taker_pubkey).into() }
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
pub struct MakerSwapData {
pub taker_coin: String,
pub maker_coin: String,
pub taker: H256Json,
pub secret: H256Json,
pub secret_hash: Option<H160Json>,
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 maker_payment_lock: u64,
/// Allows to recognize one SWAP from the other in the logs. #274.
pub uuid: Uuid,
pub started_at: u64,
pub maker_coin_start_block: u64,
pub taker_coin_start_block: u64,
/// A `MakerPayment` transaction fee.
/// Note this value is used to calculate locked amount only.
pub maker_payment_trade_fee: Option<SavedTradeFee>,
/// A transaction fee that should be paid to spend a `TakerPayment`.
/// Note this value is used to calculate locked amount only.
pub taker_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 MakerSwapMut {
data: MakerSwapData,
other_maker_coin_htlc_pub: H264,
other_taker_coin_htlc_pub: H264,
#[allow(dead_code)]
taker_fee: Option<TransactionIdentifier>,
maker_payment: Option<TransactionIdentifier>,
taker_payment: Option<TransactionIdentifier>,
taker_payment_spend: Option<TransactionIdentifier>,
taker_payment_spend_confirmed: bool,
maker_payment_refund: Option<TransactionIdentifier>,
}
pub struct MakerSwap {
ctx: MmArc,
maker_coin: MmCoinEnum,
taker_coin: MmCoinEnum,
maker_amount: BigDecimal,
taker_amount: BigDecimal,
my_persistent_pub: H264,
taker: bits256,
uuid: Uuid,
my_order_uuid: Option<Uuid>,
taker_payment_lock: AtomicU64,
taker_payment_confirmed: AtomicBool,
errors: PaMutex<Vec<SwapError>>,
finished_at: AtomicU64,
mutable: RwLock<MakerSwapMut>,
conf_settings: SwapConfirmationsSettings,
payment_locktime: u64,
/// Temporary privkey used to sign P2P messages when applicable
p2p_privkey: Option<KeyPair>,
secret: H256,
}
impl MakerSwap {
#[inline]
fn w(&self) -> RwLockWriteGuard<MakerSwapMut> { self.mutable.write().unwrap() }
#[inline]
fn r(&self) -> RwLockReadGuard<MakerSwapMut> { self.mutable.read().unwrap() }
#[inline]
pub fn generate_secret() -> [u8; 32] { rand::thread_rng().gen() }
#[inline]
fn secret_hash(&self) -> H160 {
self.r()
.data
.secret_hash
.map(H160Json::into)
.unwrap_or_else(|| dhash160(self.secret.as_slice()))
}
#[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())
}
fn wait_refund_until(&self) -> u64 { self.r().data.maker_payment_lock + 3700 }
fn apply_event(&self, event: MakerSwapEvent) {
match event {
MakerSwapEvent::Started(data) => {
self.w().data = data;
},
MakerSwapEvent::StartFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::Negotiated(data) => {
self.taker_payment_lock
.store(data.taker_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();
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;
}
},
MakerSwapEvent::NegotiateFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::TakerFeeValidated(tx) => self.w().taker_fee = Some(tx),
MakerSwapEvent::TakerFeeValidateFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::MakerPaymentSent(tx) => self.w().maker_payment = Some(tx),
MakerSwapEvent::MakerPaymentTransactionFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::MakerPaymentDataSendFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::MakerPaymentWaitConfirmFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::TakerPaymentReceived(tx) => self.w().taker_payment = Some(tx),
MakerSwapEvent::TakerPaymentWaitConfirmStarted => (),
MakerSwapEvent::TakerPaymentValidatedAndConfirmed => {
self.taker_payment_confirmed.store(true, Ordering::Relaxed)
},
MakerSwapEvent::TakerPaymentValidateFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::TakerPaymentWaitConfirmFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::TakerPaymentSpent(tx) => self.w().taker_payment_spend = Some(tx),
MakerSwapEvent::TakerPaymentSpendFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::TakerPaymentSpendConfirmStarted => (),
MakerSwapEvent::TakerPaymentSpendConfirmed => self.w().taker_payment_spend_confirmed = true,
MakerSwapEvent::TakerPaymentSpendConfirmFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::MakerPaymentWaitRefundStarted { .. } => (),
MakerSwapEvent::MakerPaymentRefunded(tx) => self.w().maker_payment_refund = Some(tx),
MakerSwapEvent::MakerPaymentRefundFailed(err) => self.errors.lock().push(err),
MakerSwapEvent::Finished => self.finished_at.store(now_ms() / 1000, Ordering::Relaxed),
}
}
async fn handle_command(
&self,
command: MakerSwapCommand,
) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
match command {
MakerSwapCommand::Start => self.start().await,
MakerSwapCommand::Negotiate => self.negotiate().await,
MakerSwapCommand::WaitForTakerFee => self.wait_taker_fee().await,
MakerSwapCommand::SendPayment => self.maker_payment().await,
MakerSwapCommand::WaitForTakerPayment => self.wait_for_taker_payment().await,
MakerSwapCommand::ValidateTakerPayment => self.validate_taker_payment().await,
MakerSwapCommand::SpendTakerPayment => self.spend_taker_payment().await,
MakerSwapCommand::ConfirmTakerPaymentSpend => self.confirm_taker_payment_spend().await,
MakerSwapCommand::RefundMakerPayment => self.refund_maker_payment().await,
MakerSwapCommand::Finish => Ok((None, vec![MakerSwapEvent::Finished])),
}
}
#[allow(clippy::too_many_arguments)]
pub fn new(
ctx: MmArc,
taker: bits256,
maker_amount: BigDecimal,
taker_amount: BigDecimal,
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>,
secret: H256,
) -> Self {
MakerSwap {
maker_coin,
taker_coin,
maker_amount,
taker_amount,
my_persistent_pub,
taker,
uuid,
my_order_uuid,
taker_payment_lock: AtomicU64::new(0),
errors: PaMutex::new(Vec::new()),
finished_at: AtomicU64::new(0),
taker_payment_confirmed: AtomicBool::new(false),
conf_settings,
payment_locktime,
p2p_privkey,
mutable: RwLock::new(MakerSwapMut {
data: MakerSwapData::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_refund: None,
taker_payment_spend_confirmed: false,
}),
ctx,
secret,
}
}
fn get_my_negotiation_data(&self) -> NegotiationDataMsg {
let r = self.r();
let secret_hash = self.secret_hash().to_vec();
let maker_coin_swap_contract = self
.maker_coin
.swap_contract_address()
.map_or_else(Vec::new, |addr| addr.0);
let taker_coin_swap_contract = self
.taker_coin
.swap_contract_address()
.map_or_else(Vec::new, |addr| addr.0);
if r.data.maker_coin_htlc_pubkey != r.data.taker_coin_htlc_pubkey {
NegotiationDataMsg::V3(NegotiationDataV3 {
started_at: r.data.started_at,
payment_locktime: r.data.maker_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(),
})
} else {
NegotiationDataMsg::V2(NegotiationDataV2 {
started_at: r.data.started_at,
payment_locktime: r.data.maker_payment_lock,
persistent_pubkey: r.data.my_persistent_pub.0.to_vec(),
secret_hash,
maker_coin_swap_contract,
taker_coin_swap_contract,
})
}
}
async fn start(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
// do not use self.r().data here as it is not initialized at this step yet
let preimage_value = TradePreimageValue::Exact(self.maker_amount.clone());
let stage = FeeApproxStage::StartSwap;
let get_sender_trade_fee_fut = self.maker_coin.get_sender_trade_fee(preimage_value, stage.clone());
let maker_payment_trade_fee = match get_sender_trade_fee_fut.await {
Ok(fee) => fee,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::StartFailed(
ERRL!("!maker_coin.get_sender_trade_fee {}", e).into(),
)]))
},
};
let taker_payment_spend_trade_fee_fut = self.taker_coin.get_receiver_trade_fee(stage.clone());
let taker_payment_spend_trade_fee = match taker_payment_spend_trade_fee_fut.compat().await {
Ok(fee) => fee,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::StartFailed(
ERRL!("!taker_coin.get_receiver_trade_fee {}", e).into(),
)]))
},
};
let params = MakerSwapPreparedParams {
maker_payment_trade_fee: maker_payment_trade_fee.clone(),
taker_payment_spend_trade_fee: taker_payment_spend_trade_fee.clone(),
};
match check_balance_for_maker_swap(
&self.ctx,
&self.maker_coin,
&self.taker_coin,
self.maker_amount.clone().into(),
Some(&self.uuid),
Some(params),
stage,
)
.await
{
Ok(_) => (),
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::StartFailed(
ERRL!("!check_balance_for_maker_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(MakerSwapCommand::Finish), vec![MakerSwapEvent::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(MakerSwapCommand::Finish), vec![MakerSwapEvent::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();
let unique_data = self.unique_swap_data();
let maker_coin_htlc_key_pair = self.maker_coin.derive_htlc_key_pair(&unique_data);
let taker_coin_htlc_key_pair = self.taker_coin.derive_htlc_key_pair(&unique_data);
let data = MakerSwapData {
taker_coin: self.taker_coin.ticker().to_owned(),
maker_coin: self.maker_coin.ticker().to_owned(),
taker: self.taker.bytes.into(),
secret: self.secret.into(),
secret_hash: Some(self.secret_hash().into()),
started_at,
lock_duration: self.payment_locktime,
maker_amount: self.maker_amount.clone(),
taker_amount: self.taker_amount.clone(),
maker_payment_confirmations: self.conf_settings.maker_coin_confs,
maker_payment_requires_nota: Some(self.conf_settings.maker_coin_nota),
taker_payment_confirmations: self.conf_settings.taker_coin_confs,
taker_payment_requires_nota: Some(self.conf_settings.taker_coin_nota),
maker_payment_lock: started_at + self.payment_locktime * 2,
my_persistent_pub: self.my_persistent_pub.into(),
uuid: self.uuid,
maker_coin_start_block,
taker_coin_start_block,
maker_payment_trade_fee: Some(SavedTradeFee::from(maker_payment_trade_fee)),
taker_payment_spend_trade_fee: Some(SavedTradeFee::from(taker_payment_spend_trade_fee)),
maker_coin_swap_contract_address,
taker_coin_swap_contract_address,
maker_coin_htlc_pubkey: Some(maker_coin_htlc_key_pair.public_slice().into()),
taker_coin_htlc_pubkey: Some(taker_coin_htlc_key_pair.public_slice().into()),
p2p_privkey: self.p2p_privkey.map(SerializableSecp256k1Keypair::from),
};
Ok((Some(MakerSwapCommand::Negotiate), vec![MakerSwapEvent::Started(data)]))
}
async fn negotiate(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let negotiation_data = self.get_my_negotiation_data();
let maker_negotiation_data = SwapMsg::Negotiation(negotiation_data);
const NEGOTIATION_TIMEOUT: u64 = 90;
debug!("Sending maker negotiation data {:?}", maker_negotiation_data);
let send_abort_handle = broadcast_swap_message_every(
self.ctx.clone(),
swap_topic(&self.uuid),
maker_negotiation_data,
NEGOTIATION_TIMEOUT as f64 / 6.,
self.p2p_privkey,
);
let recv_fut = recv_swap_msg(
self.ctx.clone(),
|store| store.negotiation_reply.take(),
&self.uuid,
NEGOTIATION_TIMEOUT,
);
let taker_data = match recv_fut.await {
Ok(d) => d,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::NegotiateFailed(
ERRL!("{:?}", e).into(),
)]))
},
};
drop(send_abort_handle);
let time_dif = (self.r().data.started_at as i64 - taker_data.started_at() as i64).abs();
if time_dif > 60 {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::NegotiateFailed(
ERRL!("Started_at time_dif over 60 {}", time_dif).into(),
)]));
}
let expected_lock_time = taker_data.started_at() + self.r().data.lock_duration;
if taker_data.payment_locktime() != expected_lock_time {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::NegotiateFailed(
ERRL!(
"taker_data.payment_locktime {} not equal to expected {}",
taker_data.payment_locktime(),
expected_lock_time
)
.into(),
)]));
}
let maker_coin_swap_contract_addr = match self
.maker_coin
.negotiate_swap_contract_addr(taker_data.maker_coin_swap_contract())
{
Ok(addr) => addr,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::NegotiateFailed(
ERRL!("!maker_coin.negotiate_swap_contract_addr {}", e).into(),
)]))
},
};
let taker_coin_swap_contract_addr = match self
.taker_coin
.negotiate_swap_contract_addr(taker_data.taker_coin_swap_contract())
{
Ok(addr) => addr,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![MakerSwapEvent::NegotiateFailed(
ERRL!("!taker_coin.negotiate_swap_contract_addr {}", e).into(),
)]))
},
};
Ok((Some(MakerSwapCommand::WaitForTakerFee), vec![
MakerSwapEvent::Negotiated(TakerNegotiationData {
taker_payment_locktime: taker_data.payment_locktime(),
// using default to avoid misuse of this field
// maker_coin_htlc_pubkey and taker_coin_htlc_pubkey must be used instead
taker_pubkey: H264Json::default(),
maker_coin_swap_contract_addr,
taker_coin_swap_contract_addr,
maker_coin_htlc_pubkey: Some(taker_data.maker_coin_htlc_pub().into()),
taker_coin_htlc_pubkey: Some(taker_data.taker_coin_htlc_pub().into()),
}),
]))
}
async fn wait_taker_fee(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
const TAKER_FEE_RECV_TIMEOUT: u64 = 600;
let negotiated = SwapMsg::Negotiated(true);
let send_abort_handle = broadcast_swap_message_every(
self.ctx.clone(),
swap_topic(&self.uuid),
negotiated,
TAKER_FEE_RECV_TIMEOUT as f64 / 6.,
self.p2p_privkey,
);
let recv_fut = recv_swap_msg(
self.ctx.clone(),
|store| store.taker_fee.take(),
&self.uuid,
TAKER_FEE_RECV_TIMEOUT,
);
let payload = match recv_fut.await {
Ok(d) => d,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::TakerFeeValidateFailed(ERRL!("{}", e).into()),
]))
},
};
drop(send_abort_handle);
let taker_fee = match self.taker_coin.tx_enum_from_bytes(&payload) {
Ok(tx) => tx,
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::TakerFeeValidateFailed(ERRL!("{}", e).into()),
]))
},
};
let hash = taker_fee.tx_hash();
info!("Taker fee tx {:02x}", hash);
let taker_amount = MmNumber::from(self.taker_amount.clone());
let fee_amount = dex_fee_amount_from_taker_coin(&self.taker_coin, &self.r().data.maker_coin, &taker_amount);
let other_taker_coin_htlc_pub = self.r().other_taker_coin_htlc_pub;
let taker_coin_start_block = self.r().data.taker_coin_start_block;
let mut attempts = 0;
loop {
match self
.taker_coin
.validate_fee(
&taker_fee,
&*other_taker_coin_htlc_pub,
&DEX_FEE_ADDR_RAW_PUBKEY,
&fee_amount.clone().into(),
taker_coin_start_block,
self.uuid.as_bytes(),
)
.compat()
.await
{
Ok(_) => break,
Err(err) => {
if attempts >= 3 {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::TakerFeeValidateFailed(ERRL!("{}", err).into()),
]));
} else {
attempts += 1;
Timer::sleep(10.).await;
}
},
};
}
let fee_ident = TransactionIdentifier {
tx_hex: taker_fee.tx_hex().into(),
tx_hash: hash,
};
Ok((Some(MakerSwapCommand::SendPayment), vec![
MakerSwapEvent::TakerFeeValidated(fee_ident),
]))
}
async fn maker_payment(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let timeout = self.r().data.started_at + self.r().data.lock_duration / 3;
let now = now_ms() / 1000;
if now > timeout {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::MakerPaymentTransactionFailed(ERRL!("Timeout {} > {}", now, timeout).into()),
]));
}
let secret_hash = self.secret_hash();
let unique_data = self.unique_swap_data();
let transaction_f = self
.maker_coin
.check_if_my_payment_sent(
self.r().data.maker_payment_lock as u32,
&*self.r().other_maker_coin_htlc_pub,
secret_hash.as_slice(),
self.r().data.maker_coin_start_block,
&self.r().data.maker_coin_swap_contract_address,
&unique_data,
)
.compat();
let transaction = match transaction_f.await {
Ok(res) => match res {
Some(tx) => tx,
None => {
let payment_fut = self.maker_coin.send_maker_payment(
self.r().data.maker_payment_lock as u32,
&*self.r().other_maker_coin_htlc_pub,
secret_hash.as_slice(),
self.maker_amount.clone(),
&self.r().data.maker_coin_swap_contract_address,
&unique_data,
);
match payment_fut.compat().await {
Ok(t) => t,
Err(err) => {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::MakerPaymentTransactionFailed(
ERRL!("{}", err.get_plain_text_format()).into(),
),
]));
},
}
},
},
Err(e) => {
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::MakerPaymentTransactionFailed(ERRL!("{}", e).into()),
]))
},
};
let tx_hash = transaction.tx_hash();
info!("Maker payment tx {:02x}", tx_hash);
let tx_ident = TransactionIdentifier {
tx_hex: transaction.tx_hex().into(),
tx_hash,
};
Ok((Some(MakerSwapCommand::WaitForTakerPayment), vec![
MakerSwapEvent::MakerPaymentSent(tx_ident),
]))
}
async fn wait_for_taker_payment(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let maker_payment_hex = self.r().maker_payment.as_ref().unwrap().tx_hex.0.clone();
let msg = SwapMsg::MakerPayment(maker_payment_hex);
let abort_send_handle =
broadcast_swap_message_every(self.ctx.clone(), swap_topic(&self.uuid), msg, 600., self.p2p_privkey);
let maker_payment_wait_confirm = self.r().data.started_at + (self.r().data.lock_duration * 2) / 5;
let f = self.maker_coin.wait_for_confirmations(
&self.r().maker_payment.clone().unwrap().tx_hex,
self.r().data.maker_payment_confirmations,
self.r().data.maker_payment_requires_nota.unwrap_or(false),
maker_payment_wait_confirm,
WAIT_CONFIRM_INTERVAL,
);
if let Err(err) = f.compat().await {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::MakerPaymentWaitConfirmFailed(
ERRL!("!wait for maker payment confirmations: {}", err).into(),
),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
}
// wait for 3/5, we need to leave some time space for transaction to be confirmed
let wait_duration = (self.r().data.lock_duration * 3) / 5;
let recv_fut = recv_swap_msg(
self.ctx.clone(),
|store| store.taker_payment.take(),
&self.uuid,
wait_duration,
);
let payload = match recv_fut.await {
Ok(p) => p,
Err(e) => {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentValidateFailed(e.into()),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]))
},
};
drop(abort_send_handle);
let taker_payment = match self.taker_coin.tx_enum_from_bytes(&payload) {
Ok(tx) => tx,
Err(err) => {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentValidateFailed(ERRL!("!taker_coin.tx_enum_from_bytes: {}", err).into()),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]))
},
};
let tx_hash = taker_payment.tx_hash();
info!("Taker payment tx {:02x}", tx_hash);
let tx_ident = TransactionIdentifier {
tx_hex: taker_payment.tx_hex().into(),
tx_hash,
};
Ok((Some(MakerSwapCommand::ValidateTakerPayment), vec![
MakerSwapEvent::TakerPaymentReceived(tx_ident),
MakerSwapEvent::TakerPaymentWaitConfirmStarted,
]))
}
async fn validate_taker_payment(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let wait_duration = (self.r().data.lock_duration * 4) / 5;
let wait_taker_payment = self.r().data.started_at + wait_duration;
let confirmations = self.r().data.taker_payment_confirmations;
let wait_f = self
.taker_coin
.wait_for_confirmations(
&self.r().taker_payment.clone().unwrap().tx_hex,
confirmations,
self.r().data.taker_payment_requires_nota.unwrap_or(false),
wait_taker_payment,
WAIT_CONFIRM_INTERVAL,
)
.compat();
if let Err(err) = wait_f.await {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentWaitConfirmFailed(
ERRL!("!taker_coin.wait_for_confirmations: {}", err).into(),
),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
}
let validate_input = ValidatePaymentInput {
payment_tx: self.r().taker_payment.clone().unwrap().tx_hex.0,
time_lock: self.taker_payment_lock.load(Ordering::Relaxed) as u32,
other_pub: self.r().other_taker_coin_htlc_pub.to_vec(),
unique_swap_data: self.unique_swap_data(),
secret_hash: self.secret_hash().to_vec(),
amount: self.taker_amount.clone(),
swap_contract_address: self.r().data.taker_coin_swap_contract_address.clone(),
try_spv_proof_until: wait_taker_payment,
confirmations,
};
let validated_f = self.taker_coin.validate_taker_payment(validate_input).compat();
if let Err(e) = validated_f.await {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentValidateFailed(ERRL!("!taker_coin.validate_taker_payment: {}", e).into()),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
}
Ok((Some(MakerSwapCommand::SpendTakerPayment), vec![
MakerSwapEvent::TakerPaymentValidatedAndConfirmed,
]))
}
async fn spend_taker_payment(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let duration = (self.r().data.lock_duration * 4) / 5;
let timeout = self.r().data.started_at + duration;
let now = now_ms() / 1000;
if now > timeout {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentSpendFailed(ERRL!("Timeout {} > {}", now, timeout).into()),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
}
let spend_fut = self.taker_coin.send_maker_spends_taker_payment(
&self.r().taker_payment.clone().unwrap().tx_hex,
self.taker_payment_lock.load(Ordering::Relaxed) as u32,
&*self.r().other_taker_coin_htlc_pub,
&self.r().data.secret.0,
&self.r().data.taker_coin_swap_contract_address,
&self.unique_swap_data(),
);
let transaction = match spend_fut.compat().await {
Ok(t) => t,
Err(err) => {
if let Some(tx) = err.get_tx() {
broadcast_p2p_tx_msg(
&self.ctx,
tx_helper_topic(self.taker_coin.ticker()),
&tx,
&self.p2p_privkey,
);
}
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentSpendFailed(
ERRL!(
"!taker_coin.send_maker_spends_taker_payment: {}",
err.get_plain_text_format()
)
.into(),
),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
},
};
broadcast_p2p_tx_msg(
&self.ctx,
tx_helper_topic(self.taker_coin.ticker()),
&transaction,
&self.p2p_privkey,
);
let tx_hash = transaction.tx_hash();
info!("Taker payment spend tx {:02x}", tx_hash);
let tx_ident = TransactionIdentifier {
tx_hex: transaction.tx_hex().into(),
tx_hash,
};
Ok((Some(MakerSwapCommand::ConfirmTakerPaymentSpend), vec![
MakerSwapEvent::TakerPaymentSpent(tx_ident),
MakerSwapEvent::TakerPaymentSpendConfirmStarted,
]))
}
async fn confirm_taker_payment_spend(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
// we should wait for only one confirmation to make sure our spend transaction is not failed
let confirmations = std::cmp::min(1, self.r().data.taker_payment_confirmations);
let requires_nota = false;
let wait_fut = self.taker_coin.wait_for_confirmations(
&self.r().taker_payment_spend.clone().unwrap().tx_hex,
confirmations,
requires_nota,
self.wait_refund_until(),
WAIT_CONFIRM_INTERVAL,
);
if let Err(err) = wait_fut.compat().await {
return Ok((Some(MakerSwapCommand::RefundMakerPayment), vec![
MakerSwapEvent::TakerPaymentSpendConfirmFailed(
ERRL!("!wait for taker payment spend confirmations: {}", err).into(),
),
MakerSwapEvent::MakerPaymentWaitRefundStarted {
wait_until: self.wait_refund_until(),
},
]));
}
Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::TakerPaymentSpendConfirmed,
]))
}
async fn refund_maker_payment(&self) -> Result<(Option<MakerSwapCommand>, Vec<MakerSwapEvent>), String> {
let locktime = self.r().data.maker_payment_lock;
loop {
match self.maker_coin.can_refund_htlc(locktime).compat().await {
Ok(CanRefundHtlc::CanRefundNow) => break,
Ok(CanRefundHtlc::HaveToWait(to_sleep)) => Timer::sleep(to_sleep as f64).await,
Err(e) => {
error!("Error {} on can_refund_htlc, retrying in 30 seconds", e);
Timer::sleep(30.).await;
},
}
}
let spend_fut = self.maker_coin.send_maker_refunds_payment(
&self.r().maker_payment.clone().unwrap().tx_hex,
self.r().data.maker_payment_lock as u32,
&*self.r().other_maker_coin_htlc_pub,
self.secret_hash().as_slice(),
&self.r().data.maker_coin_swap_contract_address,
&self.unique_swap_data(),
);
let transaction = match spend_fut.compat().await {
Ok(t) => t,
Err(err) => {
if let Some(tx) = err.get_tx() {
broadcast_p2p_tx_msg(
&self.ctx,
tx_helper_topic(self.maker_coin.ticker()),
&tx,
&self.p2p_privkey,
);
}
return Ok((Some(MakerSwapCommand::Finish), vec![
MakerSwapEvent::MakerPaymentRefundFailed(
ERRL!(
"!maker_coin.send_maker_refunds_payment: {}",
err.get_plain_text_format()
)
.into(),
),
]));
},
};
broadcast_p2p_tx_msg(
&self.ctx,
tx_helper_topic(self.maker_coin.ticker()),
&transaction,
&self.p2p_privkey,
);
let tx_hash = transaction.tx_hash();
info!("Maker payment refund tx {:02x}", tx_hash);
let tx_ident = TransactionIdentifier {
tx_hex: transaction.tx_hex().into(),
tx_hash,
};