def do_export_history(self, wallet, fileName, is_csv):
     history = self.transactions
     lines = []
     for item in history:
         if is_csv:
             lines.append([
                 item['txid'],
                 item.get('label', ''), item['confirmations'],
                 item['value'], item['date']
             ])
         else:
             lines.append(item)
     with open(fileName, "w+", encoding='utf-8') as f:
         if is_csv:
             import csv
             transaction = csv.writer(f, lineterminator='\n')
             transaction.writerow([
                 "transaction_hash", "label", "confirmations", "value",
                 "timestamp"
             ])
             for line in lines:
                 transaction.writerow(line)
         else:
             from electrum.util import json_encode
             f.write(json_encode(history))
Example #2
0
 def do_export_history(self, file_name, is_csv):
     hist = self.wallet.get_detailed_history(fx=self.parent.fx)
     txns = hist['transactions']
     lines = []
     if is_csv:
         for item in txns:
             lines.append([
                 item['txid'],
                 item.get('label', ''), item['confirmations'],
                 item['bc_value'],
                 item.get('fiat_value', ''),
                 item.get('fee', ''),
                 item.get('fiat_fee', ''), item['date']
             ])
     with open(file_name, "w+", encoding='utf-8') as f:
         if is_csv:
             import csv
             transaction = csv.writer(f, lineterminator='\n')
             transaction.writerow([
                 "transaction_hash", "label", "confirmations", "value",
                 "fiat_value", "fee", "fiat_fee", "timestamp"
             ])
             for line in lines:
                 transaction.writerow(line)
         else:
             from electrum.util import json_encode
             f.write(json_encode(txns))
Example #3
0
 def do_export_history(self, file_name, is_csv):
     history = self.transactions
     lines = []
     if is_csv:
         for item in history:
             lines.append([item['txid'],
                           item.get('label', ''),
                           item['confirmations'],
                           item['value'],
                           item.get('fiat_value', ''),
                           item.get('fee', ''),
                           item.get('fiat_fee', ''),
                           item['date']])
     with open(file_name, "w+", encoding='utf-8') as f:
         if is_csv:
             import csv
             transaction = csv.writer(f, lineterminator='\n')
             transaction.writerow(["transaction_hash",
                                   "label",
                                   "confirmations",
                                   "value",
                                   "fiat_value",
                                   "fee",
                                   "fiat_fee",
                                   "timestamp"])
             for line in lines:
                 transaction.writerow(line)
         else:
             from electrum.util import json_encode
             f.write(json_encode(history))
async def f():
    try:
        sh = bitgesell.address_to_scripthash(addr)
        hist = await network.get_history_for_scripthash(sh)
        print_msg(json_encode(hist))
    finally:
        stopping_fut.set_result(1)
Example #5
0
 def do_export_history(self, file_name, is_csv):
     hist = self.wallet.get_full_history(domain=self.get_domain(),
                                         from_timestamp=None,
                                         to_timestamp=None,
                                         fx=self.parent.fx,
                                         show_fees=True)
     txns = hist['transactions']
     lines = []
     if is_csv:
         for item in txns:
             lines.append([item['txid'],
                           item.get('label', ''),
                           item['confirmations'],
                           item['value'],
                           item.get('fiat_value', ''),
                           item.get('fee', ''),
                           item.get('fiat_fee', ''),
                           item['date']])
     with open(file_name, "w+", encoding='utf-8') as f:
         if is_csv:
             import csv
             transaction = csv.writer(f, lineterminator='\n')
             transaction.writerow(["transaction_hash",
                                   "label",
                                   "confirmations",
                                   "value",
                                   "fiat_value",
                                   "fee",
                                   "fiat_fee",
                                   "timestamp"])
             for line in lines:
                 transaction.writerow(line)
         else:
             from electrum.util import json_encode
             f.write(json_encode(txns))
Example #6
0
async def f():
    try:
        sh = bitcoin.address_to_scripthash(addr)
        hist = await network.get_history_for_scripthash(sh)
        print_msg(json_encode(hist))
    finally:
        stopping_fut.set_result(1)
    def runCommand(self):
        command = self.getCommand()
        self.addToHistory(command)

        command = self.getConstruct(command)

        if command:
            tmp_stdout = sys.stdout

            class stdoutProxy():
                def __init__(self, write_func):
                    self.write_func = write_func
                    self.skip = False

                def flush(self):
                    pass

                def write(self, text):
                    if not self.skip:
                        stripped_text = text.rstrip('\n')
                        self.write_func(stripped_text)
                        QtCore.QCoreApplication.processEvents()
                    self.skip = not self.skip

            if type(self.namespace.get(command)) == type(lambda: None):
                self.appendPlainText(
                    "'%s' is a function. Type '%s()' to use it in the Python console."
                    % (command, command))
                self.newPrompt()
                return

            sys.stdout = stdoutProxy(self.appendPlainText)
            try:
                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_msg(result)
                        else:
                            self.appendPlainText(repr(result))
                except SyntaxError:
                    # exec is generally considered bad practice. use it wisely!
                    exec command in self.namespace
            except SystemExit:
                self.close()
            except Exception:
                traceback_lines = traceback.format_exc().split('\n')
                # Remove traceback mentioning this file, and a linebreak
                for i in (3, 2, 1, -1):
                    traceback_lines.pop(i)
                self.appendPlainText('\n'.join(traceback_lines))
            sys.stdout = tmp_stdout
        self.newPrompt()
        self.set_json(False)
