forked from The-Sycorax/DenaroWalletClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet_client.py
2607 lines (2211 loc) · 150 KB
/
wallet_client.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
import os
import json
import base64
import binascii
import logging
import argparse
import sys
import threading
import gc
import re
import time
import shutil
import requests
from datetime import datetime
from decimal import Decimal, ROUND_DOWN, ROUND_UP
from collections import Counter, OrderedDict
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
# Get the absolute path of the directory containing the current script.
dir_path = os.path.dirname(os.path.realpath(__file__))
# Insert folder paths for modules
sys.path.insert(0, dir_path + "/denaro")
sys.path.insert(0, dir_path + "/denaro/wallet")
sys.path.insert(0, dir_path + "/denaro/wallet/utils")
from denaro.wallet.utils.wallet_generation_util import generate, generate_from_private_key, string_to_point, sha256, is_valid_mnemonic
from denaro.wallet.utils.cryptographic_util import EncryptDecryptUtils, TOTP
from denaro.wallet.utils.verification_util import Verification
from denaro.wallet.utils.data_manipulation_util import DataManipulation
from denaro.wallet.utils.interface_util import QRCodeUtils, UserPrompts
from denaro.wallet.utils.transaction_utils.transaction_input import TransactionInput
from denaro.wallet.utils.transaction_utils.transaction_output import TransactionOutput
from denaro.wallet.utils.transaction_utils.transaction import Transaction
from denaro.wallet.utils.paper_wallet_util import PaperWalletGenerator
is_windows = os.name == 'nt'
if is_windows:
import msvcrt
else:
import termios, fcntl, readline
# Get the root logger
root_logger = logging.getLogger()
# Set the level for the root logger
root_logger.setLevel(logging.INFO if '-verbose' in sys.argv else logging.WARNING)
# Create a handler with the desired format
handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s: %(message)s')
handler.setFormatter(formatter)
# Clear any existing handlers from the root logger and add our handler
root_logger.handlers = []
root_logger.addHandler(handler)
# Filesystem Functions
def is_wallet_encrypted(data_segment):
"""
Determines if a given segment of data appears to be encrypted.
"""
# Try to decode the data as JSON.
try:
parsed_data = json.loads(data_segment)
encrypted_indicators = ["hmac", "hmac_salt", "verification_salt", "verifier", "totp_secret"]
# If any of the encrypted indicators are found, it seems encrypted.
if any(key in parsed_data for key in encrypted_indicators):
return True
return False # Data doesn't have encryption indicators, so it doesn't seem encrypted
except json.JSONDecodeError:
pass
# If the above check fails, try to decode the data as base64 and then as UTF-8.
try:
decoded_base64 = base64.b64decode(data_segment)
decoded_base64.decode('utf-8') # Check if the decoded result can be further decoded as UTF-8
return True # Data seems encrypted as it's valid Base64 and can be decoded as UTF-8
except (binascii.Error, UnicodeDecodeError):
return False # Data neither seems to be valid JSON nor valid Base64 encoded UTF-8 text
def ensure_wallet_directories_exist(custom = None):
"""
Ensures the "./wallets" and "./wallets/wallet_backups" directories exist
Will create a custom directory if specified.
"""
os.makedirs("./wallets", exist_ok=True)
os.makedirs(os.path.join("./wallets", 'wallet_backups'), exist_ok=True)
if custom:
os.makedirs(custom, exist_ok=True)
def get_normalized_filepath(filename):
"""
Gets a normalized file path, ensuring the directory exists.
Parameters:
filename (str): The name of the file where the data will be saved.
default_directory (str): The default directory where files will be saved if no directory is specified.
Returns:
str: A normalized filepath.
"""
default_directory="./wallets"
# Ensure the filename has a .json extension
_, file_extension = os.path.splitext(filename)
# Add .json extention to the filename if it's not present
if file_extension.lower() != ".json":
filename += ".json"
# Check if the directory part is already specified in the filename
# If not, prepend the default directory to the filename
if not os.path.dirname(filename):
filename = os.path.join(default_directory, filename)
# Normalize the path to handle ".." or "." segments
normalized_filepath = os.path.normpath(filename)
# Ensure the directory to save the file in exists
file_directory = os.path.dirname(normalized_filepath)
if not os.path.exists(file_directory):
os.makedirs(file_directory)
return normalized_filepath
def _load_data(filename, new_wallet):
"""
Loads wallet data from a specified file.
Checks if wallet file exists.
"""
try:
with open(filename, 'r') as f:
data = json.load(f)
return data, True
except (FileNotFoundError, json.JSONDecodeError) as e:
if new_wallet:
return {}, False
else:
logging.error(f"Unable to read the wallet file or parse its content:\n{str(e)}")
return None, False
# Wallet Helper Functions
def generate_encrypted_wallet_data(wallet_data, current_data, password, totp_secret, hmac_salt, verification_salt, stored_verifier, is_import=False):
"""Overview:
The `generate_encrypted_wallet_data` function serves as a utility for constructing a fully encrypted representation
of the wallet's data. It works by individually encrypting fields like private keys or mnemonics and then organizing
them in a predefined format. This function is vital in ensuring that sensitive wallet components remain confidential.
Parameters:
- wallet_data (dict): Contains essential wallet information like private keys or mnemonics.
- current_data (dict): Existing wallet data, utilized to determine the next suitable ID for the entry.
- password (str): The user's password, used for the encryption process.
- totp_secret (str): The TOTP secret token used for Two-Factor Authentication.
- hmac_salt (bytes): Salt for HMAC computation.
- verification_salt (bytes): Salt for password verification.
- stored_verifier (bytes): The stored hash of the password, used for verification.
Returns:
- dict: A structured dictionary containing the encrypted wallet data.
"""
# Encrypt the wallet's private key
encrypted_wallet_data = {
"id": EncryptDecryptUtils.encrypt_data(str(len(current_data["wallet_data"]["entry_data"]["entries"] if not is_import else current_data["wallet_data"]["entry_data"]["imported_entries"]) + 1), password, totp_secret, hmac_salt, verification_salt, stored_verifier),
"private_key": EncryptDecryptUtils.encrypt_data(wallet_data['private_key'], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
}
# If the wallet is non-deterministic, encrypt the mnemonic
if current_data["wallet_data"]["wallet_type"] == "non-deterministic" and not is_import:
encrypted_wallet_data["mnemonic"] = EncryptDecryptUtils.encrypt_data(wallet_data['mnemonic'], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
del encrypted_wallet_data["private_key"]
# Ensure a specific order for the keys
desired_key_order = ["id", "mnemonic"]
ordered_entry = OrderedDict((k, encrypted_wallet_data[k]) for k in desired_key_order if k in encrypted_wallet_data)
encrypted_wallet_data = ordered_entry
result = encrypted_wallet_data
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def generate_unencrypted_wallet_data(wallet_data, current_data, is_import=False):
"""Overview:
Contrasting its encrypted counterpart, the `generate_unencrypted_wallet_data` function focuses on constructing
plaintext wallet data entries. While it doesn't encrypt data, it organizes the it in a structured manner, ensuring
easy storage and retrieval. This function is pivotal in scenarios where encryption isn't mandated, but structured
data organization is requisite.
Parameters:
- wallet_data (dict): The unencrypted wallet data.
- current_data (dict): Existing wallet data, utilized to determine the next suitable ID for the entry.
Returns:
- dict: A structured dictionary containing the plaintext wallet data.
"""
# Structure the data without encryption
unencrypted_wallet_data = {
"id": str(len(current_data["wallet_data"]["entry_data"]["entries"] if not is_import else current_data["wallet_data"]["entry_data"]["imported_entries"]) + 1),
"private_key": wallet_data['private_key'],
"public_key": wallet_data['public_key'],
"address": wallet_data['address']
}
# For non-deterministic wallets, include the mnemonic
if current_data["wallet_data"]["wallet_type"] == "non-deterministic" and not is_import:
unencrypted_wallet_data["mnemonic"] = wallet_data['mnemonic']
# Ensure a specific order for the keys
desired_key_order = ["id", "mnemonic", "private_key", "public_key", "address"]
ordered_entry = OrderedDict((k, unencrypted_wallet_data[k]) for k in desired_key_order if k in unencrypted_wallet_data)
unencrypted_wallet_data = ordered_entry
result = unencrypted_wallet_data
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def handle_new_encrypted_wallet(password, totp_code, use2FA, filename, deterministic):
"""Overview:
The `handle_new_encrypted_wallet` function facilitates the creation of a new encrypted wallet. It handles the
combination of user-provided credentials, cryptographic salts, and the option for Two-Factor Authentication (2FA)
to produce a secure and accessible wallet. The function can adapt to both deterministic and non-deterministic
wallet types based on user preference.
Parameters:
- password (str): The user's password intended for the encrypted wallet.
- totp_code (str): Time-based One-Time Password for Two-Factor Authentication.
- use2FA (bool): Indicates whether Two-Factor Authentication is enabled or not.
- filename (str): The intended filename for storing the wallet data.
- deterministic (bool): Specifies if the wallet is deterministic
Returns:
- tuple: Returns a tuple that encapsulates the wallet's structured data alongside essential cryptographic
components like salts and verifiers.
"""
# Define the initial structure for the wallet data
data = {
"wallet_data": {
"wallet_type": "deterministic" if deterministic else "non-deterministic",
"version": "0.2.2",
"entry_data": {
"key_data": [],
"entries": []
},
"hmac": "",
"hmac_salt": "",
"verification_salt": "",
"verifier": "",
"totp_secret": ""
}
}
# Check if deterministic and adjust the data structure accordingly
if not deterministic:
del data["wallet_data"]["entry_data"]["key_data"]
# Password is mandatory for encrypted wallets
if not password:
logging.error("Password is required for encrypted wallets.\n")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None, None
# Generate random salts for HMAC and password verification
hmac_salt = os.urandom(16)
data["wallet_data"]["hmac_salt"] = base64.b64encode(hmac_salt).decode()
verification_salt = os.urandom(16)
data["wallet_data"]["verification_salt"] = base64.b64encode(verification_salt).decode()
# Hash the password with the salt for verification
verifier = Verification.hash_password(password, verification_salt)
data["wallet_data"]["verifier"] = base64.b64encode(verifier).decode('utf-8')
# If no TOTP code is provided, set it to an empty string
if not totp_code:
totp_code = ""
# Handle Two-Factor Authentication (2FA) setup if enabled
if use2FA:
#global close_qr_window
# Generate a secret for TOTP
totp_secret = TOTP.generate_totp_secret(False,verification_salt)
totp_qr_data = f'otpauth://totp/{filename}?secret={totp_secret}&issuer=Denaro Wallet Client'
# Generate a QR code for the TOTP secret
qr_img = QRCodeUtils.generate_qr_with_logo(totp_qr_data, "./denaro/wallet/denaro_logo.png")
# Threading is used to show the QR window to the user while allowing input in the temrinal
thread = threading.Thread(target=QRCodeUtils.show_qr_with_timer, args=(qr_img, filename, totp_secret,))
thread.start()
# Encrypt the TOTP secret for storage
encrypted_totp_secret = EncryptDecryptUtils.encrypt_data(totp_secret, password, "", hmac_salt, verification_salt, verifier)
data["wallet_data"]["totp_secret"] = encrypted_totp_secret
# Validate the TOTP setup
if not UserPrompts.handle_2fa_validation(totp_secret, totp_code):
QRCodeUtils.close_qr_window(True)
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None, None
else:
QRCodeUtils.close_qr_window(True)
thread.join()
else:
# If 2FA is not used, generate a predictable TOTP secret based on the verification salt.
totp_secret = TOTP.generate_totp_secret(True,verification_salt)
encrypted_totp_secret = EncryptDecryptUtils.encrypt_data(totp_secret, password, "", hmac_salt, verification_salt, verifier)
data["wallet_data"]["totp_secret"] = encrypted_totp_secret
totp_secret = ""
result = data, totp_secret, hmac_salt, verification_salt, verifier
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def handle_existing_encrypted_wallet(filename, data, password, totp_code, deterministic):
"""Overview:
The `handle_existing_encrypted_wallet` function verifies access to an encrypted wallet by checking the provided password
and decoding HMAC and verification salts from the wallet data. It conducts verification of the user's password against the
stored verifier and the HMAC to ensure data integrity. If password verification fails, it updates the number of failed password
attempts assocated with the wallet, it then logs an error for authentication failure or data corruption. For wallets with Two-Factor
Authentication, it additionally manages TOTP verification. Upon successful verifications, it returns cryptographic components such as
HMAC salt, verification salt, stored verifier, and TOTP secret.
Parameters:
- filename: The name of the wallet file
- data: The wallet data
- password: The user's password
- totp_code: The TOTP code for 2FA
- deterministic: Boolean indicating if the wallet is deterministic
Returns:
- A tuple containing HMAC salt, verification salt, stored verifier, and TOTP secret
"""
# Fail if no password is provided for an encrypted wallet
if not password:
logging.error("Password is required for encrypted wallets.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None
# Decode salts for verification
verification_salt = base64.b64decode(data["wallet_data"]["verification_salt"])
hmac_salt = base64.b64decode(data["wallet_data"]["hmac_salt"])
# Verify the password and HMAC
password_verified, hmac_verified, stored_verifier = Verification.verify_password_and_hmac(data, password, hmac_salt, verification_salt, deterministic)
# Based on password verification, update or reset the number of failed attempts
data = DataManipulation.update_or_reset_attempts(data, filename, hmac_salt, password_verified, deterministic)
if data is None:
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None
else:
DataManipulation._save_data(filename,data)
# Verify the password and HMAC
password_verified, hmac_verified, stored_verifier = Verification.verify_password_and_hmac(data, password, hmac_salt, verification_salt, deterministic)
# Fail if either the password or HMAC verification failed
if not (password_verified and hmac_verified):
logging.error("Authentication failed or wallet data is corrupted.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None
# If 2FA is enabled, handle the TOTP validation
totp_secret, tfa_enabled = Verification.verify_totp_secret(password, data["wallet_data"]["totp_secret"], hmac_salt, verification_salt, stored_verifier)
if tfa_enabled:
tfa_valid = UserPrompts.handle_2fa_validation(totp_secret, totp_code)
if not tfa_valid or not tfa_valid.get("valid"):
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None, None, None, None
result = hmac_salt, verification_salt, stored_verifier, totp_secret
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def parse_and_encrypt_mnemonic(words, password, totp_secret, hmac_salt, verification_salt, stored_verifier):
"""Overview:
The `parse_and_encrypt_mnemonic` function is specifically designed to fortify the security of mnemonic phrases.
It takes a string of mnemonic words, parses them, and encrypts each word individually. The function ensures
that each mnemonic word is securely encrypted, thereby enhancing the security of the mnemonic while protecting
against potential threats. This heightened level of security is crucial given the critical nature of mnemonics
in digital wallets.
Parameters:
- words (str): The mnemonic phrase.
- password (str): The user's password, used for the encryption process.
- totp_secret (str): The TOTP secret token used for Two-Factor Authentication.
- hmac_salt (bytes): Salt for HMAC generation.
- verification_salt (bytes): Salt for password verification.
- stored_verifier (bytes): The stored hash of the password, used for verification.
Returns:
- list: A list encapsulating the encrypted representations of each mnemonic word.
"""
# Split the mnemonic words by space
word_list = words.split()
# Ensure there are exactly 12 words in the mnemonic (standard mnemonic length)
if len(word_list) != 12:
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
raise ValueError("Input should contain exactly 12 words")
# Encrypt each word, and structure it in a dictionary with its ID
encrypted_key_data = [
EncryptDecryptUtils.encrypt_data(
json.dumps({
"id": EncryptDecryptUtils.encrypt_data(str(i+1), password, totp_secret, hmac_salt, verification_salt, stored_verifier),
"word": EncryptDecryptUtils.encrypt_data(word, password, totp_secret, hmac_salt, verification_salt, stored_verifier)
}),
password, totp_secret, hmac_salt, verification_salt, stored_verifier
) for i, word in enumerate(word_list)
]
result = encrypted_key_data
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def decrypt_and_parse_mnemonic(encrypted_json, password, totp_secret, hmac_salt, verification_salt, stored_verifier):
"""Overview:
Serving as the counterpart to `parse_and_encrypt_mnemonic`, this function plays an instrumental role in
key recovery operations. This function undertakes the task of decrypting each encrypted mnemonic word and
assembling them back into their original, readable sequence.
Parameters:
- encrypted_json (list): A list containing encrypted mnemonic words.
- password (str): The user's password, used for the decryption process.
- totp_secret (str): The TOTP secret token used for Two-Factor Authentication.
- hmac_salt (bytes): Salt for HMAC computation.
- verification_salt (bytes): Salt for password verification.
- stored_verifier (bytes): The stored hash of the password, used for verification.
Returns:
- str: A string containing the decrypted sequence of mnemonic words.
"""
decrypted_words = [
EncryptDecryptUtils.decrypt_data(
json.loads(EncryptDecryptUtils.decrypt_data(encrypted_index, password, totp_secret, hmac_salt, verification_salt, stored_verifier))["word"],
password, totp_secret, hmac_salt, verification_salt, stored_verifier
) for encrypted_index in encrypted_json
]
result = " ".join(decrypted_words)
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
# Wallet Orchestrator Functions
def generateAddressHelper(filename, password, totp_code=None, new_wallet=False, encrypt=False, use2FA=False, deterministic=False,backup=None,disable_warning=False,overwrite_password=None, amount=1, private_key=None, is_import=False, mnemonic=None):
"""Overview:
The `generateAddressHelper` function serves as a central orchestrator for facilitating the creation,
integration, and management of wallet data. This function is designed to accomodate different scenarios
for the generation and oversight of wallet addresses depending on the provided parameters. This function
can generate addresses for a new wallet or add addresses to an existing wallet. When considering address
generation, it can operate in a deterministic fashion, deriving addresses from a mnemonic phrase, or in a
non-deterministic manner, generating addresses at random.
When working with existing wallets, the function verifies if the wallet data is encrypted, if a password
is provided, and determines the method of address generation used for the wallet (deterministic or non-detministic).
Depending on the characteristics of an existing wallet, the function adjusts subsequent operations accordingly.
Security is paramount to the function's design. One of its features is the implementation of a unique
double encryption technique. Initially, the individual JSON key-value pairs within the genrated wallet data
are encrypted with the use of helper functions and returned back to the `generateAddressHelper` function.
Afterwhich, the function encrypts the entire JSON entry that houses these encrypted pairs, effectively wrapping
the data in a second layer of encryption.
For users prioritizing additional layers of security, there's support for Two-Factor Authentication (2FA).
When 2FA is enabled, the function integrates the generated TOTP (Time-based One-Time Password) secret directly
into the encryption and decryption processes, intertwining the 2FA token with the cryptographic operations, thereby
adding an intricate layer of security.
To conclude its operations, the function ensures that any transient sensitive data, especially those retained in
memory, are securely eradicated, mitigating risks of unintended data exposure or leaks.
Parameters:
- filename: File path designated for the storage or retrieval of wallet data.
- password (str): The user's password, used for the various cryptographic processes.
- totp_code: An optional Time-based One-Time Password, used for Two-Factor Authentication.
- new_wallet (bool, optional): Specifies if the operation involves creating a new wallet.
- encrypt (bool, optional): Specifies if the wallet data should undergo encryption.
- use2FA (bool, optional): Specifies if Two-Factor Authentication should be enabled.
- deterministic (bool, optional): Specifies if deterministic address generation should
be enabled for the wallet.
Returns:
- str: A string that represents a newly generated address.
"""
# Initialize mnemonic to None
#mnemonic = None
#Make sure that the wallet directories exists
ensure_wallet_directories_exist()
#Normalize filename
filename = get_normalized_filepath(filename)
# Load the existing or new wallet data from a file (filename)
data, wallet_exists = _load_data(filename, new_wallet)
# If wallet dose not exist return None
# This handles the case if using generateaddress for a wallet that dose not exist
if not new_wallet and not wallet_exists:
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
if new_wallet:
stored_encrypt_param = encrypt
stored_deterministic_param = deterministic
imported_entries = 0
# Determine encryption status and wallet type for an existing wallet
if wallet_exists or not new_wallet:
# Convert part of the wallet data to a JSON string
data_segment = json.dumps(data["wallet_data"])
# Check if the wallet data is encrypted and if a password is provided
if is_wallet_encrypted(data_segment) and not password and not new_wallet:
logging.error("Wallet is encrypted. A password is required to add additional addresses.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
if is_wallet_encrypted(data_segment):
# If encrypted and password is provided, set encrypt flag to True
encrypt = True
if not is_wallet_encrypted(data_segment):
encrypt = False
# Check if the existing wallet type is deterministic
if "wallet_type" in data["wallet_data"] and not new_wallet:
deterministic = data["wallet_data"]["wallet_type"] == "deterministic"
if "imported_entries" in data["wallet_data"]["entry_data"]:
imported_entries = len(data["wallet_data"]["entry_data"]["imported_entries"])
if len(data["wallet_data"]["entry_data"]["entries"]) + imported_entries > 255 and not new_wallet:
print("Cannot proceed. Maximum wallet entries reached.")
return None
#Handle backup and overwrite for an existing wallet
if new_wallet and wallet_exists:
if "wallet_type" in data["wallet_data"]:
deterministic = data["wallet_data"]["wallet_type"] == "deterministic"
if not UserPrompts.backup_and_overwrite_helper(data, filename, overwrite_password, encrypt, backup, disable_warning, deterministic):
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return
else:
if '-verbose' in sys.argv:
print()
if new_wallet:
logging.info("new_wallet is set to True.")
encrypt = stored_encrypt_param
deterministic = stored_deterministic_param
else:
logging.info("new_wallet is set to False.")
# Handle different scenarios based on whether the wallet is encrypted
if encrypt:
logging.info("encrypt is set to True.")
if new_wallet:
logging.info("Handling new encrypted wallet.")
# Handle creation of a new encrypted wallet
data, totp_secret, hmac_salt, verification_salt, stored_verifier = handle_new_encrypted_wallet(password, totp_code, use2FA, filename, deterministic)
if not data:
logging.error(f"Error: Data from handle_new_encrypted_wallet is None!\nDebug: HMAC Salt: {hmac_salt}, Verification Salt: {verification_salt}, Stored Verifier: {stored_verifier}")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
else:
logging.info("Handling existing encrypted wallet.")
# Handle operations on an existing encrypted wallet
hmac_salt, verification_salt, stored_verifier, totp_secret = handle_existing_encrypted_wallet(filename, data, password, totp_code, deterministic)
if not hmac_salt or not verification_salt or not stored_verifier:
#logging.error(f"Error: Data from handle_existing_encrypted_wallet is None!\nDebug: HMAC Salt: {hmac_salt}, Verification Salt: {verification_salt}, Stored Verifier: {stored_verifier}")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
else:
logging.info("encrypt is set to False.")
logging.info(f"is_import is set to {is_import}")
# Check if the user is importing a wallet entry
if not is_import:
# If deterministic flag is set, generate addresses in a deterministic way
if deterministic:
logging.info("deterministic is set to True.")
if not password:
logging.error("Password is required to derive the deterministic address.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
if new_wallet:
logging.info("Generating deterministic wallet data.")
# Generate the initial data for a new deterministic wallet
if mnemonic:
wallet_data = generate(mnemonic_phrase=mnemonic, passphrase=password, deterministic=True)
else:
wallet_data = generate(passphrase=password, deterministic=True)
if encrypt:
logging.info("Data successfully generated for new encrypted deterministic wallet.")
logging.info("Parseing and encrypting master mnemonic.")
# Parse and encrypt the mnemonic words individually
data["wallet_data"]["entry_data"]["key_data"] = parse_and_encrypt_mnemonic(wallet_data["mnemonic"], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
else:
logging.info("Data successfully generated for new unencrypted deterministic wallet.")
# Structure for a new unencrypted deterministic wallet
data = {
"wallet_data": {
"wallet_type": "deterministic",
"version": "0.2.2",
"entry_data": {
"master_mnemonic": wallet_data["mnemonic"],
"entries":[]
}
}
}
else:
# Set the deterministic index value based on the length of the entries in the wallet
index = len(data["wallet_data"]["entry_data"]["entries"])
if encrypt:
logging.info("Decrypting and parsing the master mnemonic.")
# Decrypt and parse the existing mnemonic for the deterministic wallet
mnemonic = decrypt_and_parse_mnemonic(data["wallet_data"]["entry_data"]["key_data"], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
logging.info("Master mnemonic successfully decrypted.")
wallet_data = []
entries_generated = -1
logging.info("Generating deterministic wallet data.")
for _ in range(amount):
if index + entries_generated < 256:
entries_generated += 1
generated_data = generate(mnemonic_phrase=mnemonic, passphrase=password, index=index+entries_generated, deterministic=True)
wallet_data.append(generated_data)
if index + len(wallet_data) >= 256:
print("Maximum wallet entries reached.\n")
break
logging.info(f"{entries_generated + 1} address(es) successfully generated for existing encrypted determinsitic wallet.")
else:
# Use the existing mnemonic directly if it's not encrypted
mnemonic = data["wallet_data"]["entry_data"]["master_mnemonic"]
logging.info("Validating passphrase used for address derivation.")
# Verify if the provided passphrase correctly derives child keys.
# Derive the first child key using the master mnemonic and the given passphrase.
first_child_data = generate(mnemonic_phrase=mnemonic,passphrase=password, index=0, deterministic=True)
# Check if the derived child's private key matches the private key of the first entry in the stored wallet.
if first_child_data["private_key"] != data["wallet_data"]["entry_data"]["entries"][0]["private_key"]:
# Log an error message if the private keys do not match, indicating that the provided passphrase is incorrect.
logging.error("Invalid passphrase. To derive the deterministic address, please re-enter the correct passphrase and try again.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
else:
logging.info("Passphrase validated.")
wallet_data = []
entries_generated = -1
logging.info("Generating deterministic wallet data.")
for _ in range(amount):
if index + entries_generated < 256:
entries_generated += 1
generated_data = generate(mnemonic_phrase=mnemonic, passphrase=password, index=index + entries_generated, deterministic=True)
wallet_data.append(generated_data)
if index + len(wallet_data) >= 256:
print("Maximum wallet entries reached.\n")
break
logging.info(f"{entries_generated + 1} address(es) successfully generated for existing unencrypted determinsitic wallet.")
else:
logging.info("deterministic is set to False")
# For non-deterministic wallets, generate a random wallet data
if not new_wallet:
wallet_data = []
entries_generated = -1
logging.info("Generating non-deterministic wallet data.")
for _ in range(amount):
if len(data["wallet_data"]["entry_data"]["entries"]) < 256:
generated_data = generate()
wallet_data.append(generated_data)
entries_generated += 1
if len(data["wallet_data"]["entry_data"]["entries"]) + len(wallet_data) >= 256:
print("Maximum wallet entries reached.\n")
break
if encrypt:
logging.info(f"{entries_generated + 1} address(es) successfully generated for existing encrypted non-determinsitic wallet.")
else:
logging.info(f"{entries_generated + 1} address(es) successfully generated for existing unencrypted non-determinsitic wallet.")
else:
logging.info("Generating non-deterministic wallet data.")
wallet_data = generate()
if new_wallet and not encrypt:
data = {
"wallet_data": {
"wallet_type": "non-deterministic",
"version": "0.2.2",
"entry_data": {
"entries":[]
}
}
}
logging.info("Data successfully generated for new unencrypted non-deterministic wallet.")
if new_wallet and encrypt:
logging.info("Data successfully generated for new encrypted non-deterministic wallet.")
else:
if not new_wallet:
# Initialize wallet_data dictionary
wallet_data = []
# Get number of wallet entries
index = len(data["wallet_data"]["entry_data"]["entries"])
# Return None if amount of wallet entries are 256 or more
if len(data["wallet_data"]["entry_data"]["entries"]) >= 256:
logging.error("Maximum wallet entries reached.\n")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
# Validate private key using regex pattern
private_key_pattern = r'^(0x)?[0-9a-fA-F]{64}$'
if not re.match(private_key_pattern, private_key):
logging.error("The private key provided is not valid.")
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
# Remove 0x prefix from private key if it exists
if private_key.startswith('0x'):
private_key = private_key[2:]
logging.info("Generating import data based on the provided private key.")
# Generate wallet data from private key
generated_data = generate_from_private_key(private_key_hex=private_key)
if generated_data:
logging.info("Data successfully generated from private key.")
# Ensure imported_entries exists
if not "imported_entries" in data["wallet_data"]["entry_data"]:
data["wallet_data"]["entry_data"]["imported_entries"] = []
# Append generated data to wallet_data
wallet_data.append(generated_data)
# Prepare data to be saved based on encryption status
if encrypt:
# Prepare encrypted data to be saved
logging.info("Encrypting generated data.")
if new_wallet:
encrypted_wallet_data = generate_encrypted_wallet_data(wallet_data, data, password, totp_secret, hmac_salt, verification_salt, stored_verifier)
encrypted_data_entry = EncryptDecryptUtils.encrypt_data(json.dumps(encrypted_wallet_data), password, totp_secret, hmac_salt, verification_salt, stored_verifier)
data["wallet_data"]["entry_data"]["entries"].append(encrypted_data_entry)
else:
for item in wallet_data:
encrypted_wallet_data = generate_encrypted_wallet_data(item, data, password, totp_secret, hmac_salt, verification_salt, stored_verifier, is_import=is_import)
encrypted_data_entry = EncryptDecryptUtils.encrypt_data(json.dumps(encrypted_wallet_data), password, totp_secret, hmac_salt, verification_salt, stored_verifier)
if not is_import:
data["wallet_data"]["entry_data"]["entries"].append(encrypted_data_entry)
else:
data["wallet_data"]["entry_data"]["imported_entries"].append(encrypted_data_entry)
# Set HMAC message based on the encrypted wallet data
if deterministic:
hmac_msg = json.dumps(data["wallet_data"]["entry_data"]["entries"]).encode() + json.dumps(data["wallet_data"]["entry_data"]["key_data"]).encode()
else:
hmac_msg = json.dumps(data["wallet_data"]["entry_data"]["entries"]).encode()
if "imported_entries" in data["wallet_data"]["entry_data"]:
hmac_msg = json.dumps(data["wallet_data"]["entry_data"]["imported_entries"]).encode() + hmac_msg
# Calculate HMAC for wallet's integrity verification
computed_hmac = Verification.hmac_util(password=password,hmac_salt=hmac_salt,hmac_msg=hmac_msg,verify=False)
data["wallet_data"]["hmac"] = base64.b64encode(computed_hmac).decode()
else:
# Prepare unencrypted data to be saved
if new_wallet:
unencrypted_data_entry = generate_unencrypted_wallet_data(wallet_data, data)
data["wallet_data"]["entry_data"]["entries"].append(unencrypted_data_entry)
else:
for item in wallet_data:
unencrypted_data_entry = generate_unencrypted_wallet_data(item, data, is_import=is_import)
if not is_import:
data["wallet_data"]["entry_data"]["entries"].append(unencrypted_data_entry)
else:
data["wallet_data"]["entry_data"]["imported_entries"].append(unencrypted_data_entry)
# Save the updated wallet data back to the file
logging.info("Saving data to wallet file.")
DataManipulation._save_data(filename, data)
# Extract the newly generated address to be returned
if "-verbose" in sys.argv:
print("\n")
print("\033[2A")
# Sgie warning and other info to user
warning = 'WARNING: Never disclose your mnemonic phrase or private key! Anyone with access to these can steal the assets held in your account.'
if not is_import:
if amount == 1 and new_wallet:
result = f"Successfully generated new wallet at: {filename}.\n\n{warning}\n{'Master Mnemonic' if deterministic else 'Mnemonic'}: {wallet_data['mnemonic']}\nPrivate Key: 0x{wallet_data['private_key']}\nAddress #{len(data['wallet_data']['entry_data']['entries'])}: {wallet_data['address']}"
if amount == 1 and not new_wallet:
n ='\n'
result = f"Successfully generated and stored wallet entry.\n\n{warning}{n+'Mnemonic: ' + wallet_data[0]['mnemonic'] if not deterministic else ''}\nPrivate Key: 0x{wallet_data[0]['private_key']}\nAddress #{len(data['wallet_data']['entry_data']['entries'])}: {wallet_data[0]['address']}"
elif amount > 1 and not new_wallet:
result = f"Successfully generated and stored {entries_generated + 1} wallet entries."
else:
result = f"Successfully imported wallet entry.\n\n{warning}\nImported Private Key #{len(data['wallet_data']['entry_data']['imported_entries'])}: 0x{wallet_data[0]['private_key']}\nAddress: {wallet_data[0]['address']}"
print(result)
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
def decryptWalletEntries(filename, password, totp_code=None, address=[], fields=[], to_json=False, show=None):
"""Overview:
The `decryptWalletEntries` function decrypts wallet entries from an encrypted file. It supports both deterministic
and non-deterministic wallet types and executes multiple steps for processing wallet data.
The function begins with initializing necessary directories and normalizing the input file path. The function then
proceeds to load wallet data from the specified file, checking both its existence and encryption status. If the data
is encrypted, it extracts essential cryptographic parameters such as HMAC salt, verification salt, stored verifier,
and TOTP secret using the `handle_existing_encrypted_wallet` function. These parameters are crucial for the subsequent
decryption process. The function then distinguishes between deterministic and non-deterministic wallets, applying specific
decryption and data generation approaches respectively, based on the wallet type.
The core decryption process involves iterating through each entry in the wallet data. The decryption relies on the
function `decrypt_data`, which performs the multi-layered decryption process, which includes the ChaCha20-Poly1305
and AES-GCM decryption layers.
For deterministic wallets, the master mnemonic phrase is decrypted using the `decrypt_and_parse_mnemonic`function.
Following decryption, the master mnemonic is utilized, along with a user-defined password, and an entry id which, as
input parameters for the `generate` function. The `generate` function is used to deterministically produce additional
wallet entry data, consisting of the private key, public key, and address. The entry id is used for the address derivation
path when generating the requisite data, and is crucial in the process.
Conversely, for non-deterministic wallets, each wallet entry has its own unique mnemonic phrase that must undergo the same
decryption process. Once decrypted, the mnemonic is passed to the generate function to derive the corresponding wallet
entry data: private key, public key, and address.
The procedures described for both deterministic and non-deterministic wallets facilitate the independent and secure
generation of supplementary wallet data. This methodology was adopted as an alternative to directly storing the complete data
set (private key, public key, and address) for every wallet entry. Instead, encrypted wallet files are designed to contain only
the minimal data required to derive these core components. During testing, this approach has been shown to significantly reduce
the file size of encrypted wallet files
A key feature of this function is its filtering mechanism. The function can filter output based on specific addresses or fields.
If one or more addresses are specified, the function filters the entries to include or exclude only those associated with that
address. If one or more fields are specified (id, mneominc, private_key, public_key, address), then the `generate` function will
only return those specified fields. This filtering is essential for targeted data retrieval and reducing processing load, especially
for large wallets.
In addition to address-based and field-based filtering, this function can also filter entries based on their origin: distinguishing
between generated and imported wallet entries. This capability is crucial for users who need to segregate entries based on how they
were added to the wallet. When the show parameter is set to 'generated', the function processes only the entries that were internally
generated within the wallet. Conversely, if the parameter is set to 'imported', the function focuses solely on wallet entries that were
externally imported, such as those added through direct import of private keys.
Specific use cases, such as when only the 'mnemonic' field is requested for deterministic wallets or handling command-line
arguments for sending or generating paper wallets, are also included in the function's logic.
Parameters:
- filename (str): Path to the encrypted wallet file.
- password (str): User's password for decryption.
- totp_code (str, optional): TOTP for Two-Factor Authentication, required if TFA was enabled during encryption.
- address (str, optional): Filter results by a specific address.
- fields (list of str, optional): Fields to decrypt and return.
- to_json (bool, optional): If True, outputs a JSON string; otherwise, returns a dictionary.
- show (str, optional): Option to show 'imported', 'generated', or all entries.
Returns:
- dict or str: Decrypted wallet entries as a dictionary or a JSON string, formatted according to the 'pretty'
flag and filtered as per the specified criteria.
"""
# Ensure the wallet directories exist
ensure_wallet_directories_exist()
# Normalize filename to a standard path format
filename = get_normalized_filepath(filename)
# Load existing wallet data from the file, handle non-existent wallet
data, wallet_exists = _load_data(filename, False)
if not wallet_exists:
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
# Check if wallet data is encrypted and initialize flags
data_segment = json.dumps(data["wallet_data"])
is_encrypted = is_wallet_encrypted(data_segment)
deterministic = "wallet_type" in data["wallet_data"] and data["wallet_data"]["wallet_type"] == "deterministic"
# Count total entries including imported ones
index = len(data["wallet_data"]["entry_data"]["entries"])
imported_entries_length = len(data["wallet_data"]["entry_data"].get("imported_entries", []))
combined_length = index + imported_entries_length
# Extract cryptographic components for encrypted wallets
if is_encrypted:
hmac_salt, verification_salt, stored_verifier, totp_secret = handle_existing_encrypted_wallet(filename, data, password, totp_code, deterministic)
if not all([hmac_salt, verification_salt, stored_verifier]):
DataManipulation.secure_delete([var for var in locals().values() if var is not None])
return None
# Handle warnings based on wallet size and command-line arguments
if 'send' in sys.argv:
print("\nA private key is required to send funds. \nSince a private key has not been provided, the wallet client will attempt to decrypt each entry in the wallet file until it finds the private key associated with the address specified. \nYou can use the '-private-key' argument to make this process alot faster. However, doing this is not secure and can put your funds at risk.\n")
if index + imported_entries_length >= 32:
logging.warning(f"The encrypted wallet file contains {index} entries and is quite large. Decryption {'and balance requests ' if 'balance' in sys.argv else ''}may take a while.\n")
elif index + imported_entries_length >= 32 and 'balance' in sys.argv:
logging.warning(f"The wallet file contains {index} entries and is quite large. Balance requests may take a while.\n")
# Special case: If only 'mnemonic' is requested and the wallet is deterministic
if fields == ["mnemonic"] and deterministic:
master_mnemonic = decrypt_and_parse_mnemonic(data["wallet_data"]["entry_data"]["key_data"], password, totp_secret, hmac_salt, verification_salt, stored_verifier) if is_encrypted else data["wallet_data"]["entry_data"]["master_mnemonic"]
master_mnemonic_json = json.dumps({"entry_data": {"master_mnemonic": master_mnemonic}}, indent=4)
print(f"Wallet Data for: {filename}")
result = master_mnemonic_json if to_json else f"Master Mnemonic: {master_mnemonic}"
DataManipulation.secure_delete([var for var in locals().values() if var is not None and var is not result])
return result
mnemonic = ""
if deterministic:
mnemonic = decrypt_and_parse_mnemonic(data["wallet_data"]["entry_data"]["key_data"], password, totp_secret, hmac_salt, verification_salt, stored_verifier) if is_encrypted else data["wallet_data"]["entry_data"]["master_mnemonic"]
generated_entries = []
imported_entries = []
fields = fields or ["mnemonic", "id", "private_key", "public_key", "address", "is_import"]
ordered_fields = ["id", "mnemonic", "private_key", "public_key", "address"]
entry_count = 0
max_entry_count = combined_length
# Define a function to handle entry decryption and data generation
def handle_entry_decryption(entry, is_import):
# Decrypt entry data
entry_with_encrypted_values = json.loads(EncryptDecryptUtils.decrypt_data(entry, password, totp_secret, hmac_salt, verification_salt, stored_verifier)) if is_encrypted else entry
# Decrypt the 'id' field for all entries if the wallet is encrypted
if 'id' in entry_with_encrypted_values and is_encrypted:
decrypted_id = EncryptDecryptUtils.decrypt_data(entry_with_encrypted_values['id'], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
entry_with_encrypted_values['id'] = int(decrypted_id)
# Decrypt the 'mnemonic' field if the wallet is encrypted
if 'mnemonic' in entry_with_encrypted_values and is_encrypted:
decrypted_mnemonic = EncryptDecryptUtils.decrypt_data(entry_with_encrypted_values['mnemonic'], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
entry_with_encrypted_values['mnemonic'] = decrypted_mnemonic
if 'private_key' in entry_with_encrypted_values and is_encrypted:
decrypted_private_key = EncryptDecryptUtils.decrypt_data(entry_with_encrypted_values['private_key'], password, totp_secret, hmac_salt, verification_salt, stored_verifier)
entry_with_encrypted_values['private_key'] = decrypted_private_key
# Generate data fields based on the deterministic flag
generated_data = {}
if not is_import:
if deterministic:
# Generate data for deterministic wallet with index
generated_data = generate(mnemonic_phrase=mnemonic, passphrase=password, index=entry_with_encrypted_values['id'] - 1, deterministic=deterministic, fields=fields)
if "mnemonic" in generated_data:
del generated_data["mnemonic"]
generated_data["id"] = entry_with_encrypted_values['id']
#generated_verification_data = generate(mnemonic_phrase=mnemonic, passphrase=password, index=entry_with_encrypted_values['id'] - 1, deterministic=deterministic)
#if "private_key" in fields:
# if not generated_verification_data["private_key"] == entry_with_encrypted_values['private_key']:
# generated_data["private_key"] = entry_with_encrypted_values['private_key']
else:
# Generate data for non-deterministic wallet without index
generated_data = generate(mnemonic_phrase=entry_with_encrypted_values['mnemonic'], deterministic=deterministic, fields=fields)
else:
# Generate data from private key for imported entries
generated_data = generate_from_private_key(private_key_hex=entry_with_encrypted_values["private_key"], fields=fields)
generated_data["is_import"] = True
generated_data["id"] = entry_with_encrypted_values['id']
return generated_data
# Check if address filtering is applied
address_filtering_applied = bool(address) and 'address' not in fields
if address_filtering_applied:
fields.append('address')
if show == "imported":
combined_length -= index
if show == "generated":
combined_length -= imported_entries_length
address_found = False
# Main loop for processing entry_data object array
for entry_type, entries in data["wallet_data"]["entry_data"].items():
# Exclude key_data and master_mnemonic from loop
if entry_type not in ["key_data", "master_mnemonic"]:
# Seconary nested loop for processing entries
for entry in entries:
is_import = entry_type == "imported_entries"
# Skip decryption and processing if the entry type doesn't match the 'show' parameter
if (show == "imported" and not is_import) or (show == "generated" and is_import):
continue
# Decrypt the entry only if the wallet is encrypted
if is_encrypted:
if entry_count < max_entry_count:
entry_count += 1
decrypted_entry = handle_entry_decryption(entry, is_import)
# Handle decrypted entries when using the 'send' or 'generate paperwallet' sub-commands
if 'send' in sys.argv or 'paperwallet' in sys.argv:
print(f"\rDecrypting wallet entry {entry_count} of {combined_length} | Address: {decrypted_entry['address']}", end='')
if address[0] in decrypted_entry['address']: