示例#1
0
def run_offline_command(config, config_options):
    cmdname = config.get('cmd')
    cmd = known_commands[cmdname]
    storage = WalletStorage(config.get_wallet_path())
    wallet = Wallet(storage) if cmd.requires_wallet else None
    # check password
    if cmd.requires_password and storage.get('use_encryption'):
        password = config_options.get('password')
        try:
            seed = wallet.check_password(password)
        except InvalidPassword:
            print "Error: This password does not decode this wallet."
            sys.exit(1)
    if cmd.requires_network:
        print "Warning: running command offline"
    # arguments passed to function
    args = map(lambda x: config.get(x), cmd.params)
    # decode json arguments
    args = map(json_decode, args)
    # options
    args += map(lambda x: config.get(x), cmd.options)
    cmd_runner = Commands(config,
                          wallet,
                          None,
                          password=config_options.get('password'),
                          new_password=config_options.get('new_password'))
    func = getattr(cmd_runner, cmd.name)
    result = func(*args)
    # save wallet
    if wallet:
        wallet.storage.write()
    return result
示例#2
0
文件: main.py 项目: lbryio/lbryum
def run_offline_command(config, config_options):
    _ = get_blockchain(config, None)
    cmdname = config.get('cmd')
    cmd = Commands.known_commands[cmdname]
    storage = WalletStorage(config.get_wallet_path())
    wallet = Wallet(storage) if cmd.requires_wallet else None
    # check password
    if cmd.requires_password and storage.get('use_encryption'):
        password = config_options.get('password')
        try:
            seed = wallet.check_password(password)
        except InvalidPassword:
            print "Error: This password does not decode this wallet."
            sys.exit(1)
    if cmd.requires_network:
        print "Warning: running command offline"
    # arguments passed to function
    args = map(lambda x: config.get(x), cmd.params)
    # decode json arguments
    args = map(json_decode, args)
    # options
    args += map(lambda x: config.get(x), cmd.options)
    cmd_runner = Commands(config, wallet, None,
                          password=config_options.get('password'),
                          new_password=config_options.get('new_password'))
    func = getattr(cmd_runner, cmd.name)
    result = func(*args)
    # save wallet
    if wallet:
        wallet.storage.write()
    return result
示例#3
0
 def setUp(self):
     super(TestNewWallet, self).setUp()
     self.storage = WalletStorage(self.wallet_path)
     self.wallet = NewWallet(self.storage)
     # This cannot be constructed by lbryum at random, it should be safe
     # from eventual collisions.
     self.wallet.add_seed(self.seed_text, self.password)
     self.wallet.create_master_keys(self.password)
     self.wallet.create_main_account()
示例#4
0
    def test_read_dictionnary_from_file(self):
        some_dict = {"a": "b", "c": "d"}
        contents = repr(some_dict)
        with open(self.wallet_path, "w") as f:
            contents = f.write(contents)

        storage = WalletStorage(self.wallet_path)
        self.assertEqual("b", storage.get("a"))
        self.assertEqual("d", storage.get("c"))
示例#5
0
    def test_read_dictionary_from_file(self):
        some_dict = {"a": "b", "c": "d"}
        contents = repr(some_dict)
        with open(self.wallet_path, "w") as f:
            contents = f.write(contents)

        storage = WalletStorage(self.wallet_path)
        self.assertEqual("b", storage.get("a"))
        self.assertEqual("d", storage.get("c"))
示例#6
0
def init_cmdline(config_options):
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')
    cmd = known_commands[cmdname]

    if cmdname == 'signtransaction' and config.get('privkey'):
        cmd.requires_wallet = False
        cmd.requires_password = False

    if cmdname in ['payto', 'paytomany'] and config.get('unsigned'):
        cmd.requires_password = False

    if cmdname in ['payto', 'paytomany'] and config.get('broadcast'):
        cmd.requires_network = True

    if cmdname in ['createrawtx'] and config.get('unsigned'):
        cmd.requires_password = False
        cmd.requires_wallet = False

    # instanciate wallet for command-line
    storage = WalletStorage(config.get_wallet_path())

    if cmd.requires_wallet and not storage.file_exists:
        log.error("Error: Wallet file not found.")
        print "Type 'lbryum create' to create a new wallet, or provide a path to a wallet with " \
              "the -w option"
        sys.exit(0)

    # important warning
    if cmd.name in ['getprivatekeys']:
        print "WARNING: ALL your private keys are secret."
        print "Exposing a single private key can compromise your entire wallet!"
        print "In particular, DO NOT use 'redeem private key' services proposed by third parties."

    # commands needing password
    if cmd.requires_password and storage.get('use_encryption'):
        if config.get('password'):
            password = config.get('password')
        else:
            password = prompt_password('Password:'******'password'] = password

    if cmd.name == 'password':
        new_password = prompt_password('New password:'******'new_password'] = new_password

    return cmd, password
