示例#1
0
async def seed(ctx):
    """Add 50 receiving addresses to the database. RUN ONCE"""
    await Message.delete(ctx.message)
    if ctx.message.author is ctx.message.guild.owner:
        c.execute('''SELECT address FROM Addresses WHERE serverid=?''',
                  (ctx.message.guild.id, ))
        already_ran = c.fetchone()
        if already_ran is None:
            server = ctx.message.guild
            server_id = server.id
            k = keystore.from_seed(
                ctx.message.content[len(command_prefix) + 5:], '', False)
            for x in range(0, 49):
                addr = bitcoin.pubkey_to_address('p2pkh',
                                                 k.derive_pubkey(False, x))
                addr_balance = get_balance(addr)
                c.execute(
                    '''INSERT INTO Addresses (serverid, address, balance)
                                                      VALUES(?,?,?)''', (
                        server_id,
                        addr,
                        addr_balance,
                    ))
            conn.commit()
            await ctx.message.author.send(
                "50 btc addresses have been generated and stored.")
        else:
            await ctx.send("Addresses already generated.")
示例#2
0
def create_wallet():
    """
    Create an electrum wallet if it does not exist
    :return: 
    """
    if not os.path.isfile(WALLET_FILE):
        print("Creating wallet")
        config = electrum.SimpleConfig()
        storage = WalletStorage(config.get_wallet_path())
        passphrase = config.get('passphrase', '')
        seed = Mnemonic('en').make_seed()
        k = keystore.from_seed(seed, passphrase)
        k.update_password(None, None)
        storage.put('keystore', k.dump())
        storage.put('wallet_type', 'standard')
        storage.put('use_encryption', False)
        storage.write()
        wallet = ElectrumWallet(storage)
        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."
        )
        wallet.storage.write()
        print("Wallet saved in '%s'" % wallet.storage.path)
    else:
        print("Wallet already present")
def _get_keystore(seed_type: SeedType, is_p2sh):
    return keystore.from_seed(
        seed=MNEMONIC,
        passphrase='',
        is_p2sh=is_p2sh,
        seed_type_=seed_type.value,
    )
    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()
示例#5
0
    def create_wallet(self, password=''):
        """
        Create a new bitcoin wallet.
        """
        self._logger.info("Creating wallet in %s", self.wallet_dir)

        if password is not None:
            try:
                self.set_wallet_password(password)
            except InitError:
                return fail(
                    RuntimeError(
                        "Cannot initialize the keychain, unable to unlock the wallet!"
                    ))
        self.wallet_password = password

        def run_on_thread(thread_method):
            # We are running code that writes to the wallet on a separate thread.
            # This is done because Electrum does not allow writing to a wallet from a daemon thread.
            wallet_thread = Thread(target=thread_method,
                                   name="ethereum-create-wallet")
            wallet_thread.setDaemon(False)
            wallet_thread.start()
            wallet_thread.join()

        seed = Mnemonic('en').make_seed()
        k = keystore.from_seed(seed, '')
        k.update_password(None, password)
        self.storage.put('keystore', k.dump())
        self.storage.put('wallet_type', 'standard')
        self.storage.set_password(password, bool(password))
        run_on_thread(self.storage.write)

        self.wallet = ElectrumWallet(self.storage)
        self.wallet.synchronize()
        run_on_thread(self.wallet.storage.write)
        self.created = True
        self.unlocked = True

        self.start_daemon()
        self.open_wallet()

        self._logger.info("Bitcoin wallet saved in '%s'",
                          self.wallet.storage.path)

        return succeed(None)
