def test_can_set_options_set_in_user_config(self): another_path = tempfile.mkdtemp() fake_read_user = lambda _: {"electrum_path": self.electrum_dir} read_user_dir = lambda : self.user_dir config = SimpleConfig(options={}, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) config.set_key("electrum_path", another_path) self.assertEqual(another_path, config.get("electrum_path"))
def test_cannot_set_options_passed_by_command_line(self): fake_read_user = lambda _: {"electrum_path": "b"} read_user_dir = lambda : self.user_dir config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) config.set_key("electrum_path", "c") self.assertEqual(self.options.get("electrum_path"), config.get("electrum_path"))
def test_simple_config_user_config_is_used_if_others_arent_specified(self): """If no system-wide configuration and no command-line options are specified, the user configuration is used instead.""" fake_read_user = lambda _: {"electrum_path": self.electrum_dir} read_user_dir = lambda : self.user_dir config = SimpleConfig(options={}, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(self.options.get("electrum_path"), config.get("electrum_path"))
def test_simple_config_command_line_overrides_everything(self): """Options passed by command line override all other configuration sources""" fake_read_user = lambda _: {"electrum_path": "b"} read_user_dir = lambda : self.user_dir config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(self.options.get("electrum_path"), config.get("electrum_path"))
def test_fee_to_depth(self): config = SimpleConfig(self.options) config.mempool_fees = [[49, 100000], [10, 120000], [6, 150000], [5, 125000], [1, 36000000]] self.assertEqual(100000, config.fee_to_depth(500)) self.assertEqual(100000, config.fee_to_depth(50)) self.assertEqual(100000, config.fee_to_depth(49)) self.assertEqual(220000, config.fee_to_depth(48)) self.assertEqual(220000, config.fee_to_depth(10)) self.assertEqual(370000, config.fee_to_depth(9)) self.assertEqual(370000, config.fee_to_depth(6.5)) self.assertEqual(370000, config.fee_to_depth(6)) self.assertEqual(495000, config.fee_to_depth(5.5)) self.assertEqual(36495000, config.fee_to_depth(0.5))
def test_user_config_is_not_written_with_read_only_config(self): """The user config does not contain command-line options when saved.""" fake_read_user = lambda _: {"something": "a"} read_user_dir = lambda : self.user_dir self.options.update({"something": "c"}) config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) config.save_user_config() contents = None with open(os.path.join(self.electrum_dir, "config"), "r") as f: contents = f.read() result = ast.literal_eval(contents) result.pop('config_version', None) self.assertEqual({"something": "a"}, result)
def setUp(self): super(WalletTestCase, self).setUp() self.user_dir = tempfile.mkdtemp() self.config = SimpleConfig({'electrum_path': self.user_dir}) self.wallet_path = os.path.join(self.user_dir, "somewallet") self._saved_stdout = sys.stdout self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer
def make_address_electrum(mnemonic: str, second: str, num: int = 0, script: str = 'p2wpkh', path: str = 'wallet.db', remove: bool = True): if electrum is None: raise ImportError( 'Unable to import electrum. Follow README instructions.') if len(second) < MIN_LEN_PASSWORD: raise ValueError( f'Password too short {len(second)} < {MIN_LEN_PASSWORD}') script_types = ('p2pkh', 'p2wpkh', 'p2wpkh-p2sh') if script not in script_types: raise ValueError(f'Script {script} must be noe of {script_types}') if os.path.exists(path): os.unlink(path) language = 'english' seed = Mnemonic(language).to_seed(mnemonic).hex() derivation = None if script == 'p2wpkh': derivation = "m/84'/0'/0'" elif script == 'p2wpkh-p2sh': derivation = "m/49'/0'/0'" elif script == 'p2pkh': script = 'standard' derivation = "m/44'/0'/0'" ks = keystore.from_bip39_seed(mnemonic, second, derivation, xtype=script) db = WalletDB('', manual_upgrades=False) db.put('keystore', ks.dump()) db.put('wallet_type', 'standard') storage = WalletStorage(path) wallet = Wallet(db, storage, config=SimpleConfig()) if not storage.file_exists(): wallet.update_password(old_pw=None, new_pw=second, encrypt_storage=True) wallet.synchronize() wallet.save_db() addr = wallet.get_receiving_addresses()[num] wif = wallet.export_private_key(addr, password=second) if remove: os.unlink(path) return AddressResult(address=addr, wif=wif, num=num)
def setUpClass(cls): super().setUpClass() from electrum.plugin import Plugins from electrum.simple_config import SimpleConfig cls.__electrum_path = tempfile.mkdtemp() config = SimpleConfig({'electrum_path': cls.__electrum_path}) gui_name = 'cmdline' # TODO it's probably wasteful to load all plugins... only need Trezor Plugins(config, gui_name)
def start_it(): global network, fx thread = threading.currentThread() asyncio.set_event_loop(asyncio.new_event_loop()) config = SimpleConfig() config.set_key("currency", "USD") config.set_key("use_exchange_rate", True) daemon = Daemon(config, listen_jsonrpc=False) network = daemon.network fx = daemon.fx while thread.is_running: pass
def test_simple_config_key_rename(self): """auto_cycle was renamed auto_connect""" fake_read_user = lambda _: {"auto_cycle": True} read_user_dir = lambda: self.user_dir config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(config.get("auto_connect"), True) self.assertEqual(config.get("auto_cycle"), None) fake_read_user = lambda _: {"auto_connect": False, "auto_cycle": True} config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(config.get("auto_connect"), False) self.assertEqual(config.get("auto_cycle"), None)
def qr_input(self): from electrum import qrscanner try: data = qrscanner.scan_barcode( SimpleConfig.get_instance().get_video_device()) except BaseException as e: self.show_error(repr(e)) data = '' if not data: data = '' if self.allow_multi: new_text = self.text() + data + '\n' else: new_text = data self.setText(new_text) return data
def load_wallet(xpub): if xpub in wallets: return wallets[xpub] config = SimpleConfig() command_runner = Commands(config, wallet=None, network=network) # get wallet on disk wallet_dir = os.path.dirname(config.get_wallet_path()) wallet_path = os.path.join(wallet_dir, xpub) if not os.path.exists(wallet_path): config.set_key('wallet_path', wallet_path) command_runner.restore(xpub) storage = WalletStorage(wallet_path) wallet = Wallet(storage) wallet.start_network(network) command_runner.wallet = wallet wallets[xpub] = command_runner return command_runner
def __init__(self, data, parent=None, title="", show_text=False): WindowModalDialog.__init__(self, parent, title) vbox = QVBoxLayout() qrw = QRCodeWidget(data) vbox.addWidget(qrw, 1) if show_text: text = QTextEdit() text.setText(data) text.setReadOnly(True) vbox.addWidget(text) hbox = QHBoxLayout() hbox.addStretch(1) config = SimpleConfig.get_instance() if config: filename = os.path.join(config.path, "qrcode.png") def print_qr(): p = qrw.grab() # FIXME also grabs neutral colored padding p.save(filename, 'png') self.show_message(_("QR code saved to file") + " " + filename) def copy_to_clipboard(): p = qrw.grab() QApplication.clipboard().setPixmap(p) self.show_message(_("QR code copied to clipboard")) b = QPushButton(_("Copy")) hbox.addWidget(b) b.clicked.connect(copy_to_clipboard) b = QPushButton(_("Save")) hbox.addWidget(b) b.clicked.connect(print_qr) b = QPushButton(_("Close")) hbox.addWidget(b) b.clicked.connect(self.accept) b.setDefault(True) vbox.addLayout(hbox) self.setLayout(vbox)
def test_simple_config_key_rename(self): """auto_cycle was renamed auto_connect""" fake_read_user = lambda _: {"auto_cycle": True} read_user_dir = lambda : self.user_dir config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(config.get("auto_connect"), True) self.assertEqual(config.get("auto_cycle"), None) fake_read_user = lambda _: {"auto_connect": False, "auto_cycle": True} config = SimpleConfig(options=self.options, read_user_config_function=fake_read_user, read_user_dir_function=read_user_dir) self.assertEqual(config.get("auto_connect"), False) self.assertEqual(config.get("auto_cycle"), None)
def main(): cleanup_tmp_dir() config_options = { 'verbose': True, 'cmd': 'gui', 'gui': 'ios_native', 'cwd': os.getcwd(), } set_verbosity(str(config_options.get('verbose'))) for k, v in config_options.items(): print("config[%s] = %s" % (str(k), str(v))) constants.set_mainnet() config = SimpleConfig(config_options, read_user_dir_function=get_user_dir) gui = ElectrumGui(config) gui.main() return "Bitcoin FTW!"
def setUp(self): super().setUp() self.asyncio_loop, self._stop_loop, self._loop_thread = create_and_start_event_loop( ) self.config = SimpleConfig({'electrum_path': self.electrum_path})
import sys import asyncio import time from electrum.simple_config import SimpleConfig from electrum import constants from electrum.daemon import Daemon from electrum.storage import WalletStorage from electrum.wallet import Wallet, create_new_wallet from electrum.commands import Commands, known_commands from electrum.network import filter_protocol, Network from electrum.util import create_and_start_event_loop, log_exceptions from electrum.simple_config import SimpleConfig # use ~/.electrum/testnet as datadir config = SimpleConfig({"testnet": True, "fee_per_kb": 10000, "dynamic_fees": False}) # set testnet magic bytes constants.set_testnet() # set up daemon daemon = Daemon(config, listen_jsonrpc=False) network = daemon.network # get wallet on disk wallet_dir = os.path.dirname(config.get_wallet_path()) print("Wallet dir: "+ wallet_dir) wallet_path = os.path.join(wallet_dir, "wallet_lib") if not os.path.exists(wallet_path): create_new_wallet(path=wallet_path, segwit=True)
import sys import asyncio from electrum import bitgesell from electrum.network import Network from electrum.util import json_encode, print_msg, create_and_start_event_loop, log_exceptions from electrum.simple_config import SimpleConfig try: addr = sys.argv[1] except Exception: print("usage: get_history <bitgesell_address>") sys.exit(1) config = SimpleConfig() loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network(config) network.start() @log_exceptions 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)
def test_depth_target_to_fee(self): config = SimpleConfig(self.options) config.mempool_fees = [[49, 100110], [10, 121301], [6, 153731], [5, 125872], [1, 36488810]] self.assertEqual(400000, config.depth_target_to_fee(1000000)) self.assertEqual(400000, config.depth_target_to_fee(500000)) self.assertEqual(400000, config.depth_target_to_fee(250000)) self.assertEqual(400000, config.depth_target_to_fee(200000)) self.assertEqual(400000, config.depth_target_to_fee(100000)) config.mempool_fees = [] self.assertEqual(400000, config.depth_target_to_fee(10**5)) self.assertEqual(400000, config.depth_target_to_fee(10**6)) self.assertEqual(400000, config.depth_target_to_fee(10**7)) config.mempool_fees = [[1, 36488810]] self.assertEqual(400000, config.depth_target_to_fee(10**5)) self.assertEqual(400000, config.depth_target_to_fee(10**6)) self.assertEqual(400000, config.depth_target_to_fee(10**7)) self.assertEqual(400000, config.depth_target_to_fee(10**8)) config.mempool_fees = [[5, 125872], [1, 36488810]] self.assertEqual(400000, config.depth_target_to_fee(10**5)) self.assertEqual(400000, config.depth_target_to_fee(10**6)) self.assertEqual(400000, config.depth_target_to_fee(10**7)) self.assertEqual(400000, config.depth_target_to_fee(10**8))
def test_depth_target_to_fee(self): # Namecoin note: This test expects Bitcoin's relay fees, so we set them # here. simple_config.FEERATE_MAX_DYNAMIC = 1500000 simple_config.FEERATE_DEFAULT_RELAY = 1000 config = SimpleConfig(self.options) config.mempool_fees = [[49, 100110], [10, 121301], [6, 153731], [5, 125872], [1, 36488810]] self.assertEqual(2 * 1000, config.depth_target_to_fee(1000000)) self.assertEqual(6 * 1000, config.depth_target_to_fee(500000)) self.assertEqual(7 * 1000, config.depth_target_to_fee(250000)) self.assertEqual(11 * 1000, config.depth_target_to_fee(200000)) self.assertEqual(50 * 1000, config.depth_target_to_fee(100000)) config.mempool_fees = [] self.assertEqual(1 * 1000, config.depth_target_to_fee(10**5)) self.assertEqual(1 * 1000, config.depth_target_to_fee(10**6)) self.assertEqual(1 * 1000, config.depth_target_to_fee(10**7)) config.mempool_fees = [[1, 36488810]] self.assertEqual(2 * 1000, config.depth_target_to_fee(10**5)) self.assertEqual(2 * 1000, config.depth_target_to_fee(10**6)) self.assertEqual(2 * 1000, config.depth_target_to_fee(10**7)) self.assertEqual(1 * 1000, config.depth_target_to_fee(10**8)) config.mempool_fees = [[5, 125872], [1, 36488810]] self.assertEqual(6 * 1000, config.depth_target_to_fee(10**5)) self.assertEqual(2 * 1000, config.depth_target_to_fee(10**6)) self.assertEqual(2 * 1000, config.depth_target_to_fee(10**7)) self.assertEqual(1 * 1000, config.depth_target_to_fee(10**8))
def setUpClass(cls): super().setUpClass() cls.electrum_path = tempfile.mkdtemp() cls.config = SimpleConfig({'electrum_path': cls.electrum_path})
def setUp(self): super().setUp() self.config = SimpleConfig({'electrum_path': self.electrum_path}) self.interface = MockInterface(self.config)
class ElectrumWallet: """ An Electrum wallet wrapper """ def __init__(self, name, config): """ Initializes new electrum wallet instance @param name: Name of the wallet @param config: Configuration dictionary e.g { 'server': 'localhost:7777:s', 'rpc_user': '******', 'rpc_pass_': 'pass', 'electrum_path': '/opt/var/data/electrum', 'seed': '....', 'fee': 10000, 'testnet': 1 } """ self._name = name self._config = config self._config['testnet'] = bool(self._config['testnet']) if self._config['testnet'] is True: constants.set_testnet() self._config['verbos'] = False self._electrum_config = SimpleConfig(self._config) self._wallet_path = os.path.join(self._electrum_config.path, 'wallets', self._name) self._storage = WalletStorage(path=self._wallet_path) if not self._storage.file_exists(): self._electrum_config.set_key('default_wallet_path', self._wallet_path) k = keystore.from_seed(self._config['seed'], self._config['passphrase'], False) k.update_password(None, self._config['password']) self._storage.put('keystore', k.dump()) self._storage.put('wallet_type', 'standard') self._storage.put('use_encryption', bool(self._config['password'])) self._storage.write() self._wallet = Wallet(self._storage) # self._server = daemon.get_server(self._electrum_config) self._network = Network(self._electrum_config) self._network.start() self._wallet.start_threads(self._network) self._wallet.synchronize() self._wallet.wait_until_synchronized() self._wallet.stop_threads() self._wallet.storage.write() else: self._network = None self._wallet = self._wallet = Wallet(self._storage) self._commands = Commands(config=self._electrum_config, wallet=self._wallet, network=self._network) self._init_commands() def _init_commands(self): """ Scans the electrum commands class and binds all its methods to this class """ execlude_cmd = lambda item: (not item[0].startswith('_')) and item[ 0] not in EXECLUDED_COMMANDS for name, func in filter( execlude_cmd, inspect.getmembers(self._commands, inspect.ismethod)): setattr(self, name, func)
import os from electrum.simple_config import SimpleConfig from electrum import constants from electrum.daemon import Daemon from electrum.storage import WalletStorage from electrum.wallet import Wallet, create_new_wallet from electrum.commands import Commands config = SimpleConfig({"testnet": True}) # to use ~/.electrum/testnet as datadir constants.set_testnet() # to set testnet magic bytes daemon = Daemon(config, listen_jsonrpc=False) network = daemon.network assert network.asyncio_loop.is_running() # get wallet on disk wallet_dir = os.path.dirname(config.get_wallet_path()) wallet_path = os.path.join(wallet_dir, "test_wallet") if not os.path.exists(wallet_path): create_new_wallet(path=wallet_path, segwit=True) # open wallet storage = WalletStorage(wallet_path) wallet = Wallet(storage) wallet.start_network(network) # you can use ~CLI commands by accessing command_runner command_runner = Commands(config, wallet=None, network=network) command_runner.wallet = wallet print("balance", command_runner.getbalance())
def get_newly_added_servers(fname1, fname2=None): with open(fname1) as f: res_hostmap = json.loads(f.read()) if fname2 is not None: with open(fname2) as f: dict2 = json.loads(f.read()) common_set = set.intersection(set(res_hostmap), set(dict2)) res_hostmap = {k: v for k, v in res_hostmap.items() if k in common_set} return res_hostmap # testnet? #constants.set_testnet() config = SimpleConfig({'testnet': False}) loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network(config) network.start() @log_exceptions async def f(): try: # prune existing servers old_servers_all = constants.net.DEFAULT_SERVERS old_servers_online = await network.prune_offline_servers( constants.net.DEFAULT_SERVERS) # add new servers newly_added_servers = get_newly_added_servers(fname1, fname2)
def test_depth_target_to_fee(self): config = SimpleConfig(self.options) config.mempool_fees = [[49, 100110], [10, 121301], [6, 153731], [5, 125872], [1, 36488810]] self.assertEqual( 2 * 1000, config.depth_target_to_fee(1000000)) self.assertEqual( 6 * 1000, config.depth_target_to_fee( 500000)) self.assertEqual( 7 * 1000, config.depth_target_to_fee( 250000)) self.assertEqual(11 * 1000, config.depth_target_to_fee( 200000)) self.assertEqual(50 * 1000, config.depth_target_to_fee( 100000)) config.mempool_fees = [] self.assertEqual( 1 * 1000, config.depth_target_to_fee(10 ** 5)) self.assertEqual( 1 * 1000, config.depth_target_to_fee(10 ** 6)) self.assertEqual( 1 * 1000, config.depth_target_to_fee(10 ** 7)) config.mempool_fees = [[1, 36488810]] self.assertEqual( 2 * 1000, config.depth_target_to_fee(10 ** 5)) self.assertEqual( 2 * 1000, config.depth_target_to_fee(10 ** 6)) self.assertEqual( 2 * 1000, config.depth_target_to_fee(10 ** 7)) self.assertEqual( 1 * 1000, config.depth_target_to_fee(10 ** 8)) config.mempool_fees = [[5, 125872], [1, 36488810]] self.assertEqual( 6 * 1000, config.depth_target_to_fee(10 ** 5)) self.assertEqual( 2 * 1000, config.depth_target_to_fee(10 ** 6)) self.assertEqual( 2 * 1000, config.depth_target_to_fee(10 ** 7)) self.assertEqual( 1 * 1000, config.depth_target_to_fee(10 ** 8))
def setUp(self): super().setUp() self.config = SimpleConfig({'electrum_path': self.electrum_path})
def setUp(self): super().setUp() self.data_dir = self.electrum_path make_dir(os.path.join(self.data_dir, 'forks')) self.config = SimpleConfig({'electrum_path': self.data_dir}) blockchain.blockchains = {}
def setUp(self): self.config = SimpleConfig({'electrum_path': tempfile.mkdtemp(prefix="test_network")}) self.interface = MockInterface(self.config)
_logger = get_logger(__name__) if __name__ == '__main__': passphrase = os.getenv("WALLET_PASSPHRASE") segwit = os.getenv("SEGWIT") == "true" seed = os.getenv("WALLET_SEED") gap_limit = int(os.getenv("GAP_LIMIT", "20")) if passphrase is None: raise Exception("WALLET_PASSPHRASE unset") if cmdline_options["testnet"]: constants.set_testnet() config = SimpleConfig(cmdline_options) logging.configure_logging(config) fd, server = daemon.get_fd_or_server(config) if fd is not None: init_plugins(config, 'cmdline') d = daemon.Daemon(config, fd) path = config.get_wallet_path() if os.path.exists(path) is False: _logger.warn("Wallet doesn't exist, creating (segwit {segwit})".format(segwit=segwit)) if seed is not None: restore_wallet_from_text(seed, path=path, password=passphrase, encrypt_file=True) else: