Skip to content

Commit

Permalink
Various fixes for command line. Make 'payto' command require network (f…
Browse files Browse the repository at this point in the history
…ixes #1525)
  • Loading branch information
ecdsa committed Oct 29, 2015
1 parent 079cb31 commit bb7b088
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 33 deletions.
23 changes: 9 additions & 14 deletions electrum
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ if is_bundle or is_local or is_android:

from electrum import util
from electrum import SimpleConfig, Network, Wallet, WalletStorage
from electrum.util import print_msg, print_error, print_stderr, print_json, set_verbosity, InvalidPassword
from electrum.util import print_msg, print_error, print_stderr, json_encode, json_decode, set_verbosity, InvalidPassword
from electrum.plugins import Plugins, run_hook, always_hook
from electrum.commands import get_parser, known_commands, Commands, config_variables

Expand Down Expand Up @@ -251,15 +251,9 @@ def run_command(config, network, password):
# arguments passed to function
args = map(lambda x: config.get(x), cmd.params)
# decode json arguments
def json_decode(x):
try:
return json.loads(x)
except:
return x
args = map(json_decode, args)
# options
args += map(lambda x: config.get(x), cmd.options)

cmd_runner = Commands(config, wallet, network)
cmd_runner.password = password
func = getattr(cmd_runner, cmd.name)
Expand Down Expand Up @@ -467,13 +461,15 @@ if __name__ == '__main__':
gui_name = config.get('gui', 'qt') if cmd_name == 'gui' else 'cmdline'
plugins = Plugins(config, is_bundle or is_local or is_android, gui_name)

# get password if needed
# run command offline
if cmd_name not in ['gui', 'daemon']:
cmd, password = init_cmdline(config)
if not cmd.requires_network or config.get('offline'):
result = run_command(config, None, password)
print_json(result)
sys.exit(1)
print_msg(json_encode(result))
sys.exit(0)
else:
config_options['password'] = password

# check if daemon is running
s = get_daemon(config, False)
Expand All @@ -485,11 +481,10 @@ if __name__ == '__main__':
s.close()
if type(result) in [str, unicode]:
print_msg(result)
elif type(result) is dict and result.get('error'):
print_stderr(result.get('error'))
elif result is not None:
if type(result) is dir and result.get('error'):
print_stderr(result.get('error'))
else:
print_json(result)
print_msg(json_encode(result))
sys.exit(0)

# daemon is not running
Expand Down
3 changes: 2 additions & 1 deletion gui/qt/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,10 @@ def write(self, text):
try:
# eval is generally considered bad practice. use it wisely!
result = eval(command, self.namespace, self.namespace)
result = util.json_encode(result)
if result != None:
if self.is_json:
util.print_json(result)
util.print_msg(result)
else:
self.appendPlainText(repr(result))
except SyntaxError:
Expand Down
2 changes: 1 addition & 1 deletion lib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from version import ELECTRUM_VERSION
from util import format_satoshis, print_msg, print_json, print_error, set_verbosity
from util import format_satoshis, print_msg, print_error, set_verbosity
from wallet import Synchronizer, WalletStorage
from wallet import Wallet, Imported_Wallet
from network import Network, DEFAULT_SERVERS, DEFAULT_PORTS, pick_random_server
Expand Down
8 changes: 4 additions & 4 deletions lib/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,14 +418,14 @@ def _mktx(self, outputs, fee, change_addr, domain, nocheck, unsigned):
self.wallet.sign_transaction(tx, self.password)
return tx

@command('wp')
@command('wpn')
def payto(self, destination, amount, tx_fee=None, from_addr=None, change_addr=None, nocheck=False, unsigned=False, deserialized=False):
"""Create a transaction. """
domain = [from_addr] if from_addr else None
tx = self._mktx([(destination, amount)], tx_fee, change_addr, domain, nocheck, unsigned)
return tx.deserialize() if deserialized else tx

@command('wp')
@command('wpn')
def paytomany(self, outputs, tx_fee=None, from_addr=None, change_addr=None, nocheck=False, unsigned=False, deserialized=False):
"""Create a multi-output transaction. """
domain = [from_addr] if from_addr else None
Expand Down Expand Up @@ -657,8 +657,8 @@ def clearrequests(self):
'pubkeys': json.loads,
'inputs': json.loads,
'outputs': json.loads,
'tx_fee': lambda x: Decimal(x) if x is not None else None,
'amount': lambda x: Decimal(x) if x!='!' else '!',
'tx_fee': lambda x: float(x) if x is not None else None,
'amount': lambda x: float(x) if x!='!' else '!',
}

config_variables = {
Expand Down
10 changes: 7 additions & 3 deletions lib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,18 @@ def print_msg(*args):
sys.stdout.write(" ".join(args) + "\n")
sys.stdout.flush()

def print_json(obj):
def json_encode(obj):
try:
s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
except TypeError:
s = repr(obj)
sys.stdout.write(s + "\n")
sys.stdout.flush()
return s

def json_decode(x):
try:
return json.loads(x)
except:
return x

# decorator that prints execution time
def profiler(func):
Expand Down
9 changes: 5 additions & 4 deletions scripts/block_headers
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
# A simple script that connects to a server and displays block headers

import time
import electrum
from electrum import SimpleConfig, Network
from electrum.util import print_msg, json_encode

# start network
c = electrum.SimpleConfig()
network = electrum.Network(c)
c = SimpleConfig()
network = Network(c)
network.start()

# wait until connected
Expand All @@ -19,7 +20,7 @@ if not network.is_connected():
sys.exit(1)

# 2. send the subscription
callback = lambda response: electrum.print_json(response.get('result'))
callback = lambda response: print_msg(json_encode(response.get('result')))
network.send([('blockchain.headers.subscribe',[])], callback)

# 3. wait for results
Expand Down
5 changes: 3 additions & 2 deletions scripts/get_history
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python

import sys
from electrum import Network, print_json
from electrum import Network
from electrum.util import json_encode, print_msg

try:
addr = sys.argv[1]
Expand All @@ -12,4 +13,4 @@ except Exception:
n = Network()
n.start()
h = n.synchronous_get(('blockchain.address.get_history',[addr]))
print_json(h)
print_msg(json_encode(h))
9 changes: 5 additions & 4 deletions scripts/watch_address
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import sys
import time
import electrum
from electrum import SimpleConfig, Network
from electrum.util import print_msg, json_encode

try:
addr = sys.argv[1]
Expand All @@ -11,8 +12,8 @@ except Exception:
sys.exit(1)

# start network
c = electrum.SimpleConfig()
network = electrum.Network(c)
c = SimpleConfig()
network = Network(c)
network.start()

# wait until connected
Expand All @@ -24,7 +25,7 @@ if not network.is_connected():
sys.exit(1)

# 2. send the subscription
callback = lambda response: electrum.print_json(response.get('result'))
callback = lambda response: print_msg(json_encode(response.get('result')))
network.send([('blockchain.address.subscribe',[addr])], callback)

# 3. wait for results
Expand Down

0 comments on commit bb7b088

Please sign in to comment.