示例#6
0
    def create_storage(self, js_data, single_password_enabled,
                       single_password):
        self._logger.info('Creating wallet from wizard data')
        data = js_data.toVariant()
        self._logger.debug(str(data))

        if single_password_enabled and single_password:
            data['encrypt'] = True
            data['password'] = single_password

        try:
            path = os.path.join(
                os.path.dirname(self.daemon.config.get_wallet_path()),
                data['wallet_name'])
            if os.path.exists(path):
                raise Exception('file already exists at path')
            storage = WalletStorage(path)

            if data['seed_type'] in ['old', 'standard',
                                     'segwit']:  #2fa, 2fa-segwit
                self._logger.debug('creating keystore from electrum seed')
                k = keystore.from_seed(data['seed'], data['seed_extra_words'],
                                       data['wallet_type'] == 'multisig')
            elif data['seed_type'] == 'bip39':
                self._logger.debug('creating keystore from bip39 seed')
                root_seed = keystore.bip39_to_seed(data['seed'],
                                                   data['seed_extra_words'])
                derivation = normalize_bip32_derivation(
                    data['derivation_path'])
                script = data['script_type'] if data[
                    'script_type'] != 'p2pkh' else 'standard'
                k = keystore.from_bip43_rootseed(root_seed,
                                                 derivation,
                                                 xtype=script)
            else:
                raise Exception('unsupported/unknown seed_type %s' %
                                data['seed_type'])

            if data['encrypt']:
                if k.may_have_password():
                    k.update_password(None, data['password'])
                storage.set_password(
                    data['password'],
                    enc_version=StorageEncryptionVersion.USER_PASSWORD)

            db = WalletDB('', manual_upgrades=False)
            db.set_keystore_encryption(
                bool(data['password']) and data['encrypt'])

            db.put('wallet_type', data['wallet_type'])
            db.put('seed_type', data['seed_type'])
            db.put('keystore', k.dump())
            if k.can_have_deterministic_lightning_xprv():
                db.put(
                    'lightning_xprv',
                    k.get_lightning_xprv(
                        data['password'] if data['encrypt'] else None))

            db.load_plugins()
            db.write(storage)

            # minimally populate self after create
            self._password = data['password']
            self.path = path

            self.createSuccess.emit()
        except Exception as e:
            self._logger.error(str(e))
            self.createError.emit(str(e))
def _get_cosigner_keystore(seed_type: SeedType):
    return keystore.from_seed(seed=MNEMONIC_COSIGNER,
                              passphrase='',
                              is_p2sh=True,
                              seed_type_=seed_type.value)
示例#8
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').strip()
        passphrase = config.get('passphrase', '')
        password = password_dialog() if keystore.is_private(text) else None
        if keystore.is_address_list(text):
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_address(x)
        elif keystore.is_private_key_list(text):
            k = keystore.Imported_KeyStore({})
            storage.put('keystore', k.dump())
            storage.put('use_encryption', bool(password))
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_private_key(x, password)
            storage.write()
        else:
            if keystore.is_seed(text):
                k = keystore.from_seed(text, passphrase, False)
            elif keystore.is_master_key(text):
                k = keystore.from_master_key(text)
            else:
                sys.exit("Error: Seed or key not recognized")
            if password:
                k.update_password(None, password)
            storage.put('keystore', k.dump())
            storage.put('wallet_type', 'standard')
            storage.put('use_encryption', bool(password))
            storage.write()
            wallet = Wallet(storage)
        if not config.get('offline'):
            network = Network(config)
            network.start()
            wallet.start_threads(network)
            print_msg("Recovering wallet...")
            wallet.synchronize()
            wallet.wait_until_synchronized()
            wallet.stop_threads()
            # note: we don't wait for SPV
            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."
        print_msg(msg)

    elif cmdname == 'create':
        password = password_dialog()
        passphrase = config.get('passphrase', '')
        seed_type = 'segwit' if config.get('segwit') else 'standard'
        seed = Mnemonic('en').make_seed(seed_type)
        k = keystore.from_seed(seed, passphrase, False)
        storage.put('keystore', k.dump())
        storage.put('wallet_type', 'standard')
        wallet = Wallet(storage)
        wallet.update_password(None, password, True)
        wallet.synchronize()
        print_msg("Your wallet generation seed is:\n\"%s\"" % seed)
        print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")

    wallet.storage.write()
    print_msg("Wallet saved in '%s'" % wallet.storage.path)
    sys.exit(0)