示例#7
0
    def test_write_dictionary_to_file(self):
        storage = WalletStorage(self.wallet_path)

        some_dict = {"a": "b", "c": "d"}

        for key, value in some_dict.items():
            storage.put(key, value)
        storage.write()

        contents = ""
        with open(self.wallet_path, "r") as f:
            contents = f.read()
        self.assertEqual(some_dict, json.loads(contents))
示例#8
0
    def __init__(self, config, network, daemon, plugins):
        self.network = network
        self.config = config
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists:
            print "Wallet not found. try 'electrum create'"
            exit()

        self.done = 0
        self.last_balance = ""

        set_verbosity(False)

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""

        self.wallet = Wallet(storage)
        self.wallet.start_threads(network)
        self.contacts = StoreDict(self.config, 'contacts')

        network.register_callback(self.on_network, ['updated', 'banner'])
        self.commands = [_("[h] - displays this help text"), \
                         _("[i] - display transaction history"), \
                         _("[o] - enter payment order"), \
                         _("[p] - print stored payment order"), \
                         _("[s] - send stored payment order"), \
                         _("[r] - show own receipt addresses"), \
                         _("[c] - display contacts"), \
                         _("[b] - print server banner"), \
                         _("[q] - quit") ]
        self.num_commands = len(self.commands)
示例#9
0
    def load_wallet(self, path, get_wizard=None):
        if path in self.wallets:
            wallet = self.wallets[path]
        else:
            storage = WalletStorage(path)
            if get_wizard:
                if storage.file_exists:
                    wallet = Wallet(storage)
                    action = wallet.get_action()
                else:
                    action = 'new'
                if action:
                    wizard = get_wizard()
                    wallet = wizard.run(self.network, storage)
                else:
                    wallet.start_threads(self.network)
            else:
                wallet = Wallet(storage)
                # automatically generate wallet for lbrynet
                if not storage.file_exists:
                    seed = wallet.make_seed()
                    wallet.add_seed(seed, None)
                    wallet.create_master_keys(None)
                    wallet.create_main_account()
                    wallet.synchronize()

                wallet.start_threads(self.network)
            if wallet:
                self.wallets[path] = wallet
        return wallet
示例#10
0
 def test_wallet_without_seed_is_watching_only(self):
     # We need a new storage , since the default storage was already seeded
     # in setUp()
     new_dir = tempfile.mkdtemp()
     storage = WalletStorage(os.path.join(new_dir, "somewallet"))
     wallet = NewWallet(storage)
     self.assertTrue(wallet.is_watching_only())
     shutil.rmtree(new_dir)  # Don't leave useless stuff in /tmp
示例#11
0
 def setUp(self):
     super(TestNewWallet, self).setUp()
     self.storage = WalletStorage(self.wallet_path)
     self.wallet = NewWallet(self.storage)
     # This cannot be constructed by lbryum at random, it should be safe
     # from eventual collisions.
     self.wallet.add_seed(self.seed_text, self.password)
     self.wallet.create_master_keys(self.password)
     self.wallet.create_main_account()
def getWallet(path=None):
    if not path:
        config = SimpleConfig()
        path = config.get_wallet_path()
    storage = WalletStorage(path)
    if not storage.file_exists:
        print "Failed to run: No wallet to migrate"
        sys.exit(1)
    return Wallet(storage)
示例#13
0
文件: main.py 项目: lbryio/lbryum
def init_cmdline(config_options):
    config = SimpleConfig(config_options)
    cmdname = config.get('cmd')
    cmd = Commands.known_commands[cmdname]

    # instanciate wallet for command-line
    storage = WalletStorage(config.get_wallet_path())

    if cmd.requires_wallet and not storage.file_exists:
        log.error("Error: Wallet file not found.")
        print "Type 'lbryum create' to create a new wallet, or provide a path to a wallet with " \
              "the -w option"
        sys.exit(0)

    # important warning
    if cmd.name in ['getprivatekeys']:
        print "WARNING: ALL your private keys are secret."
        print "Exposing a single private key can compromise your entire wallet!"
        print "In particular, DO NOT use 'redeem private key' services proposed by third parties."

    # commands needing password
    if cmd.requires_password and storage.get('use_encryption'):
        if config.get('password'):
            password = config.get('password')
        else:
            password = prompt_password('Password:'******'password'] = password

    if cmd.name == 'password':
        new_password = prompt_password('New password:'******'password'] = password
        config_options['new_password'] = new_password

    return cmd, password
