forked from ibbtco/electrum-dash
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdash_ps.py
2007 lines (1844 loc) · 86.5 KB
/
dash_ps.py
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
# -*- coding: utf-8 -*-
import asyncio
import copy
import random
import time
import threading
from collections import deque
from uuid import uuid4
from . import util
from .dash_msg import PRIVATESEND_ENTRY_MAX_SIZE, DSPoolState
from .dash_ps_net import (PSMixSession, PRIVATESEND_SESSION_MSG_TIMEOUT,
MixSessionTimeout, MixSessionPeerClosed)
from .dash_ps_wallet import (PSDataMixin, PSKeystoreMixin, KeyPairsMixin,
KPStates, NotFoundInKeypairs, AddPSDataError,
SignWithKeypairsFailed)
from .dash_ps_util import (PSOptsMixin, PSUtilsMixin, PSGUILogHandler,
PSManLogAdapter, PSCoinRounds, PSStates,
PS_DENOMS_DICT, COLLATERAL_VAL, MIN_DENOM_VAL,
CREATE_COLLATERAL_VAL, CREATE_COLLATERAL_VALS,
PSTxWorkflow, PSDenominateWorkflow, calc_tx_fee)
from .dash_tx import PSTxTypes, SPEC_TX_NAMES, CTxIn
from .logging import Logger
from .transaction import Transaction, PartialTxOutput, PartialTransaction
from .util import (NoDynamicFeeEstimates, log_exceptions, SilentTaskGroup,
NotEnoughFunds, bfh, is_android)
from .i18n import _
PS_DENOM_REVERSE_DICT = {int(v): k for k, v in PS_DENOMS_DICT.items()}
class TooManyUtxos(Exception):
"""Thrown when creating new denoms/collateral txs from coins"""
class TooLargeUtxoVal(Exception):
"""Thrown when creating new collateral txs from coins"""
class PSManager(Logger, PSKeystoreMixin, PSDataMixin, PSOptsMixin,
PSUtilsMixin, KeyPairsMixin):
'''Class representing wallet PrivateSend manager'''
LOGGING_SHORTCUT = 'A'
ADD_PS_DATA_ERR_MSG = _('Error on adding PrivateSend transaction data.')
SPEND_TO_PS_ADDRS_MSG = _('For privacy reasons blocked attempt to'
' transfer coins to PrivateSend address.')
WATCHING_ONLY_MSG = _('This is a watching-only wallet.'
' Mixing can not be run.')
ALL_MIXED_MSG = _('PrivateSend mixing is done')
CLEAR_PS_DATA_MSG = _('Are you sure to clear all wallet PrivateSend data?'
' This is not recommended if there is'
' no particular need.')
NO_NETWORK_MSG = _('Can not start mixing. Network is not available')
NO_DASH_NET_MSG = _('Can not start mixing. DashNet is not available')
LLMQ_DATA_NOT_READY = _('LLMQ quorums data is not fully loaded.')
MNS_DATA_NOT_READY = _('Masternodes data is not fully loaded.')
NOT_ENABLED_MSG = _('PrivateSend mixing is not enabled')
INITIALIZING_MSG = _('PrivateSend mixing is initializing.'
' Please try again soon')
MIXING_ALREADY_RUNNING_MSG = _('PrivateSend mixing is already running.')
MIXING_NOT_RUNNING_MSG = _('PrivateSend mixing is not running.')
FIND_UNTRACKED_RUN_MSG = _('PrivateSend mixing can not start. Process of'
' finding untracked PS transactions'
' is currently run')
ERRORED_MSG = _('PrivateSend mixing can not start.'
' Please check errors in PS Log tab')
UNKNOWN_STATE_MSG = _('PrivateSend mixing can not start.'
' Unknown state: {}')
WAIT_MIXING_STOP_MSG = _('Mixing is not stopped. If mixing sessions ends'
' prematurely additional pay collateral may be'
' paid. Do you really want to close wallet?')
NO_NETWORK_STOP_MSG = _('Network is not available')
OTHER_COINS_ARRIVED_MSG1 = _('Some unknown coins arrived on addresses'
' reserved for PrivateSend use, txid: {}.')
OTHER_COINS_ARRIVED_MSG2 = _('WARNING: it is not recommended to spend'
' these coins in regular transactions!')
OTHER_COINS_ARRIVED_MSG3 = _('You can use these coins in PrivateSend'
' mixing process by manually selecting UTXO'
' and creating new denoms or new collateral,'
' depending on UTXO value.')
OTHER_COINS_ARRIVED_Q = _('Do you want to use other coins now?')
if is_android():
NO_DYNAMIC_FEE_MSG = _('{}\n\nYou can switch fee estimation method'
' on send screen')
OTHER_COINS_ARRIVED_MSG4 = _('You can view and use these coins from'
' Coins popup from PrivateSend options.')
else:
NO_DYNAMIC_FEE_MSG = _('{}\n\nYou can switch to static fee estimation'
' on Fees Preferences tab')
OTHER_COINS_ARRIVED_MSG4 = _('You can view and use these coins from'
' Coins tab.')
def __init__(self, wallet):
Logger.__init__(self)
PSDataMixin.__init__(self, wallet)
PSKeystoreMixin.__init__(self, wallet)
KeyPairsMixin.__init__(self, wallet)
PSOptsMixin.__init__(self, wallet)
PSUtilsMixin.__init__(self, wallet)
self.log_handler = PSGUILogHandler(self)
self.logger = PSManLogAdapter(self.logger, {'psman_id': id(self)})
self.state_lock = threading.Lock()
self.states = s = PSStates
self.mixing_running_states = [s.StartMixing, s.Mixing, s.StopMixing]
self.no_clean_history_states = [s.Initializing, s.Errored,
s.StartMixing, s.Mixing, s.StopMixing,
s.FindingUntracked]
self.config = wallet.config
self._state = PSStates.Unsupported
self.wallet_types_supported = ['standard']
self.keystore_types_supported = ['bip32', 'hardware']
keystore = wallet.db.get('keystore')
if keystore:
self.w_ks_type = keystore.get('type', 'unknown')
else:
self.w_ks_type = 'unknown'
self.w_type = wallet.wallet_type
if (self.w_type in self.wallet_types_supported
and self.w_ks_type in self.keystore_types_supported):
if wallet.db.get_ps_data('ps_enabled', False):
self.state = PSStates.Initializing
else:
self.state = PSStates.Disabled
if self.unsupported:
supported_w = ', '.join(self.wallet_types_supported)
supported_ks = ', '.join(self.keystore_types_supported)
this_type = self.w_type
this_ks_type = self.w_ks_type
self.unsupported_msg = _(f'PrivateSend is currently supported on'
f' next wallet types: "{supported_w}"'
f' and keystore types: "{supported_ks}".'
f'\n\nThis wallet has type "{this_type}"'
f' and kestore type "{this_ks_type}".')
else:
self.unsupported_msg = ''
self.ps_keystore_has_history = False
if self.is_hw_ks:
self.enable_ps_keystore()
self.network = None
self.dash_net = None
self.loop = None
self.main_taskgroup = None
self.mix_sessions_lock = asyncio.Lock()
self.mix_sessions = {} # dict peer -> PSMixSession
self.recent_mixes_mns = deque([], 10) # added from mixing sessions
self.denoms_lock = threading.Lock()
self.collateral_lock = threading.Lock()
self.others_lock = threading.Lock()
self.new_denoms_wfl_lock = threading.Lock()
self.new_collateral_wfl_lock = threading.Lock()
self.pay_collateral_wfl_lock = threading.Lock()
self.denominate_wfl_lock = threading.Lock()
self._not_enough_funds = False
# electrum network disconnect time
self.disconnect_time = 0
@property
def unsupported(self):
'''Wallet and keystore types is not supported'''
return self.state == PSStates.Unsupported
@property
def enabled(self):
'''PS was enabled on this wallet'''
return self.state not in [PSStates.Unsupported, PSStates.Disabled]
@property
def is_hw_ks(self):
'''Wallet has hardware keystore type'''
return self.w_ks_type == 'hardware'
def enable_ps(self):
'''Enables PS on this wallet, store changes in db.
For hardware wallets PS Keystore must be created first'''
if (self.w_type == 'standard' and self.is_hw_ks
and 'ps_keystore' not in self.wallet.db.data):
self.logger.info('ps_keystore for hw wallets must be created')
return
if not self.enabled:
self.wallet.db.set_ps_data('ps_enabled', True)
coro = self._enable_ps()
asyncio.run_coroutine_threadsafe(coro, self.loop)
async def _enable_ps(self):
'''Start initialization, enable PS Keystore, find untracked txs'''
if self.enabled:
return
self.state = PSStates.Initializing
util.trigger_callback('ps-state-changes', self.wallet, None, None)
_load_and_cleanup = self.load_and_cleanup
await self.loop.run_in_executor(None, _load_and_cleanup)
await self.find_untracked_ps_txs()
self.wallet.save_db()
def can_find_untracked(self):
'''find untracked txs should run on synchronized wallet'''
w = self.wallet
network = self.network
if network is None:
return False
server_height = network.get_server_height()
if server_height == 0:
return False
local_height = network.get_local_height()
if local_height < server_height:
return False
with w.lock:
unverified_no_islock = []
for txid in w.unverified_tx:
if txid not in w.db.islocks:
unverified_no_islock.append(txid)
if (unverified_no_islock
or not w.is_up_to_date()
or not w.synchronizer.is_up_to_date()):
return False
return True
@property
def state(self):
'''Current state of PSManager (dash_ps_util.PSStates enum)'''
return self._state
@property
def is_waiting(self):
'''Mixing is running but no active workflows are found'''
if self.state not in self.mixing_running_states:
return False
if self.keypairs_state in [KPStates.NeedCache, KPStates.Caching]:
return False
active_wfls_cnt = 0
active_wfls_cnt += len(self.denominate_wfl_list)
if self.new_denoms_wfl:
active_wfls_cnt += 1
if self.new_collateral_wfl:
active_wfls_cnt += 1
return (active_wfls_cnt == 0)
@state.setter
def state(self, state):
'''Set current state of PSManager'''
self._state = state
def on_network_start(self, network):
'''Run when network is connected to the wallet'''
self.network = network
util.register_callback(self.on_wallet_updated, ['wallet_updated'])
util.register_callback(self.on_network_status, ['status'])
self.dash_net = network.dash_net
self.loop = network.asyncio_loop
asyncio.ensure_future(self.clean_keypairs_on_timeout())
asyncio.ensure_future(self.cleanup_staled_denominate_wfls())
asyncio.ensure_future(self.trigger_postponed_notifications())
def on_stop_threads(self):
'''Run when the wallet is unloaded/stopped'''
if self.state == PSStates.Mixing:
self.stop_mixing()
util.unregister_callback(self.on_wallet_updated)
util.unregister_callback(self.on_network_status)
def on_network_status(self, event, *args):
'''Monitor if electrum network is disconnected and then stop mixing.'''
connected = self.network.is_connected()
if connected:
self.disconnect_time = 0
else:
now = time.time()
if self.disconnect_time == 0:
self.disconnect_time = now
if now - self.disconnect_time > 30: # disconnected for 30 seconds
if self.state == PSStates.Mixing:
self.stop_mixing(self.NO_NETWORK_STOP_MSG)
async def on_wallet_updated(self, event, *args):
'''Run when wallet/synchronizer's is_up_to_date state changed'''
if not self.enabled:
return
w = args[0]
if w != self.wallet:
return
if w.is_up_to_date():
self._not_enough_funds = False
if self.state in [PSStates.Initializing, PSStates.Ready]:
await self.find_untracked_ps_txs()
# Methods related to mixing process
def start_mixing(self, password, nowait=True):
'''Start mixing from GUI'''
w = self.wallet
msg = None
if w.is_watching_only():
msg = self.WATCHING_ONLY_MSG, 'err'
elif self.all_mixed:
msg = self.ALL_MIXED_MSG, 'inf'
elif not self.network or not self.network.is_connected():
msg = self.NO_NETWORK_MSG, 'err'
elif not self.dash_net.run_dash_net:
msg = self.NO_DASH_NET_MSG, 'err'
if msg:
msg, inf = msg
self.logger.info(f'Can not start PrivateSend Mixing: {msg}')
util.trigger_callback('ps-state-changes', w, msg, inf)
return
coro = self.find_untracked_ps_txs()
asyncio.run_coroutine_threadsafe(coro, self.loop).result()
with self.state_lock:
if self.state == PSStates.Ready:
self.state = PSStates.StartMixing
elif self.state in [PSStates.Unsupported, PSStates.Disabled]:
msg = self.NOT_ENABLED_MSG
elif self.state == PSStates.Initializing:
msg = self.INITIALIZING_MSG
elif self.state in self.mixing_running_states:
msg = self.MIXING_ALREADY_RUNNING_MSG
elif self.state == PSStates.FindingUntracked:
msg = self.FIND_UNTRACKED_RUN_MSG
elif self.state == PSStates.FindingUntracked:
msg = self.ERRORED_MSG
else:
msg = self.UNKNOWN_STATE_MSG.format(self.state)
if msg:
util.trigger_callback('ps-state-changes', w, msg, None)
self.logger.info(f'Can not start PrivateSend Mixing: {msg}')
return
else:
util.trigger_callback('ps-state-changes', w, None, None)
fut = asyncio.run_coroutine_threadsafe(self._start_mixing(password),
self.loop)
if nowait:
return
try:
fut.result(timeout=2)
except (asyncio.TimeoutError, asyncio.CancelledError):
pass
async def _start_mixing(self, password):
if not self.enabled or not self.network:
return
assert not self.main_taskgroup
self._not_enough_funds = False
self.main_taskgroup = main_taskgroup = SilentTaskGroup()
self.logger.info('Starting PrivateSend Mixing')
async def main():
try:
async with main_taskgroup as group:
if (self.w_type == 'standard'
and self.is_hw_ks):
await group.spawn(self._prepare_funds_from_hw_wallet())
await group.spawn(self._make_keypairs_cache(password))
await group.spawn(self._check_not_enough_funds())
await group.spawn(self._check_all_mixed())
await group.spawn(self._maintain_pay_collateral_tx())
await group.spawn(self._maintain_collateral_amount())
await group.spawn(self._maintain_denoms())
await group.spawn(self._mix_denoms())
except Exception as e:
self.logger.info(f'error starting mixing: {str(e)}')
raise e
asyncio.run_coroutine_threadsafe(main(), self.loop)
with self.state_lock:
self.state = PSStates.Mixing
self.last_mix_start_time = time.time()
self.logger.info('Started PrivateSend Mixing')
w = self.wallet
util.trigger_callback('ps-state-changes', w, None, None)
async def stop_mixing_from_async_thread(self, msg, msg_type=None):
'''Stop mixing programmatically'''
await self.loop.run_in_executor(None, self.stop_mixing, msg, msg_type)
def stop_mixing(self, msg=None, msg_type=None, nowait=True):
'''Stop mixing from GUI'''
w = self.wallet
with self.state_lock:
if self.state == PSStates.Mixing:
self.state = PSStates.StopMixing
elif self.state == PSStates.StopMixing:
return
else:
msg = self.MIXING_NOT_RUNNING_MSG
util.trigger_callback('ps-state-changes', w, msg, 'inf')
self.logger.info(f'Can not stop PrivateSend Mixing: {msg}')
return
if msg:
self.logger.info(f'Stopping PrivateSend Mixing: {msg}')
if not msg_type or not msg_type.startswith('inf'):
stopped_prefix = _('PrivateSend mixing is stopping!')
msg = f'{stopped_prefix}\n\n{msg}'
util.trigger_callback('ps-state-changes', w, msg, msg_type)
else:
self.logger.info('Stopping PrivateSend Mixing')
util.trigger_callback('ps-state-changes', w, None, None)
self.last_mix_stop_time = time.time() # write early if later time lost
fut = asyncio.run_coroutine_threadsafe(self._stop_mixing(), self.loop)
if nowait:
return
try:
fut.result(timeout=PRIVATESEND_SESSION_MSG_TIMEOUT+5)
except (asyncio.TimeoutError, asyncio.CancelledError):
pass
@log_exceptions
async def _stop_mixing(self):
'''Async part of stop_mixing'''
if self.keypairs_state == KPStates.Caching:
self.logger.info('Waiting for keypairs caching to finish')
while self.keypairs_state == KPStates.Caching:
await asyncio.sleep(0.5)
if self.main_taskgroup:
sess_cnt = len(self.mix_sessions)
if sess_cnt > 0:
self.logger.info(f'Waiting for {sess_cnt}'
f' mixing sessions to finish')
while sess_cnt > 0:
await asyncio.sleep(0.5)
sess_cnt = len(self.mix_sessions)
try:
await asyncio.wait_for(self.main_taskgroup.cancel_remaining(),
timeout=2)
except (asyncio.TimeoutError, asyncio.CancelledError) as e:
self.logger.debug(f'Exception during main_taskgroup'
f' cancellation: {repr(e)}')
self.main_taskgroup = None
with self.keypairs_state_lock:
if self.keypairs_state == KPStates.Ready:
self.logger.info('Mark keypairs as unused')
self.keypairs_state = KPStates.Unused
self.logger.info('Stopped PrivateSend Mixing')
self.last_mix_stop_time = time.time()
with self.state_lock:
self.state = PSStates.Ready
w = self.wallet
util.trigger_callback('ps-state-changes', w, None, None)
async def _check_all_mixed(self):
'''Async task to check all_mixed and stop if done'''
while not self.main_taskgroup.closed():
await asyncio.sleep(10)
if self.all_mixed:
await self.stop_mixing_from_async_thread(self.ALL_MIXED_MSG,
'inf')
async def _check_not_enough_funds(self):
'''Async task to reset _not_enough_funds condition after 30 secs'''
while not self.main_taskgroup.closed():
if self._not_enough_funds:
await asyncio.sleep(30)
self._not_enough_funds = False
await asyncio.sleep(5)
async def _maintain_pay_collateral_tx(self):
'''Async task to maintain actual pay collateral tx'''
kp_wait_state = KPStates.Ready if self.need_password() else None
while not self.main_taskgroup.closed():
wfl = self.pay_collateral_wfl
if wfl:
if not wfl.completed or not wfl.tx_order:
await self.cleanup_pay_collateral_wfl()
elif self.ps_collateral_cnt > 0:
if kp_wait_state and self.keypairs_state != kp_wait_state:
self.logger.info('Pay collateral workflow waiting'
' for keypairs generation')
await asyncio.sleep(5)
continue
if not self.get_confirmed_ps_collateral_data():
await asyncio.sleep(5)
continue
await self.prepare_pay_collateral_wfl()
await asyncio.sleep(0.25)
async def _maintain_collateral_amount(self):
'''Async task to maintain available collateral coins'''
w = self.wallet
kp_wait_state = KPStates.Ready if self.need_password() else None
while not self.main_taskgroup.closed():
wfl = self.new_collateral_wfl
if wfl:
if not wfl.completed or not wfl.tx_order:
await self.cleanup_new_collateral_wfl()
elif wfl.next_to_send(w):
await self.broadcast_new_collateral_wfl()
else:
for txid in wfl.tx_order:
tx = Transaction(wfl.tx_data[txid].raw_tx)
self._process_by_new_collateral_wfl(txid, tx)
elif (not self._not_enough_funds
and not self.ps_collateral_cnt
and not self.calc_need_denoms_amounts(use_cache=True)):
coins = await self.get_next_coins_for_mixing(for_denoms=False)
if not coins:
await asyncio.sleep(5)
continue
if not self.check_llmq_ready():
self.logger.info(_('New collateral workflow: {}')
.format(self.LLMQ_DATA_NOT_READY))
await asyncio.sleep(5)
continue
elif kp_wait_state and self.keypairs_state != kp_wait_state:
self.logger.info('New collateral workflow waiting'
' for keypairs generation')
await asyncio.sleep(5)
continue
await self.create_new_collateral_wfl()
await asyncio.sleep(0.25)
async def _maintain_denoms(self):
'''Async task which makes new denoms available for mixing'''
w = self.wallet
kp_wait_state = KPStates.Ready if self.need_password() else None
while not self.main_taskgroup.closed():
wfl = self.new_denoms_wfl
if wfl:
if not wfl.completed or not wfl.tx_order:
await self.cleanup_new_denoms_wfl()
elif wfl.next_to_send(w):
await self.broadcast_new_denoms_wfl()
else:
for txid in wfl.tx_order:
tx = Transaction(wfl.tx_data[txid].raw_tx)
self._process_by_new_denoms_wfl(txid, tx)
elif (not self._not_enough_funds
and self.calc_need_denoms_amounts(use_cache=True)):
coins = await self.get_next_coins_for_mixing()
if not coins:
await asyncio.sleep(5)
continue
if not self.check_llmq_ready():
self.logger.info(_('New denoms workflow: {}')
.format(self.LLMQ_DATA_NOT_READY))
await asyncio.sleep(5)
continue
elif kp_wait_state and self.keypairs_state != kp_wait_state:
self.logger.info('New denoms workflow waiting'
' for keypairs generation')
await asyncio.sleep(5)
continue
await self.create_new_denoms_wfl()
await asyncio.sleep(0.25)
async def _mix_denoms(self):
'''Async task which maintains mixing process'''
kp_wait_state = KPStates.Ready if self.need_password() else None
def _cleanup():
for uuid in self.denominate_wfl_list:
wfl = self.get_denominate_wfl(uuid)
if wfl and not wfl.completed:
self._cleanup_denominate_wfl(wfl)
await self.loop.run_in_executor(None, _cleanup)
main_taskgroup = self.main_taskgroup
while not main_taskgroup.closed():
if (self._denoms_to_mix_cache
and self.pay_collateral_wfl
and self.active_denominate_wfl_cnt < self.max_sessions):
if not self.check_llmq_ready():
self.logger.info(_('Denominate workflow: {}')
.format(self.LLMQ_DATA_NOT_READY))
await asyncio.sleep(5)
continue
elif not self.check_protx_info_completeness():
self.logger.info(_('Denominate workflow: {}')
.format(self.MNS_DATA_NOT_READY))
await asyncio.sleep(5)
continue
elif kp_wait_state and self.keypairs_state != kp_wait_state:
self.logger.info('Denominate workflow waiting'
' for keypairs generation')
await asyncio.sleep(5)
continue
if self.state == PSStates.Mixing:
await main_taskgroup.spawn(self.start_denominate_wfl())
await asyncio.sleep(0.25)
async def start_mix_session(self, denom_value, dsq, wfl_lid):
'''Start mixing session on MN from dsq in wfl identified by wfl_lid'''
n_denom = PS_DENOMS_DICT[denom_value]
sess = PSMixSession(self, denom_value, n_denom, dsq, wfl_lid)
peer_str = sess.peer_str
async with self.mix_sessions_lock:
if peer_str in self.mix_sessions:
raise Exception(f'Session with {peer_str} already exists')
await sess.run_peer()
self.mix_sessions[peer_str] = sess
return sess
async def stop_mix_session(self, peer_str):
'''Stop mixing session identified by "ip:port" peer string'''
async with self.mix_sessions_lock:
sess = self.mix_sessions.pop(peer_str)
if not sess:
self.logger.debug(f'Peer {peer_str} not found in mix_session')
return
sess.close_peer()
return sess
# Workflow methods for pay collateral transaction
def get_confirmed_ps_collateral_data(self):
'''Return one of many possible confirmed collateral utxo'''
w = self.wallet
for outpoint, ps_collateral in w.db.get_ps_collaterals().items():
addr, value = ps_collateral
utxos = w.get_utxos([addr], min_rounds=PSCoinRounds.COLLATERAL,
confirmed_funding_only=True,
consider_islocks=True)
utxos = self.filter_out_hw_ks_coins(utxos)
inputs = []
for utxo in utxos:
if utxo.prevout.to_str() != outpoint:
continue
w.add_input_info(utxo)
inputs.append(utxo)
if inputs:
return outpoint, value, inputs
else:
self.logger.wfl_err(f'ps_collateral outpoint {outpoint}'
f' is not confirmed')
async def prepare_pay_collateral_wfl(self):
'''Async prepare signed pay collateral tx in pay_collateral_wfl'''
try:
_prepare = self._prepare_pay_collateral_tx
res = await self.loop.run_in_executor(None, _prepare)
if res:
txid, wfl = res
self.logger.wfl_ok(f'Completed pay collateral workflow with'
f' tx: {txid}, workflow: {wfl.lid}')
self.wallet.save_db()
except Exception as e:
wfl = self.pay_collateral_wfl
if wfl:
self.logger.wfl_err(f'Error creating pay collateral tx:'
f' {str(e)}, workflow: {wfl.lid}')
await self.cleanup_pay_collateral_wfl(force=True)
else:
self.logger.wfl_err(f'Error during creation of pay collateral'
f' workflow: {str(e)}')
type_e = type(e)
msg = None
if type_e == NoDynamicFeeEstimates:
msg = self.NO_DYNAMIC_FEE_MSG.format(str(e))
elif type_e == NotFoundInKeypairs:
msg = self.NOT_FOUND_KEYS_MSG
elif type_e == SignWithKeypairsFailed:
msg = self.SIGN_WIHT_KP_FAILED_MSG
if msg:
await self.stop_mixing_from_async_thread(msg)
def _prepare_pay_collateral_tx(self):
'''Prepare pay collateral tx and save it to pay_collateral_wfl'''
with self.pay_collateral_wfl_lock:
if self.pay_collateral_wfl:
return
uuid = str(uuid4())
wfl = PSTxWorkflow(uuid=uuid)
self.set_pay_collateral_wfl(wfl)
self.logger.info(f'Started up pay collateral workflow: {wfl.lid}')
res = self.get_confirmed_ps_collateral_data()
if not res:
raise Exception('No confirmed ps_collateral found')
outpoint, value, inputs = res
# check input addresses is in keypairs if keypairs cache available
if self._keypairs_cache:
input_addrs = [utxo.address for utxo in inputs]
not_found_addrs = self._find_addrs_not_in_keypairs(input_addrs)
if not_found_addrs:
not_found_addrs = ', '.join(list(not_found_addrs))
raise NotFoundInKeypairs(f'Input addresses is not found'
f' in the keypairs cache:'
f' {not_found_addrs}')
self.add_ps_spending_collateral(outpoint, wfl.uuid)
if value >= COLLATERAL_VAL*2:
ovalue = value - COLLATERAL_VAL
output_addr = None
for addr, data in self.wallet.db.get_ps_reserved().items():
if data == outpoint:
output_addr = addr
break
if not output_addr:
reserved = self.reserve_addresses(1, for_change=True,
data=outpoint)
output_addr = reserved[0]
outputs = [PartialTxOutput.from_address_and_value(output_addr, ovalue)]
else:
# OP_RETURN as ouptut script
outputs = [PartialTxOutput(scriptpubkey=bfh('6a'), value=0)]
tx = PartialTransaction.from_io(inputs[:], outputs[:], locktime=0)
tx.inputs()[0].nsequence = 0xffffffff
tx = self.sign_transaction(tx, None)
txid = tx.txid()
raw_tx = tx.serialize_to_network()
tx_type = PSTxTypes.PAY_COLLATERAL
wfl.add_tx(txid=txid, raw_tx=raw_tx, tx_type=tx_type)
wfl.completed = True
with self.pay_collateral_wfl_lock:
saved = self.pay_collateral_wfl
if not saved:
raise Exception('pay_collateral_wfl not found')
if saved.uuid != wfl.uuid:
raise Exception('pay_collateral_wfl differs from original')
self.set_pay_collateral_wfl(wfl)
return txid, wfl
async def cleanup_pay_collateral_wfl(self, force=False):
'''Async cleanup of pay_collateral_wfl'''
_cleanup = self._cleanup_pay_collateral_wfl
changed = await self.loop.run_in_executor(None, _cleanup, force)
if changed:
self.wallet.save_db()
def _cleanup_pay_collateral_wfl(self, force=False):
'''Cleanup of pay_collateral_wfl'''
with self.pay_collateral_wfl_lock:
wfl = self.pay_collateral_wfl
if not wfl or wfl.completed and wfl.tx_order and not force:
return
w = self.wallet
if wfl.tx_order:
for txid in wfl.tx_order[::-1]: # use reversed tx_order
if w.db.get_transaction(txid):
w.remove_transaction(txid)
else:
self._cleanup_pay_collateral_wfl_tx_data(txid)
else:
self._cleanup_pay_collateral_wfl_tx_data()
return True
def _cleanup_pay_collateral_wfl_tx_data(self, txid=None):
'''Cleanup of pay_collateral_wfl tx and its db supplementary data'''
with self.pay_collateral_wfl_lock:
wfl = self.pay_collateral_wfl
if not wfl:
return
if txid:
tx_data = wfl.pop_tx(txid)
if tx_data:
self.set_pay_collateral_wfl(wfl)
self.logger.info(f'Cleaned up pay collateral tx:'
f' {txid}, workflow: {wfl.lid}')
if wfl.tx_order:
return
w = self.wallet
for outpoint, uuid in list(w.db.get_ps_spending_collaterals().items()):
if uuid != wfl.uuid:
continue
with self.collateral_lock:
self.pop_ps_spending_collateral(outpoint)
with self.pay_collateral_wfl_lock:
saved = self.pay_collateral_wfl
if saved and saved.uuid == wfl.uuid:
self.clear_pay_collateral_wfl()
self.logger.info(f'Cleaned up pay collateral workflow: {wfl.lid}')
def _search_pay_collateral_wfl(self, txid, tx):
'''Search available pay_collateral_wfl corresponding to txid/tx data'''
err = self._check_pay_collateral_tx_err(txid, tx, full_check=False)
if not err:
wfl = self.pay_collateral_wfl
if wfl and wfl.tx_order and txid in wfl.tx_order:
return wfl
def _check_on_pay_collateral_wfl(self, txid, tx):
'''Check it's pay collateral tx, corresponding to pay_collateral_wfl'''
wfl = self._search_pay_collateral_wfl(txid, tx)
err = self._check_pay_collateral_tx_err(txid, tx)
if not err:
return True
if wfl:
raise AddPSDataError(f'{err}')
else:
return False
def _process_by_pay_collateral_wfl(self, txid, tx):
'''Process tx by pay_collateral_wfl, cleanup wfl/supplementary data'''
wfl = self._search_pay_collateral_wfl(txid, tx)
if not wfl:
return
with self.pay_collateral_wfl_lock:
saved = self.pay_collateral_wfl
if not saved or saved.uuid != wfl.uuid:
return
tx_data = wfl.pop_tx(txid)
if tx_data:
self.set_pay_collateral_wfl(wfl)
self.logger.wfl_done(f'Processed tx: {txid} from pay'
f' collateral workflow: {wfl.lid}')
if wfl.tx_order:
return
w = self.wallet
for outpoint, uuid in list(w.db.get_ps_spending_collaterals().items()):
if uuid != wfl.uuid:
continue
with self.collateral_lock:
self.pop_ps_spending_collateral(outpoint)
with self.pay_collateral_wfl_lock:
saved = self.pay_collateral_wfl
if saved and saved.uuid == wfl.uuid:
self.clear_pay_collateral_wfl()
self.logger.wfl_done(f'Finished processing of pay collateral'
f' workflow: {wfl.lid}')
def get_pay_collateral_tx(self):
'''Get pay collateral tx prepared in pay_collateral_wfl'''
wfl = self.pay_collateral_wfl
if not wfl or not wfl.tx_order:
return
txid = wfl.tx_order[0]
tx_data = wfl.tx_data.get(txid)
if not tx_data:
return
return tx_data.raw_tx
# Workflow methods for new collateral transaction
def new_collateral_from_coins_info(self, coins):
'''Get info on new collateral wfl prepared from GUI'''
if not coins or len(coins) > 1:
return
coins_val = sum([c.value_sats() for c in coins])
if (coins_val >= self.min_new_denoms_from_coins_val
or coins_val < self.min_new_collateral_from_coins_val):
return
fee_per_kb = self.config.fee_per_kb()
for collateral_val in CREATE_COLLATERAL_VALS[::-1]:
new_collateral_fee = calc_tx_fee(1, 1, fee_per_kb, max_size=True)
if coins_val - new_collateral_fee >= collateral_val:
tx_type = SPEC_TX_NAMES[PSTxTypes.NEW_COLLATERAL]
info = _('Transactions type: {}').format(tx_type)
info += '\n'
info += _('Count of transactions: {}').format(1)
info += '\n'
info += _('Total sent amount: {}').format(coins_val)
info += '\n'
info += _('Total output amount: {}').format(collateral_val)
info += '\n'
info += _('Total fee: {}').format(coins_val - collateral_val)
return info
def create_new_collateral_wfl_from_gui(self, coins, password):
'''Create new collateral tx/wfl from PS coins from GUI'''
if self.state in self.mixing_running_states:
return None, ('Can not create new collateral as mixing'
' process is currently run.')
if len(coins) > 1:
return None, ('Can not create new collateral amount,'
' too many coins selected')
wfl = self._start_new_collateral_wfl()
if not wfl:
return None, ('Can not create new collateral as other new'
' collateral creation process is in progress')
try:
w = self.wallet
txid, tx = self._make_new_collateral_tx(wfl, coins, password)
if not w.add_transaction(tx):
raise Exception(f'Transaction with txid: {txid}'
f' conflicts with current history')
if not w.db.get_ps_tx(txid)[0] == PSTxTypes.NEW_COLLATERAL:
self._add_ps_data(txid, tx, PSTxTypes.NEW_COLLATERAL)
with self.new_collateral_wfl_lock:
saved = self.new_collateral_wfl
if not saved:
raise Exception('new_collateral_wfl not found')
if saved.uuid != wfl.uuid:
raise Exception('new_collateral_wfl differs from original')
wfl.completed = True
self.set_new_collateral_wfl(wfl)
self.logger.wfl_ok(f'Completed new collateral workflow'
f' with tx: {txid},'
f' workflow: {wfl.lid}')
return wfl, None
except Exception as e:
err = str(e)
self.logger.wfl_err(f'Error creating new collateral tx:'
f' {err}, workflow: {wfl.lid}')
self._cleanup_new_collateral_wfl(force=True)
self.logger.info(f'Cleaned up new collateral workflow:'
f' {wfl.lid}')
return None, err
async def create_new_collateral_wfl(self):
'''Create new collateral tx/wfl from async mixing task'''
coins_data = await self.get_next_coins_for_mixing(for_denoms=False)
coins = coins_data['coins']
_start = self._start_new_collateral_wfl
wfl = await self.loop.run_in_executor(None, _start)
if not wfl:
return
try:
_make_tx = self._make_new_collateral_tx
txid, tx = await self.loop.run_in_executor(None, _make_tx,
wfl, coins)
w = self.wallet
# add_transaction need run in network therad
if not w.add_transaction(tx):
raise Exception(f'Transaction with txid: {txid}'
f' conflicts with current history')
def _after_create_tx():
with self.new_collateral_wfl_lock:
saved = self.new_collateral_wfl
if not saved:
raise Exception('new_collateral_wfl not found')
if saved.uuid != wfl.uuid:
raise Exception('new_collateral_wfl differs'
' from original')
wfl.completed = True
self.set_new_collateral_wfl(wfl)
self.logger.wfl_ok(f'Completed new collateral workflow'
f' with tx: {txid},'
f' workflow: {wfl.lid}')
await self.loop.run_in_executor(None, _after_create_tx)
w.save_db()
except Exception as e:
self.logger.wfl_err(f'Error creating new collateral tx:'
f' {str(e)}, workflow: {wfl.lid}')
await self.cleanup_new_collateral_wfl(force=True)
type_e = type(e)
msg = None
if type_e == NoDynamicFeeEstimates:
msg = self.NO_DYNAMIC_FEE_MSG.format(str(e))
elif type_e == AddPSDataError:
msg = self.ADD_PS_DATA_ERR_MSG
type_name = SPEC_TX_NAMES[PSTxTypes.NEW_COLLATERAL]
msg = f'{msg} {type_name} {txid}:\n{str(e)}'
elif type_e == NotFoundInKeypairs:
msg = self.NOT_FOUND_KEYS_MSG
elif type_e == SignWithKeypairsFailed:
msg = self.SIGN_WIHT_KP_FAILED_MSG
elif type_e == NotEnoughFunds:
self._not_enough_funds = True
if msg:
await self.stop_mixing_from_async_thread(msg)
def _start_new_collateral_wfl(self):
'''Start new_collateral_wfl with appropriate locking'''
with self.new_collateral_wfl_lock:
if self.new_collateral_wfl:
return
uuid = str(uuid4())
wfl = PSTxWorkflow(uuid=uuid)
self.set_new_collateral_wfl(wfl)
self.logger.info(f'Started up new collateral workflow: {wfl.lid}')
return self.new_collateral_wfl
def _make_new_collateral_tx(self, wfl, coins=None, password=None):
'''Make signed new collateral tx and save it to new_collateral_wfl'''
with self.new_collateral_wfl_lock:
saved = self.new_collateral_wfl
if not saved:
raise Exception('new_collateral_wfl not found')
if saved.uuid != wfl.uuid:
raise Exception('new_collateral_wfl differs from original')
w = self.wallet
fee_per_kb = self.config.fee_per_kb()
uuid = wfl.uuid
oaddr = self.reserve_addresses(1, data=uuid)[0]
if not coins:
# try select minimal denom utxo with mimial rounds
coins = w.get_utxos(None, mature_only=True,
confirmed_funding_only=True,
consider_islocks=True, min_rounds=0)
coins = [c for c in coins if c.value_sats() == MIN_DENOM_VAL]
coins = self.filter_out_hw_ks_coins(coins)
if not coins:
raise NotEnoughFunds()
coins = sorted(coins, key=lambda x: x.ps_rounds)