Example #8
0
async def f():
    try:
        await network.interface.session.subscribe(
            'blockchain.headers.subscribe', [], header_queue)
        # 3. wait for results
        while network.is_connected():
            header = await header_queue.get()
            print_msg(json_encode(header))
    finally:
        stopping_fut.set_result(1)
Example #9
0
    def runCommand(self):
        command = self.getCommand()
        self.addToHistory(command)

        command = self.getConstruct(command)

        if command:
            tmp_stdout = sys.stdout

            class stdoutProxy():
                def __init__(self, write_func):
                    self.write_func = write_func
                    self.skip = False

                def flush(self):
                    pass

                def write(self, text):
                    if not self.skip:
                        stripped_text = text.rstrip('\n')
                        self.write_func(stripped_text)
                        QtCore.QCoreApplication.processEvents()
                    self.skip = not self.skip

            if type(self.namespace.get(command)) == type(lambda:None):
                self.appendPlainText("'{}' is a function. Type '{}()' to use it in the Python console."
                                     .format(command, command))
                self.newPrompt()
                return

            sys.stdout = stdoutProxy(self.appendPlainText)
            try:
                try:
                    # eval is generally considered bad practice. use it wisely!
                    result = eval(command, self.namespace, self.namespace)
                    if result != None:
                        if self.is_json:
                            util.print_msg(util.json_encode(result))
                        else:
                            self.appendPlainText(repr(result))
                except SyntaxError:
                    # exec is generally considered bad practice. use it wisely!
                    exec(command, self.namespace, self.namespace)
            except SystemExit:
                self.close()
            except BaseException:
                traceback_lines = traceback.format_exc().split('\n')
                # Remove traceback mentioning this file, and a linebreak
                for i in (3,2,1,-1):
                    traceback_lines.pop(i)
                self.appendPlainText('\n'.join(traceback_lines))
            sys.stdout = tmp_stdout
        self.newPrompt()
        self.set_json(False)
async def f():
    try:
        def get_account_xpub(account_path):
            root_seed = bip39_to_seed(mnemonic, passphrase)
            root_node = BIP32Node.from_rootseed(root_seed, xtype="standard")
            account_node = root_node.subkey_at_private_derivation(account_path)
            account_xpub = account_node.to_xpub()
            return account_xpub
        active_accounts = await account_discovery(network, get_account_xpub)
        print_msg(json_encode(active_accounts))
    finally:
        stopping_fut.set_result(1)
# A simple script that connects to a server and displays block headers

import time
import sys

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

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

# wait until connected
while network.is_connecting():
    time.sleep(0.1)

if not network.is_connected():
    print_msg("daemon is not connected")
    sys.exit(1)

# 2. send the subscription
callback = lambda response: print_msg(json_encode(response.get('result')))
network.send([('server.version',["block_headers script", "1.2"])], callback)
network.subscribe_to_headers(callback)

# 3. wait for results
while network.is_connected():
    time.sleep(1)
Example #12
0
#!/usr/bin/env python3

# A simple script that connects to a server and displays block headers

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

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

# wait until connected
while network.is_connecting():
    time.sleep(0.1)

if not network.is_connected():
    print_msg("daemon is not connected")
    sys.exit(1)

# 2. send the subscription
callback = lambda response: print_msg(json_encode(response.get('result')))
network.send([('server.version',["block_headers script", "1.2"])], callback)
network.subscribe_to_headers(callback)

# 3. wait for results
while network.is_connected():
    time.sleep(1)
Example #13
0
#!/usr/bin/env python3

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

try:
    addr = sys.argv[1]
except Exception:
    print("usage: get_history <bitcoin_address>")
    sys.exit(1)

n = Network()
n.start()
_hash = bitcoin.address_to_scripthash(addr)
h = n.get_history_for_scripthash(_hash)
print_msg(json_encode(h))
Example #14
0
                result = server.daemon(config_options)
        else:
            server = daemon.get_server(config)
            if server is not None:
                result = server.daemon(config_options)
            else:
                print_msg("Daemon not running")
                sys.exit(1)
    else:
        # command line
        server = daemon.get_server(config)
        init_cmdline(config_options, server)
        if server is not None:
            result = server.run_cmdline(config_options)
        else:
            cmd = known_commands[cmdname]
            if cmd.requires_network:
                print_msg("Daemon not running; try 'electrum daemon start'")
                sys.exit(1)
            else:
                plugins = init_plugins(config, 'cmdline')
                result = run_offline_command(config, config_options, plugins)
                # print result
    if isinstance(result, str):
        print_msg(result)
    elif type(result) is dict and result.get('error'):
        print_stderr(result.get('error'))
    elif result is not None:
        print_msg(json_encode(result))
    sys.exit(0)