示例#14
0
 def __init__(self, lbryum_path):
     self.config = SimpleConfig()
     self.config.set_key('chain', 'lbrycrd_main')
     self.storage = WalletStorage(lbryum_path)
     self.wallet = Wallet(self.storage)
     self.cmd_runner = Commands(self.config, self.wallet, None)
     if not self.wallet.has_seed():
         seed = self.wallet.make_seed()
         self.wallet.add_seed(seed, "derp")
         self.wallet.create_master_keys("derp")
         self.wallet.create_main_account()
         self.wallet.update_password("derp", "")
     self.network = Network(self.config)
     self.blockchain = get_blockchain(self.config, self.network)
     print self.config.get('chain'), self.blockchain
     self.wallet.storage.write()
示例#15
0
    def test_write_dictionnary_to_file(self):
        storage = WalletStorage(self.wallet_path)

        some_dict = {"a": "b", "c": "d"}

        for key, value in some_dict.items():
            storage.put(key, value)
        storage.write()

        contents = ""
        with open(self.wallet_path, "r") as f:
            contents = f.read()
        self.assertEqual(some_dict, json.loads(contents))
示例#16
0
class TestNewWallet(WalletTestCase):
    seed_text = "travel nowhere air position hill peace suffer parent beautiful rise blood power home crumble teach"
    xprv_text = "xprv9s21ZrQH143K2RNUGjxcwJXKSzQeSoCp1GwLFBF8YVQ92TJUX7LXvwoCLVVyrHcPAbAaGQwnFydd8hftzAuTMRCzHue31ftg9wiGkkoVAaT"
    password = "******"

    first_account_name = "account1"

    import_private_key = "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW"
    import_key_address = "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma"

    def setUp(self):
        super(TestNewWallet, self).setUp()
        self.storage = WalletStorage(self.wallet_path)
        self.wallet = NewWallet(self.storage)
        # This cannot be constructed by lbryum at random, it should be safe
        # from eventual collisions.
        self.wallet.add_seed(self.seed_text, self.password)
        self.wallet.create_master_keys(self.password)
        self.wallet.create_main_account()

    def test_wallet_with_seed_is_not_watching_only(self):
        self.assertFalse(self.wallet.is_watching_only())

    def test_wallet_without_seed_is_watching_only(self):
        # We need a new storage , since the default storage was already seeded
        # in setUp()
        new_dir = tempfile.mkdtemp()
        storage = WalletStorage(os.path.join(new_dir, "somewallet"))
        wallet = NewWallet(storage)
        self.assertTrue(wallet.is_watching_only())
        shutil.rmtree(new_dir)  # Don't leave useless stuff in /tmp

    def test_new_wallet_is_deterministic(self):
        self.assertTrue(self.wallet.is_deterministic())

    def test_get_seed_returns_correct_seed(self):
        self.assertEqual(self.wallet.get_seed(self.password), self.seed_text)

    def test_update_password(self):
        new_password = "******"
        self.wallet.update_password(self.password, new_password)
        self.wallet.get_seed(new_password)

    def test_encryption(self):
        self.storage.write()
        wallet_data = json.load(open(self.wallet_path, "r"))
        self.assertTrue(wallet_data['use_encryption'])

        # retrieve the encrypted values from wallet storage
        enc_xprv_key = wallet_data['master_private_keys']['x/']
        enc_seed = wallet_data['seed']

        # the xprv key and seed should not be in plain text in the wallet storage
        self.assertNotEqual(self.seed_text, enc_seed)
        self.assertNotEqual(self.xprv_text, enc_xprv_key)

        # decoding the encrypted xprv key and seed should return the original values
        self.assertEqual(self.seed_text, pw_decode(enc_seed, self.password))
        self.assertEqual(self.xprv_text, pw_decode(enc_xprv_key,
                                                   self.password))
        self.assertEqual(
            self.xprv_text,
            self.wallet.get_master_private_key('x/', self.password))

    def test_check_password(self):
        # no errors should occur if the password is valid
        self.wallet.check_password(self.password)

    def test_check_invalid_password(self):
        with self.assertRaises(InvalidPassword):
            self.wallet.check_password('invalid')
