forked from spesmilo/electrum
-
Notifications
You must be signed in to change notification settings - Fork 24
/
commands.py
2130 lines (1874 loc) · 93.8 KB
/
commands.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
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import datetime
import copy
import argparse
import json
import ast
import base64
import operator
import asyncio
import inspect
from functools import wraps, partial
from itertools import repeat
from decimal import Decimal
from typing import Optional, TYPE_CHECKING, Dict, List
from .import util, ecc
from .util import (bfh, bh2u, format_satoshis, json_decode, json_normalize,
is_hash256_str, is_hex_str, to_bytes)
from . import bitcoin
from .bitcoin import is_address, hash_160, COIN
from .bip32 import BIP32Node
from .i18n import _
from .names import build_name_commitment, build_name_new, Encoding, format_name_identifier, name_expiration_datetime_estimate, name_from_str, name_identifier_to_scripthash, name_semi_expires_in, name_to_str, OP_NAME_NEW, OP_NAME_FIRSTUPDATE, OP_NAME_UPDATE, validate_commitment_length, validate_identifier_length, validate_salt_length, validate_value_length
from .verifier import verify_tx_is_in_block
from .transaction import (Transaction, multisig_script, TxOutput, PartialTransaction, PartialTxOutput,
tx_from_any, PartialTxInput, TxOutpoint)
from .invoices import PR_PAID, PR_UNPAID, PR_UNKNOWN, PR_EXPIRED
from .synchronizer import Notifier
from .wallet import Abstract_Wallet, create_new_wallet, restore_wallet_from_text, Deterministic_Wallet
from .address_synchronizer import TX_HEIGHT_LOCAL
from .mnemonic import Mnemonic
from .lnutil import SENT, RECEIVED
from .lnutil import LnFeatures
from .lnutil import extract_nodeid
from .lnpeer import channel_id_from_funding_tx
from .plugin import run_hook
from .version import ELECTRUM_VERSION
from .simple_config import SimpleConfig
from .invoices import LNInvoice
from . import submarine_swaps
from . import constants
if TYPE_CHECKING:
from .network import Network
from .daemon import Daemon
known_commands = {} # type: Dict[str, Command]
class NotSynchronizedException(Exception):
pass
class NameNotResolvableError(Exception):
pass
class NameNotFoundError(NameNotResolvableError):
pass
class NameUnconfirmedError(NameNotFoundError):
pass
class NameExpiredError(NameNotFoundError):
pass
class NameSemiExpiredError(NameNotResolvableError):
pass
class NameNeverExistedError(NameNotFoundError):
pass
class NameAlreadyExistsError(Exception):
pass
class NamePreRegistrationNotFound(Exception):
pass
class NamePreRegistrationPendingError(Exception):
pass
class NameUpdatedTooRecentlyError(Exception):
pass
def satoshis(amount):
# satoshi conversion must not be performed by the parser
return int(COIN*Decimal(amount)) if amount not in ['!', None] else amount
def format_satoshis(x):
return str(Decimal(x)/COIN) if x is not None else None
class Command:
def __init__(self, func, s):
self.name = func.__name__
self.requires_network = 'n' in s
self.requires_wallet = 'w' in s
self.requires_password = 'p' in s
self.description = func.__doc__
self.help = self.description.split('.')[0] if self.description else None
varnames = func.__code__.co_varnames[1:func.__code__.co_argcount]
self.defaults = func.__defaults__
if self.defaults:
n = len(self.defaults)
self.params = list(varnames[:-n])
self.options = list(varnames[-n:])
else:
self.params = list(varnames)
self.options = []
self.defaults = []
# sanity checks
if self.requires_password:
assert self.requires_wallet
for varname in ('wallet_path', 'wallet'):
if varname in varnames:
assert varname in self.options
assert not ('wallet_path' in varnames and 'wallet' in varnames)
if self.requires_wallet:
assert 'wallet' in varnames
def command(s):
def decorator(func):
global known_commands
name = func.__name__
known_commands[name] = Command(func, s)
@wraps(func)
async def func_wrapper(*args, **kwargs):
cmd_runner = args[0] # type: Commands
cmd = known_commands[func.__name__] # type: Command
password = kwargs.get('password')
daemon = cmd_runner.daemon
if daemon:
if 'wallet_path' in cmd.options and kwargs.get('wallet_path') is None:
kwargs['wallet_path'] = daemon.config.get_wallet_path()
if cmd.requires_wallet and kwargs.get('wallet') is None:
kwargs['wallet'] = daemon.config.get_wallet_path()
if 'wallet' in cmd.options:
wallet_path = kwargs.get('wallet', None)
if isinstance(wallet_path, str):
wallet = daemon.get_wallet(wallet_path)
if wallet is None:
raise Exception('wallet not loaded')
kwargs['wallet'] = wallet
wallet = kwargs.get('wallet') # type: Optional[Abstract_Wallet]
if cmd.requires_wallet and not wallet:
raise Exception('wallet not loaded')
if cmd.requires_password and password is None and wallet.has_password():
raise Exception('Password required')
return await func(*args, **kwargs)
return func_wrapper
return decorator
class Commands:
def __init__(self, *, config: 'SimpleConfig',
network: 'Network' = None,
daemon: 'Daemon' = None, callback=None):
self.config = config
self.daemon = daemon
self.network = network
self._callback = callback
def _run(self, method, args, password_getter=None, **kwargs):
"""This wrapper is called from unit tests and the Qt python console."""
cmd = known_commands[method]
password = kwargs.get('password', None)
wallet = kwargs.get('wallet', None)
if (cmd.requires_password and wallet and wallet.has_password()
and password is None):
password = password_getter()
if password is None:
return
f = getattr(self, method)
if cmd.requires_password:
kwargs['password'] = password
if 'wallet' in kwargs:
sig = inspect.signature(f)
if 'wallet' not in sig.parameters:
kwargs.pop('wallet')
coro = f(*args, **kwargs)
fut = asyncio.run_coroutine_threadsafe(coro, asyncio.get_event_loop())
result = fut.result()
if self._callback:
self._callback()
return result
@command('')
async def commands(self):
"""List of commands"""
return ' '.join(sorted(known_commands.keys()))
@command('n')
async def getinfo(self):
""" network info """
net_params = self.network.get_parameters()
response = {
'path': self.network.config.path,
'server': net_params.server.host,
'blockchain_height': self.network.get_local_height(),
'server_height': self.network.get_server_height(),
'spv_nodes': len(self.network.get_interfaces()),
'connected': self.network.is_connected(),
'auto_connect': net_params.auto_connect,
'version': ELECTRUM_VERSION,
'default_wallet': self.config.get_wallet_path(),
'fee_per_kb': self.config.fee_per_kb(),
}
return response
@command('n')
async def stop(self):
"""Stop daemon"""
# TODO it would be nice if this could stop the GUI too
await self.daemon.stop()
return "Daemon stopped"
@command('n')
async def list_wallets(self):
"""List wallets open in daemon"""
return [{'path': path, 'synchronized': w.is_up_to_date()}
for path, w in self.daemon.get_wallets().items()]
@command('n')
async def load_wallet(self, wallet_path=None, password=None):
"""Open wallet in daemon"""
wallet = self.daemon.load_wallet(wallet_path, password, manual_upgrades=False)
if wallet is not None:
run_hook('load_wallet', wallet, None)
response = wallet is not None
return response
@command('n')
async def close_wallet(self, wallet_path=None):
"""Close wallet"""
return self.daemon.stop_wallet(wallet_path)
@command('')
async def create(self, passphrase=None, password=None, encrypt_file=True, seed_type=None, wallet_path=None):
"""Create a new wallet.
If you want to be prompted for an argument, type '?' or ':' (concealed)
"""
d = create_new_wallet(path=wallet_path,
passphrase=passphrase,
password=password,
encrypt_file=encrypt_file,
seed_type=seed_type,
config=self.config)
return {
'seed': d['seed'],
'path': d['wallet'].storage.path,
'msg': d['msg'],
}
@command('')
async def restore(self, text, passphrase=None, password=None, encrypt_file=True, wallet_path=None):
"""Restore a wallet from text. Text can be a seed phrase, a master
public key, a master private key, a list of namecoin addresses
or namecoin private keys.
If you want to be prompted for an argument, type '?' or ':' (concealed)
"""
# TODO create a separate command that blocks until wallet is synced
d = restore_wallet_from_text(text,
path=wallet_path,
passphrase=passphrase,
password=password,
encrypt_file=encrypt_file,
config=self.config)
return {
'path': d['wallet'].storage.path,
'msg': d['msg'],
}
@command('wp')
async def password(self, password=None, new_password=None, wallet: Abstract_Wallet = None):
"""Change wallet password. """
if wallet.storage.is_encrypted_with_hw_device() and new_password:
raise Exception("Can't change the password of a wallet encrypted with a hw device.")
b = wallet.storage.is_encrypted()
wallet.update_password(password, new_password, encrypt_storage=b)
wallet.save_db()
return {'password':wallet.has_password()}
@command('w')
async def get(self, key, wallet: Abstract_Wallet = None):
"""Return item from wallet storage"""
return wallet.db.get(key)
@command('')
async def getconfig(self, key):
"""Return a configuration variable. """
return self.config.get(key)
@classmethod
def _setconfig_normalize_value(cls, key, value):
if key not in ('rpcuser', 'rpcpassword'):
value = json_decode(value)
# call literal_eval for backward compatibility (see #4225)
try:
value = ast.literal_eval(value)
except:
pass
return value
@command('')
async def setconfig(self, key, value):
"""Set a configuration variable. 'value' may be a string or a Python expression."""
value = self._setconfig_normalize_value(key, value)
if self.daemon and key == 'rpcuser':
self.daemon.commands_server.rpc_user = value
if self.daemon and key == 'rpcpassword':
self.daemon.commands_server.rpc_password = value
self.config.set_key(key, value)
return True
@command('')
async def get_ssl_domain(self):
"""Check and return the SSL domain set in ssl_keyfile and ssl_certfile
"""
return self.config.get_ssl_domain()
@command('')
async def make_seed(self, nbits=None, language=None, seed_type=None):
"""Create a seed"""
from .mnemonic import Mnemonic
s = Mnemonic(language).make_seed(seed_type=seed_type, num_bits=nbits)
return s
@command('n')
async def getaddresshistory(self, address):
"""Return the transaction history of any address. Note: This is a
walletless server query, results are not checked by SPV.
"""
sh = bitcoin.address_to_scripthash(address)
return await self.network.get_history_for_scripthash(sh)
@command('w')
async def listunspent(self, wallet: Abstract_Wallet = None):
"""List unspent outputs. Returns the list of unspent transaction
outputs in your wallet."""
coins = []
for txin in wallet.get_utxos():
d = txin.to_json()
v = d.pop("value_sats")
d["value"] = str(Decimal(v)/COIN) if v is not None else None
coins.append(d)
return coins
@command('wn')
async def name_list(self, identifier=None, name_encoding='ascii', value_encoding='ascii', wallet: Abstract_Wallet = None):
"""List unspent name outputs. Returns the list of unspent name_anyupdate
outputs in your wallet."""
name_encoding = Encoding(name_encoding)
value_encoding = Encoding(value_encoding)
coins = await self.listunspent(wallet=wallet)
result = []
for coin in coins:
name_op = coin["name_op"]
if name_op is None:
continue
if "name" not in name_op:
continue
name_bytes = bfh(name_op["name"])
name = name_to_str(name_bytes, name_encoding)
value_bytes = bfh(name_op["value"])
value = name_to_str(value_bytes, value_encoding)
# Skip this item if it doesn't match the requested identifier
if identifier is not None:
if identifier != name:
continue
txid = coin["prevout_hash"]
vout = coin["prevout_n"]
address = coin["address"]
height = coin["height"]
local_chain_height = self.network.get_local_height()
expires_in, expires_time = name_expiration_datetime_estimate(height, self.network.blockchain())
expired = expires_in <= 0 if expires_in is not None else None
semi_expires_in, semi_expires_time = name_expiration_datetime_estimate(height, self.network.blockchain(), blocks_func=name_semi_expires_in)
semi_expired = semi_expires_in <= 0 if semi_expires_in is not None else None
is_mine = wallet.is_mine(address)
result_item = {
"name": name,
"name_encoding": name_encoding.value,
"value": value,
"value_encoding": value_encoding.value,
"txid": txid,
"vout": vout,
"address": address,
"height": height,
"expires_in": expires_in,
"expires_time": round(expires_time.timestamp()),
"expired": expired,
"semi_expires_in": semi_expires_in,
"semi_expires_time": round(semi_expires_time.timestamp()),
"semi_expired": semi_expired,
"ismine": is_mine,
}
result.append(result_item)
return result
@command('n')
async def getaddressunspent(self, address):
"""Returns the UTXO list of any address. Note: This
is a walletless server query, results are not checked by SPV.
"""
sh = bitcoin.address_to_scripthash(address)
return await self.network.listunspent_for_scripthash(sh)
@command('')
async def serialize(self, jsontx):
"""Create a transaction from json inputs.
Inputs must have a redeemPubkey.
Outputs must be a list of {'address':address, 'value':satoshi_amount}.
"""
keypairs = {}
inputs = [] # type: List[PartialTxInput]
locktime = jsontx.get('locktime', 0)
for txin_dict in jsontx.get('inputs'):
if txin_dict.get('prevout_hash') is not None and txin_dict.get('prevout_n') is not None:
prevout = TxOutpoint(txid=bfh(txin_dict['prevout_hash']), out_idx=int(txin_dict['prevout_n']))
elif txin_dict.get('output'):
prevout = TxOutpoint.from_str(txin_dict['output'])
else:
raise Exception("missing prevout for txin")
txin = PartialTxInput(prevout=prevout)
txin._trusted_value_sats = int(txin_dict.get('value', txin_dict['value_sats']))
nsequence = txin_dict.get('nsequence', None)
if nsequence is not None:
txin.nsequence = nsequence
sec = txin_dict.get('privkey')
if sec:
txin_type, privkey, compressed = bitcoin.deserialize_privkey(sec)
pubkey = ecc.ECPrivkey(privkey).get_public_key_hex(compressed=compressed)
keypairs[pubkey] = privkey, compressed
txin.script_type = txin_type
txin.pubkeys = [bfh(pubkey)]
txin.num_sig = 1
inputs.append(txin)
outputs = [PartialTxOutput.from_address_and_value(txout['address'], int(txout.get('value', txout['value_sats'])))
for txout in jsontx.get('outputs')]
tx = PartialTransaction.from_io(inputs, outputs, locktime=locktime)
tx.sign(keypairs)
return tx.serialize()
@command('wp')
async def signtransaction(self, tx, privkey=None, password=None, wallet: Abstract_Wallet = None):
"""Sign a transaction. The wallet keys will be used unless a private key is provided."""
# TODO this command should be split in two... (1) *_with_wallet, (2) *_with_privkey
tx = tx_from_any(tx)
if privkey:
txin_type, privkey2, compressed = bitcoin.deserialize_privkey(privkey)
pubkey = ecc.ECPrivkey(privkey2).get_public_key_bytes(compressed=compressed)
for txin in tx.inputs():
if txin.address and txin.address == bitcoin.pubkey_to_address(txin_type, pubkey.hex()):
txin.pubkeys = [pubkey]
txin.script_type = txin_type
tx.sign({pubkey.hex(): (privkey2, compressed)})
else:
wallet.sign_transaction(tx, password)
return tx.serialize()
@command('')
async def deserialize(self, tx):
"""Deserialize a serialized transaction"""
tx = tx_from_any(tx)
return tx.to_json()
@command('n')
async def broadcast(self, tx):
"""Broadcast a transaction to the network. """
tx = Transaction(tx)
await self.network.broadcast_transaction(tx)
return tx.txid()
@command('')
async def createmultisig(self, num, pubkeys):
"""Create multisig address"""
assert isinstance(pubkeys, list), (type(num), type(pubkeys))
redeem_script = multisig_script(pubkeys, num)
address = bitcoin.hash160_to_p2sh(hash_160(bfh(redeem_script)))
return {'address':address, 'redeemScript':redeem_script}
@command('w')
async def freeze(self, address: str, wallet: Abstract_Wallet = None):
"""Freeze address. Freeze the funds at one of your wallet\'s addresses"""
return wallet.set_frozen_state_of_addresses([address], True)
@command('w')
async def unfreeze(self, address: str, wallet: Abstract_Wallet = None):
"""Unfreeze address. Unfreeze the funds at one of your wallet\'s address"""
return wallet.set_frozen_state_of_addresses([address], False)
@command('w')
async def freeze_utxo(self, coin: str, wallet: Abstract_Wallet = None):
"""Freeze a UTXO so that the wallet will not spend it."""
wallet.set_frozen_state_of_coins([coin], True)
return True
@command('w')
async def unfreeze_utxo(self, coin: str, wallet: Abstract_Wallet = None):
"""Unfreeze a UTXO so that the wallet might spend it."""
wallet.set_frozen_state_of_coins([coin], False)
return True
@command('wp')
async def getprivatekeys(self, address, password=None, wallet: Abstract_Wallet = None):
"""Get private keys of addresses. You may pass a single wallet address, or a list of wallet addresses."""
if isinstance(address, str):
address = address.strip()
if is_address(address):
return wallet.export_private_key(address, password)
domain = address
return [wallet.export_private_key(address, password) for address in domain]
@command('wp')
async def getprivatekeyforpath(self, path, password=None, wallet: Abstract_Wallet = None):
"""Get private key corresponding to derivation path (address index).
'path' can be either a str such as "m/0/50", or a list of ints such as [0, 50].
"""
return wallet.export_private_key_for_path(path, password)
@command('w')
async def ismine(self, address, wallet: Abstract_Wallet = None):
"""Check if address is in wallet. Return true if and only address is in wallet"""
return wallet.is_mine(address)
@command('')
async def dumpprivkeys(self):
"""Deprecated."""
return "This command is deprecated. Use a pipe instead: 'electrum-nmc listaddresses | electrum-nmc getprivatekeys - '"
@command('')
async def validateaddress(self, address):
"""Check that an address is valid. """
return is_address(address)
@command('w')
async def getpubkeys(self, address, wallet: Abstract_Wallet = None):
"""Return the public keys for a wallet address. """
return wallet.get_public_keys(address)
@command('w')
async def getbalance(self, wallet: Abstract_Wallet = None):
"""Return the balance of your wallet. """
c, u, x = wallet.get_balance()
l = wallet.lnworker.get_balance() if wallet.lnworker else None
out = {"confirmed": str(Decimal(c)/COIN)}
if u:
out["unconfirmed"] = str(Decimal(u)/COIN)
if x:
out["unmatured"] = str(Decimal(x)/COIN)
if l:
out["lightning"] = str(Decimal(l)/COIN)
return out
@command('n')
async def getaddressbalance(self, address):
"""Return the balance of any address. Note: This is a walletless
server query, results are not checked by SPV.
"""
sh = bitcoin.address_to_scripthash(address)
out = await self.network.get_balance_for_scripthash(sh)
out["confirmed"] = str(Decimal(out["confirmed"])/COIN)
out["unconfirmed"] = str(Decimal(out["unconfirmed"])/COIN)
return out
@command('n')
async def getmerkle(self, txid, height):
"""Get Merkle branch of a transaction included in a block. Electrum
uses this to verify transactions (Simple Payment Verification)."""
return await self.network.get_merkle_for_transaction(txid, int(height))
@command('n')
async def getservers(self):
"""Return the list of known servers (candidates for connecting)."""
return self.network.get_servers()
@command('')
async def version(self):
"""Return the version of Electrum."""
from .version import ELECTRUM_VERSION
return ELECTRUM_VERSION
@command('w')
async def getmpk(self, wallet: Abstract_Wallet = None):
"""Get master public key. Return your wallet\'s master public key"""
return wallet.get_master_public_key()
@command('wp')
async def getmasterprivate(self, password=None, wallet: Abstract_Wallet = None):
"""Get master private key. Return your wallet\'s master private key"""
return str(wallet.keystore.get_master_private_key(password))
@command('')
async def convert_xkey(self, xkey, xtype):
"""Convert xtype of a master key. e.g. xpub -> ypub"""
try:
node = BIP32Node.from_xkey(xkey)
except:
raise Exception('xkey should be a master public/private key')
return node._replace(xtype=xtype).to_xkey()
@command('wp')
async def getseed(self, password=None, wallet: Abstract_Wallet = None):
"""Get seed phrase. Print the generation seed of your wallet."""
s = wallet.get_seed(password)
return s
@command('wp')
async def importprivkey(self, privkey, password=None, wallet: Abstract_Wallet = None):
"""Import a private key."""
if not wallet.can_import_privkey():
return "Error: This type of wallet cannot import private keys. Try to create a new wallet with that key."
try:
addr = wallet.import_private_key(privkey, password)
out = "Keypair imported: " + addr
except Exception as e:
out = "Error: " + repr(e)
return out
def _resolver(self, x, wallet):
if x is None:
return None
out = wallet.contacts.resolve(x)
if out.get('type') == 'openalias' and self.nocheck is False and out.get('validated') is False:
raise Exception('cannot verify alias', x)
return out['address']
@command('n')
async def sweep(self, privkey, destination, fee=None, nocheck=False, imax=100):
"""Sweep private keys. Returns a transaction that spends UTXOs from
privkey to a destination address. The transaction is not
broadcasted."""
from .wallet import sweep
tx_fee = satoshis(fee)
privkeys = privkey.split()
self.nocheck = nocheck
#dest = self._resolver(destination)
tx = await sweep(
privkeys,
network=self.network,
config=self.config,
to_address=destination,
fee=tx_fee,
imax=imax,
)
return tx.serialize() if tx else None
@command('wp')
async def signmessage(self, address, message, password=None, wallet: Abstract_Wallet = None):
"""Sign a message with a key. Use quotes if your message contains
whitespaces"""
sig = wallet.sign_message(address, message, password)
return base64.b64encode(sig).decode('ascii')
@command('')
async def verifymessage(self, address, signature, message):
"""Verify a signature."""
sig = base64.b64decode(signature)
message = util.to_bytes(message)
return ecc.verify_message_with_address(address, sig, message)
@command('wp')
async def payto(self, destination, amount, fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None,
nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, addtransaction=False, wallet: Abstract_Wallet = None):
"""Create a transaction. """
self.nocheck = nocheck
tx_fee = satoshis(fee)
domain_addr = from_addr.split(',') if from_addr else None
domain_coins = from_coins.split(',') if from_coins else None
change_addr = self._resolver(change_addr, wallet)
domain_addr = None if domain_addr is None else map(self._resolver, domain_addr, repeat(wallet))
amount_sat = satoshis(amount)
outputs = [PartialTxOutput.from_address_and_value(destination, amount_sat)]
tx = wallet.create_transaction(
outputs,
fee=tx_fee,
feerate=feerate,
change_addr=change_addr,
domain_addr=domain_addr,
domain_coins=domain_coins,
unsigned=unsigned,
rbf=rbf,
password=password,
locktime=locktime)
result = tx.serialize()
if addtransaction:
await self.addtransaction(result, wallet=wallet)
return result
@command('wp')
async def paytomany(self, outputs, fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None,
nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, addtransaction=False, wallet: Abstract_Wallet = None):
"""Create a multi-output transaction. """
self.nocheck = nocheck
tx_fee = satoshis(fee)
domain_addr = from_addr.split(',') if from_addr else None
domain_coins = from_coins.split(',') if from_coins else None
change_addr = self._resolver(change_addr, wallet)
domain_addr = None if domain_addr is None else map(self._resolver, domain_addr, repeat(wallet))
final_outputs = []
for address, amount in outputs:
address = self._resolver(address, wallet)
amount_sat = satoshis(amount)
final_outputs.append(PartialTxOutput.from_address_and_value(address, amount_sat))
tx = wallet.create_transaction(
final_outputs,
fee=tx_fee,
feerate=feerate,
change_addr=change_addr,
domain_addr=domain_addr,
domain_coins=domain_coins,
unsigned=unsigned,
rbf=rbf,
password=password,
locktime=locktime)
result = tx.serialize()
if addtransaction:
await self.addtransaction(result, wallet=wallet)
return result
@command('wp')
async def name_new(self, identifier=None, name_encoding='ascii', commitment=None, destination=None, amount=0.0, outputs=[], fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None, nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, allow_existing=False, wallet: Abstract_Wallet = None):
"""Create a name pre-registration transaction. """
self.nocheck = nocheck
name_encoding = Encoding(name_encoding)
if identifier is None and commitment is None:
raise Exception("Must specify identifier or commitment")
if identifier is not None and commitment is not None:
raise Exception("Must not specify both identifier and commitment")
if identifier is not None and not allow_existing:
name_exists = True
try:
show = await self.name_show(identifier, name_encoding=name_encoding.value, value_encoding='hex')
except NameNotFoundError:
name_exists = False
except NameSemiExpiredError:
pass
if name_exists:
raise NameAlreadyExistsError("The name is already registered")
tx_fee = satoshis(fee)
domain_addr = from_addr.split(',') if from_addr else None
domain_coins = from_coins.split(',') if from_coins else None
change_addr = self._resolver(change_addr, wallet)
domain_addr = None if domain_addr is None else map(self._resolver, domain_addr, repeat(wallet))
if identifier is not None:
identifier_bytes = name_from_str(identifier, name_encoding)
validate_identifier_length(identifier_bytes)
memo = "Pre-Registration: " + format_name_identifier(identifier_bytes)
else:
commitment_bytes = bfh(commitment)
validate_commitment_length(commitment_bytes)
memo = "Pre-Registration: " + commitment
if destination is None:
request = await self.add_request(None, memo=memo, wallet=wallet)
destination = request['address']
if identifier is not None:
name_op, salt = build_name_new(identifier_bytes, address=destination, password=password, wallet=wallet)
salt_hex = bh2u(salt)
commitment = bh2u(name_op["commitment"])
else:
name_op, salt = {"op": OP_NAME_NEW, "commitment": commitment_bytes}, None
salt_hex = None
final_outputs = []
for o_address, o_amount in outputs:
o_address = self._resolver(o_address, wallet)
amount_sat = satoshis(o_amount)
final_outputs.append(PartialTxOutput.from_address_and_value(o_address, amount_sat))
destination = self._resolver(destination, wallet)
amount_sat = satoshis(amount)
name_output = PartialTxOutput.from_address_and_value(destination, amount_sat)
name_output.add_name_op(name_op)
final_outputs.append(name_output)
tx = wallet.create_transaction(
final_outputs,
fee=tx_fee,
feerate=feerate,
change_addr=change_addr,
domain_addr=domain_addr,
domain_coins=domain_coins,
unsigned=unsigned,
rbf=rbf,
password=password,
locktime=locktime)
return {"tx": tx.serialize(), "txid": tx.txid(), "salt": salt_hex, "commitment": commitment}
@command('wp')
async def name_firstupdate(self, identifier, salt=None, name_new_txid=None, value="", name_encoding='ascii', value_encoding='ascii', destination=None, amount=0.0, outputs=[], fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None, nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, allow_early=False, wallet: Abstract_Wallet = None):
"""Create a name registration transaction. """
self.nocheck = nocheck
name_encoding = Encoding(name_encoding)
value_encoding = Encoding(value_encoding)
tx_fee = satoshis(fee)
domain_addr = from_addr.split(',') if from_addr else None
domain_coins = from_coins.split(',') if from_coins else None
change_addr = self._resolver(change_addr, wallet)
domain_addr = None if domain_addr is None else map(self._resolver, domain_addr, repeat(wallet))
identifier_bytes = name_from_str(identifier, name_encoding)
validate_identifier_length(identifier_bytes)
value_bytes = name_from_str(value, value_encoding)
validate_value_length(value_bytes)
if salt is None:
if name_new_txid is None:
txid_filter = None
else:
txid_filter = [name_new_txid]
# Get a list of inputs. If the user supplied an input txid, use
# that as a hint.
name_inputs = wallet.get_spendable_coins(None, include_names=True, only_uno_txids=txid_filter)
# Check all the inputs to see if any of them have a commitment that
# matches the salt we can calculate.
for new_input in name_inputs:
# Skip any inputs that aren't a name_new.
if new_input.name_op is None:
continue
new_op = new_input.name_op
if new_op["op"] != OP_NAME_NEW:
continue
# Calculate the salt
address = new_input.address
salt_bytes = wallet.name_salt(identifier_bytes, address, password)
# Calculate the commitment, and check if it matches
commitment = build_name_commitment(identifier_bytes, salt_bytes)
if commitment == new_op["commitment"]:
# We found the commitment.
name_new_txid = new_input.prevout.txid.hex()
break
else:
raise NamePreRegistrationNotFound("name_new input with matching commitment not found")
else:
salt_bytes = bfh(salt)
validate_salt_length(salt_bytes)
if not allow_early:
conf = wallet.get_tx_height(name_new_txid).conf
if conf < 12:
remaining_conf = 12 - conf
raise NamePreRegistrationPendingError("The name pre-registration is still pending; wait " + str(remaining_conf) + " more blocks")
name_op = {"op": OP_NAME_FIRSTUPDATE, "name": identifier_bytes, "salt": salt_bytes, "value": value_bytes}
memo = "Registration: " + format_name_identifier(identifier_bytes)
if destination is None:
request = await self.add_request(None, memo=memo, wallet=wallet)
destination = request['address']
final_outputs = []
for o_address, o_amount in outputs:
o_address = self._resolver(o_address, wallet)
amount_sat = satoshis(o_amount)
final_outputs.append(PartialTxOutput.from_address_and_value(o_address, amount_sat))
destination = self._resolver(destination, wallet)
amount_sat = satoshis(amount)
name_output = PartialTxOutput.from_address_and_value(destination, amount_sat)
name_output.add_name_op(name_op)
final_outputs.append(name_output)
tx = wallet.create_transaction(
final_outputs,
fee=tx_fee,
feerate=feerate,
change_addr=change_addr,
domain_addr=domain_addr,
domain_coins=domain_coins,
unsigned=unsigned,
rbf=rbf,
password=password,
locktime=locktime,
name_input_txids=[name_new_txid])
return tx.serialize()
@command('wpn')
async def name_update(self, identifier, value=None, name_encoding='ascii', value_encoding='ascii', destination=None, amount=0.0, outputs=[], fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None, nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, wallet: Abstract_Wallet = None):
"""Create a name update transaction. """
self.nocheck = nocheck
name_encoding = Encoding(name_encoding)
value_encoding = Encoding(value_encoding)
tx_fee = satoshis(fee)
domain_addr = from_addr.split(',') if from_addr else None
domain_coins = from_coins.split(',') if from_coins else None
change_addr = self._resolver(change_addr, wallet)
domain_addr = None if domain_addr is None else map(self._resolver, domain_addr, repeat(wallet))
# Allow renewing a name without any value changes by omitting the
# value.
renew = False
if value is None:
list_results = await self.name_list(identifier, name_encoding=name_encoding.value, value_encoding=value_encoding.value, wallet=wallet)
list_results = list_results[0]
# This check is in place to prevent an attack where an ElectrumX
# server supplies an unconfirmed name_update transaction with a
# malicious value and then tricks the wallet owner into signing a
# name renewal with that malicious value. expires_in is None when
# the transaction has 0 confirmations.
expires_in = list_results["expires_in"]
if expires_in is None or expires_in > constants.net.NAME_EXPIRATION - 12:
raise NameUpdatedTooRecentlyError("Name was updated too recently to safely determine current value. Either wait or specify an explicit value.")
value = list_results["value"]
renew = True
identifier_bytes = name_from_str(identifier, name_encoding)
validate_identifier_length(identifier_bytes)
value_bytes = name_from_str(value, value_encoding)
validate_value_length(value_bytes)
name_op = {"op": OP_NAME_UPDATE, "name": identifier_bytes, "value": value_bytes}
memo = ("Renew: " if renew else "Update: ") + format_name_identifier(identifier_bytes)
if destination is None:
request = await self.add_request(None, memo=memo, wallet=wallet)
destination = request['address']
final_outputs = []
for o_address, o_amount in outputs:
o_address = self._resolver(o_address, wallet)
amount_sat = satoshis(o_amount)
final_outputs.append(PartialTxOutput.from_address_and_value(o_address, amount_sat))
destination = self._resolver(destination, wallet)
amount_sat = satoshis(amount)
name_output = PartialTxOutput.from_address_and_value(destination, amount_sat)
name_output.add_name_op(name_op)
final_outputs.append(name_output)
tx = wallet.create_transaction(
final_outputs,
fee=tx_fee,
feerate=feerate,
change_addr=change_addr,
domain_addr=domain_addr,
domain_coins=domain_coins,