-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcli_wallet.py
334 lines (269 loc) · 12.9 KB
/
cli_wallet.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
import getpass
import json
import logging
import sys
from pathlib import Path
from typing import Any, List, Optional, Tuple
from multiversx_sdk import (Address, Mnemonic, UserPEM, UserSecretKey,
UserWallet)
from multiversx_sdk.core.address import get_shard_of_pubkey
from multiversx_sdk_cli import cli_shared, utils
from multiversx_sdk_cli.config import get_address_hrp
from multiversx_sdk_cli.constants import NUMBER_OF_SHARDS
from multiversx_sdk_cli.errors import (BadUserInput, KnownError,
WalletGenerationError)
from multiversx_sdk_cli.sign_verify import SignedMessage, sign_message
from multiversx_sdk_cli.ux import show_critical_error, show_message
logger = logging.getLogger("cli.wallet")
WALLET_FORMAT_RAW_MNEMONIC = "raw-mnemonic"
WALLET_FORMAT_KEYSTORE_MNEMONIC = "keystore-mnemonic"
WALLET_FORMAT_KEYSTORE_SECRET_KEY = "keystore-secret-key"
WALLET_FORMAT_PEM = "pem"
WALLET_FORMAT_ADDRESS_BECH32 = "address-bech32"
WALLET_FORMAT_ADDRESS_HEX = "address-hex"
WALLET_FORMAT_SECRET_KEY = "secret-key"
WALLET_FORMATS = [
WALLET_FORMAT_RAW_MNEMONIC,
WALLET_FORMAT_KEYSTORE_MNEMONIC,
WALLET_FORMAT_KEYSTORE_SECRET_KEY,
WALLET_FORMAT_PEM,
]
WALLET_FORMATS_AND_ADDRESSES = [
*WALLET_FORMATS,
WALLET_FORMAT_ADDRESS_BECH32,
WALLET_FORMAT_ADDRESS_HEX,
WALLET_FORMAT_SECRET_KEY,
]
MAX_ITERATIONS_FOR_GENERATING_WALLET = 100
CURRENT_SHARDS = [i for i in range(NUMBER_OF_SHARDS)]
def setup_parser(args: List[str], subparsers: Any) -> Any:
parser = cli_shared.add_group_subparser(
subparsers,
"wallet",
"Create wallet, derive secret key from mnemonic, bech32 address helpers etc."
)
subparsers = parser.add_subparsers()
sub = cli_shared.add_command_subparser(
subparsers,
"wallet",
"new",
"Create a new wallet and print its mnemonic; optionally save as password-protected JSON (recommended) or PEM (not recommended)"
)
sub.add_argument("--format", choices=WALLET_FORMATS, help="the format of the generated wallet file (default: %(default)s)", default=None)
sub.add_argument("--outfile", help="the output path and base file name for the generated wallet files (default: %(default)s)", type=str)
sub.add_argument("--address-hrp", help=f"the human-readable part of the address, when format is {WALLET_FORMAT_KEYSTORE_SECRET_KEY} or {WALLET_FORMAT_PEM} (default: %(default)s)", type=str, default=get_address_hrp())
sub.add_argument("--shard", type=int, help="the shard in which the address will be generated; (default: random)")
sub.set_defaults(func=wallet_new)
sub = cli_shared.add_command_subparser(
subparsers,
"wallet",
"convert",
"Convert a wallet from one format to another"
)
sub.add_argument("--infile", help="path to the input file")
sub.add_argument("--outfile", help="path to the output file")
sub.add_argument("--in-format", required=True, choices=WALLET_FORMATS, help="the format of the input file")
sub.add_argument("--out-format", required=True, choices=WALLET_FORMATS_AND_ADDRESSES, help="the format of the output file")
sub.add_argument("--address-index", help=f"the address index, if input format is {WALLET_FORMAT_RAW_MNEMONIC}, {WALLET_FORMAT_KEYSTORE_MNEMONIC} or {WALLET_FORMAT_PEM} (with multiple entries) and the output format is {WALLET_FORMAT_KEYSTORE_SECRET_KEY} or {WALLET_FORMAT_PEM}", type=int, default=0)
sub.add_argument("--address-hrp", help=f"the human-readable part of the address, when the output format is {WALLET_FORMAT_KEYSTORE_SECRET_KEY} or {WALLET_FORMAT_PEM} (default: %(default)s)", type=str, default=get_address_hrp())
sub.set_defaults(func=convert_wallet)
sub = cli_shared.add_command_subparser(
subparsers,
"wallet",
"bech32",
"Helper for encoding and decoding bech32 addresses"
)
sub.add_argument("value", help="the value to encode or decode")
group = sub.add_mutually_exclusive_group(required=True)
group.add_argument("--encode", action="store_true", help="whether to encode")
group.add_argument("--decode", action="store_true", help="whether to decode")
sub.add_argument("--hrp", type=str, help="the human readable part; only used for encoding to bech32 (default: %(default)s)", default=get_address_hrp())
sub.set_defaults(func=do_bech32)
sub = cli_shared.add_command_subparser(
subparsers,
"wallet",
"sign-message",
"Sign a message"
)
sub.add_argument("--message", required=True, help="the message you want to sign")
cli_shared.add_wallet_args(args, sub)
sub.set_defaults(func=sign_user_message)
sub = cli_shared.add_command_subparser(
subparsers,
"wallet",
"verify-message",
"Verify a previously signed message"
)
sub.add_argument("--address", required=True, help="the bech32 address of the signer")
sub.add_argument("--message", required=True, help="the previously signed message(readable text, as it was signed)")
sub.add_argument("--signature", required=True, help="the signature in hex format")
sub.set_defaults(func=verify_signed_message)
parser.epilog = cli_shared.build_group_epilog(subparsers)
return subparsers
def wallet_new(args: Any):
format = args.format
outfile = args.outfile
address_hrp = args.address_hrp
shard = args.shard
if shard is not None:
mnemonic = _generate_mnemonic_with_shard_constraint(shard)
else:
mnemonic = Mnemonic.generate()
print(f"Mnemonic: {mnemonic.get_text()}")
print(f"Wallet address: {mnemonic.derive_key().generate_public_key().to_address(address_hrp).to_bech32()}")
if format is None:
return
if outfile is None:
raise KnownError("The --outfile option is required when --format is specified.")
outfile = Path(outfile).expanduser().resolve()
if outfile.exists():
raise KnownError(f"File already exists, will not overwrite: {outfile}")
if format == WALLET_FORMAT_RAW_MNEMONIC:
outfile.write_text(mnemonic.get_text())
elif format == WALLET_FORMAT_KEYSTORE_MNEMONIC:
password = getpass.getpass("Enter a new password (for keystore):")
wallet = UserWallet.from_mnemonic(mnemonic.get_text(), password)
wallet.save(outfile)
elif format == WALLET_FORMAT_KEYSTORE_SECRET_KEY:
password = getpass.getpass("Enter a new password (for keystore):")
secret_key = mnemonic.derive_key()
wallet = UserWallet.from_secret_key(secret_key, password)
wallet.save(outfile, address_hrp)
elif format == WALLET_FORMAT_PEM:
secret_key = mnemonic.derive_key()
pubkey = secret_key.generate_public_key()
address = pubkey.to_address(address_hrp)
pem_file = UserPEM(address.to_bech32(), secret_key)
pem_file.save(outfile)
else:
raise KnownError(f"Unknown format: {format}")
logger.info(f"Wallet ({format}) saved: {outfile}")
def _generate_mnemonic_with_shard_constraint(shard: int) -> Mnemonic:
if shard not in CURRENT_SHARDS:
raise BadUserInput(f"Wrong shard provided. Choose between {CURRENT_SHARDS}")
for _ in range(MAX_ITERATIONS_FOR_GENERATING_WALLET):
mnemonic = Mnemonic.generate()
pubkey = mnemonic.derive_key().generate_public_key()
generated_address_shard = get_shard_of_pubkey(pubkey.buffer, NUMBER_OF_SHARDS)
if shard == generated_address_shard:
return mnemonic
raise WalletGenerationError(f"Couldn't generate wallet in shard {shard}")
def convert_wallet(args: Any):
infile = Path(args.infile).expanduser().resolve() if args.infile else None
outfile = Path(args.outfile).expanduser().resolve() if args.outfile else None
in_format = args.in_format
out_format = args.out_format
address_index = args.address_index
address_hrp = args.address_hrp
if outfile and outfile.exists():
raise KnownError(f"File already exists, will not overwrite: {outfile}")
if infile:
input_text = infile.read_text()
else:
print("Insert text below. Press 'Ctrl-D' (Linux / MacOS) or 'Ctrl-Z' (Windows) when done.")
input_text = sys.stdin.read().strip()
mnemonic, secret_key = _load_wallet(input_text, in_format, address_index)
output_text = _create_wallet_content(out_format, mnemonic, secret_key, address_index, address_hrp)
if outfile:
outfile.write_text(output_text)
else:
print("Output:")
print()
print(output_text)
def _load_wallet(input_text: str, in_format: str, address_index: int) -> Tuple[Optional[Mnemonic], Optional[UserSecretKey]]:
if in_format == WALLET_FORMAT_RAW_MNEMONIC:
input_text = " ".join(input_text.split())
mnemonic = Mnemonic(input_text)
return mnemonic, None
if in_format == WALLET_FORMAT_KEYSTORE_MNEMONIC:
password = getpass.getpass("Enter the password for the input keystore:")
keyfile = json.loads(input_text)
mnemonic = UserWallet.decrypt_mnemonic(keyfile, password)
return mnemonic, None
if in_format == WALLET_FORMAT_KEYSTORE_SECRET_KEY:
password = getpass.getpass("Enter the password for the input keystore:")
keyfile = json.loads(input_text)
secret_key = UserWallet.decrypt_secret_key(keyfile, password)
return None, secret_key
if in_format == WALLET_FORMAT_PEM:
secret_key = UserPEM.from_text(input_text, address_index).secret_key
return None, secret_key
raise KnownError(f"Cannot load wallet, unknown input format: <{in_format}>. Make sure to use one of following: {WALLET_FORMATS}.")
def _create_wallet_content(
out_format: str,
mnemonic: Optional[Mnemonic],
secret_key: Optional[UserSecretKey],
address_index: int,
address_hrp: str
) -> str:
if out_format == WALLET_FORMAT_RAW_MNEMONIC:
if mnemonic is None:
raise KnownError(f"Cannot convert to {out_format} (mnemonic not available).")
return mnemonic.get_text()
if out_format == WALLET_FORMAT_KEYSTORE_MNEMONIC:
if mnemonic is None:
raise KnownError(f"Cannot convert to {out_format} (mnemonic not available).")
password = getpass.getpass("Enter a new password (for the output keystore):")
wallet = UserWallet.from_mnemonic(mnemonic.get_text(), password)
return wallet.to_json()
if out_format == WALLET_FORMAT_KEYSTORE_SECRET_KEY:
if mnemonic:
secret_key = mnemonic.derive_key(address_index)
assert secret_key is not None
password = getpass.getpass("Enter a new password (for the output keystore):")
wallet = UserWallet.from_secret_key(secret_key, password)
return wallet.to_json(address_hrp)
if out_format == WALLET_FORMAT_PEM:
if mnemonic:
secret_key = mnemonic.derive_key(address_index)
assert secret_key is not None
pubkey = secret_key.generate_public_key()
address = pubkey.to_address(address_hrp)
pem = UserPEM(address.to_bech32(), secret_key)
return pem.to_text()
if out_format == WALLET_FORMAT_ADDRESS_BECH32:
if mnemonic:
secret_key = mnemonic.derive_key(address_index)
assert secret_key is not None
pubkey = secret_key.generate_public_key()
address = pubkey.to_address(address_hrp)
return address.to_bech32()
if out_format == WALLET_FORMAT_ADDRESS_HEX:
if mnemonic:
secret_key = mnemonic.derive_key(address_index)
assert secret_key is not None
pubkey = secret_key.generate_public_key()
return pubkey.hex()
if out_format == WALLET_FORMAT_SECRET_KEY:
if mnemonic:
secret_key = mnemonic.derive_key(address_index)
assert secret_key is not None
return secret_key.hex()
raise KnownError(f"Cannot create wallet, unknown output format: <{out_format}>. Make sure to use one of following: {WALLET_FORMATS}.")
def do_bech32(args: Any):
encode = args.encode
value = args.value
if encode:
hrp = args.hrp
address = Address.new_from_hex(value, hrp)
result = address.to_bech32()
else:
address = Address.new_from_bech32(value)
result = address.to_hex()
print(result)
return result
def sign_user_message(args: Any):
message: str = args.message
account = cli_shared.prepare_account(args)
signed_message = sign_message(message, account)
utils.dump_out_json(signed_message.to_dictionary())
def verify_signed_message(args: Any):
bech32_address = args.address
message: str = args.message
signature: str = args.signature
signed_message = SignedMessage(bech32_address, message, signature)
is_signed = signed_message.verify_signature()
if is_signed:
show_message(f"""SUCCESS: The message "{message}" was signed by {bech32_address}""")
else:
show_critical_error(f"""FAILED: The message "{message}" was NOT signed by {bech32_address}""")