示例#17
0
class TestNewWallet(WalletTestCase):
    seed_text = "travel nowhere air position hill peace suffer parent beautiful rise blood power home crumble teach"
    xprv_text = "xprv9s21ZrQH143K2RNUGjxcwJXKSzQeSoCp1GwLFBF8YVQ92TJUX7LXvwoCLVVyrHcPAbAaGQwnFydd8hftzAuTMRCzHue31ftg9wiGkkoVAaT"
    password = "******"

    first_account_name = "account1"

    import_private_key = "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW"
    import_key_address = "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma"

    def setUp(self):
        super(TestNewWallet, self).setUp()
        self.storage = WalletStorage(self.wallet_path)
        self.wallet = NewWallet(self.storage)
        # This cannot be constructed by lbryum at random, it should be safe
        # from eventual collisions.
        self.wallet.add_seed(self.seed_text, self.password)
        self.wallet.create_master_keys(self.password)
        self.wallet.create_main_account()

    def test_wallet_with_seed_is_not_watching_only(self):
        self.assertFalse(self.wallet.is_watching_only())

    def test_wallet_without_seed_is_watching_only(self):
        # We need a new storage , since the default storage was already seeded
        # in setUp()
        new_dir = tempfile.mkdtemp()
        storage = WalletStorage(os.path.join(new_dir, "somewallet"))
        wallet = NewWallet(storage)
        self.assertTrue(wallet.is_watching_only())
        shutil.rmtree(new_dir)  # Don't leave useless stuff in /tmp

    def test_new_wallet_is_deterministic(self):
        self.assertTrue(self.wallet.is_deterministic())

    def test_get_seed_returns_correct_seed(self):
        self.assertEqual(self.wallet.get_seed(self.password), self.seed_text)

    def test_update_password(self):
        new_password = "******"
        self.wallet.update_password(self.password, new_password)
        self.wallet.get_seed(new_password)

    def test_encryption(self):
        self.storage.write()
        wallet_data = json.load(open(self.wallet_path, "r"))
        self.assertTrue(wallet_data['use_encryption'])

        # retrieve the encrypted values from wallet storage
        enc_xprv_key = wallet_data['master_private_keys']['x/']
        enc_seed = wallet_data['seed']

        # the xprv key and seed should not be in plain text in the wallet storage
        self.assertNotEqual(self.seed_text, enc_seed)
        self.assertNotEqual(self.xprv_text, enc_xprv_key)

        # decoding the encrypted xprv key and seed should return the original values
        self.assertEqual(self.seed_text, pw_decode(enc_seed, self.password))
        self.assertEqual(self.xprv_text, pw_decode(enc_xprv_key, self.password))
        self.assertEqual(self.xprv_text, self.wallet.get_master_private_key('x/', self.password))

    def test_check_password(self):
        # no errors should occur if the password is valid
        self.wallet.check_password(self.password)

    def test_check_invalid_password(self):
        with self.assertRaises(InvalidPassword):
            self.wallet.check_password('invalid')
示例#18
0
def run_non_RPC(config):
    cmdname = config.get('cmd')

    storage = WalletStorage(config.get_wallet_path())
    if storage.file_exists:
        sys.exit("Error: Remove the existing wallet first!")

    def password_dialog():
        return prompt_password(
            "Password (hit return if you do not wish to encrypt your wallet):")

    if cmdname == 'restore':
        text = config.get('text')
        password = password_dialog() if Wallet.is_seed(text) or Wallet.is_xprv(
            text) or Wallet.is_private_key(text) else None
        try:
            wallet = Wallet.from_text(text, password, storage)
        except BaseException as e:
            sys.exit(str(e))
        if not config.get('offline'):
            network = Network(config)
            network.start()
            wallet.start_threads(network)
            log.info("Recovering wallet...")
            wallet.synchronize()
            wallet.wait_until_synchronized()
            msg = "Recovery successful" if wallet.is_found(
            ) else "Found no history for this wallet"
        else:
            msg = "This wallet was restored offline. It may contain more addresses than displayed."
        log.info(msg)
    elif cmdname == 'create':
        password = password_dialog()
        wallet = Wallet(storage)
        seed = wallet.make_seed()
        wallet.add_seed(seed, password)
        wallet.create_master_keys(password)
        wallet.create_main_account()
        wallet.synchronize()
        print "Your wallet generation seed is:\n\"%s\"" % seed
        print "Please keep it in a safe place; if you lose it, you will not be able to restore " \
              "your wallet."
    elif cmdname == 'deseed':
        wallet = Wallet(storage)
        if not wallet.seed:
            log.info("Error: This wallet has no seed")
        else:
            ns = wallet.storage.path + '.seedless'
            print "Warning: you are going to create a seedless wallet'\n" \
                  "It will be saved in '%s'" % ns
            if raw_input("Are you sure you want to continue? (y/n) ") in [
                    'y', 'Y', 'yes'
            ]:
                wallet.storage.path = ns
                wallet.seed = ''
                wallet.storage.put('seed', '')
                wallet.use_encryption = False
                wallet.storage.put('use_encryption', wallet.use_encryption)
                for k in wallet.imported_keys.keys():
                    wallet.imported_keys[k] = ''
                wallet.storage.put('imported_keys', wallet.imported_keys)
                print "Done."
            else:
                print "Action canceled."
        wallet.storage.write()
    else:
        raise Exception("Unknown command %s" % cmdname)
    wallet.storage.write()
    log.info("Wallet saved in '%s'", wallet.storage.path)