Example #15
0
#!/usr/bin/env python3

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

try:
    addr = sys.argv[1]
except Exception:
    print("usage: get_history <bitcore_address>")
    sys.exit(1)

n = Network()
n.start()
_hash = bitcoin.address_to_scripthash(addr)
h = n.get_history_for_scripthash(_hash)
print_msg(json_encode(h))
Example #16
0
def launch():
    # The hook will only be used in the Qt GUI right now
    util.setup_thread_excepthook()
    # on osx, delete Process Serial Number arg generated for apps launched in Finder
    sys.argv = list(filter(lambda x: not x.startswith('-psn'), sys.argv))

    # old 'help' syntax
    if len(sys.argv) > 1 and sys.argv[1] == 'help':
        sys.argv.remove('help')
        sys.argv.append('-h')

    # read arguments from stdin pipe and prompt
    for i, arg in enumerate(sys.argv):
        if arg == '-':
            if not sys.stdin.isatty():
                sys.argv[i] = sys.stdin.read()
                break
            else:
                raise BaseException('Cannot get argument from stdin')
        elif arg == '?':
            sys.argv[i] = input("Enter argument:")
        elif arg == ':':
            sys.argv[i] = prompt_password('Enter argument (will not echo):', False)

    # parse command line
    parser = get_parser()
    args = parser.parse_args()

    # config is an object passed to the various constructors (wallet, interface, gui)
    if is_android:
        config_options = {
            'verbose': True,
            'cmd': 'gui',
            'gui': 'kivy',
        }
    else:
        config_options = args.__dict__
        f = lambda key: config_options[key] is not None and key not in config_variables.get(args.cmd, {}).keys()
        config_options = {key: config_options[key] for key in filter(f, config_options.keys())}
        if config_options.get('server'):
            config_options['auto_connect'] = False

    config_options['cwd'] = os.getcwd()

    # fixme: this can probably be achieved with a runtime hook (pyinstaller)
    if is_bundle and os.path.exists(os.path.join(sys._MEIPASS, 'is_portable')):
        config_options['portable'] = True

#if config_options.get('portable'):
    config_options['electrum_path'] = os.path.join(managers.shared().documentsDirectory(), 'electrum_data')

    # kivy sometimes freezes when we write to sys.stderr
    set_verbosity(config_options.get('verbose') and config_options.get('gui')!='kivy')

    # check uri
    '''
    uri = config_options.get('url')
    if uri:
        if not uri.startswith('bitcoin:'):
            print_stderr('unknown command:', uri)
            sys.exit(1)
        config_options['url'] = uri
    '''
    
    # todo: defer this to gui
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')

    if config.get('testnet'):
        constants.set_testnet()

    # run non-RPC commands separately
    if cmdname in ['create', 'restore']:
        run_non_RPC(config)
        sys.exit(0)

    if cmdname == 'gui':
        fd, server = daemon.get_fd_or_server(config)
        if fd is not None:
            plugins = init_plugins(config, config.get('gui', 'qt'))
            d = daemon.Daemon(config, fd, True)
            d.start()
            d.init_gui(config, plugins)
            sys.exit(0)
        else:
            result = server.gui(config_options)

    elif cmdname == 'daemon':
        subcommand = config.get('subcommand')
        if subcommand in ['load_wallet']:
            init_daemon(config_options)

        if subcommand in [None, 'start']:
            fd, server = daemon.get_fd_or_server(config)
            if fd is not None:
                if subcommand == 'start':
                    pid = os.fork()
                    if pid:
                        print_stderr("starting daemon (PID %d)" % pid)
                        sys.exit(0)
                init_plugins(config, 'cmdline')
                d = daemon.Daemon(config, fd, False)
                d.start()
                if config.get('websocket_server'):
                    from electrum import websockets
                    websockets.WebSocketServer(config, d.network).start()
                if config.get('requests_dir'):
                    path = os.path.join(config.get('requests_dir'), 'index.html')
                    if not os.path.exists(path):
                        print("Requests directory not configured.")
                        print("You can configure it using https://github.com/spesmilo/electrum-merchant")
                        sys.exit(1)
                d.join()
                sys.exit(0)
            else:
                result = server.daemon(config_options)
        else:
            server = daemon.get_server(config)
            if server is not None:
                result = server.daemon(config_options)
            else:
                print_msg("Daemon not running")
                sys.exit(1)
    else:
        # command line
        server = daemon.get_server(config)
        init_cmdline(config_options, server)
        if server is not None:
            result = server.run_cmdline(config_options)
        else:
            cmd = known_commands[cmdname]
            if cmd.requires_network:
                print_msg("Daemon not running; try 'electrum daemon start'")
                sys.exit(1)
            else:
                plugins = init_plugins(config, 'cmdline')
                result = run_offline_command(config, config_options, plugins)
                # print result
    if isinstance(result, str):
        print_msg(result)
    elif type(result) is dict and result.get('error'):
        print_stderr(result.get('error'))
    elif result is not None:
        print_msg(json_encode(result))
    sys.exit(0)