Beispiel #1
0
def main():

    parser = argparse.ArgumentParser(
        description='Generate private keys from password',
        epilog='Report bugs to: ')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),
    parser.add_argument('-c',
                        '--config',
                        default='./config.yml',
                        help='specify custom path for config file')
    parser.add_argument('account')
    parser.add_argument('password')
    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.safe_load(ymlfile)

    for role in roles:
        key = PasswordKey(args.account, args.password, role=role)
        privkey = key.get_private_key()
        print('role: {}, key: {}'.format(role, str(privkey)))
Beispiel #2
0
def get_keys_from_password(
    account_name: str,
    password: str,
    prefix: str,
    key_types: Optional[List[str]] = None,
) -> Dict[str, str]:
    """Generates public/private keys from a password."""
    if not key_types:
        key_types = ['active', 'owner', 'memo']

    keys = {}
    for key_type in key_types:
        # PasswordKey object
        passkey = PasswordKey(account_name, password, role=key_type)

        privkey = passkey.get_private_key()
        print('{} private: {}'.format(
            key_type, str(privkey)))  # we need explicit str() conversion!

        # pubkey with default prefix GPH
        pubkey = passkey.get_public_key()

        # pubkey with correct prefix
        keys[key_type] = format(pubkey, prefix)
        print('{} public: {}\n'.format(key_type, keys[key_type]))

    return keys
Beispiel #3
0
def importaccount(ctx, account, role):
    """ Import an account using an account password
    """
    from bitsharesbase.account import PasswordKey

    password = click.prompt(
        "Account Passphrase",
        hide_input=True,
    )
    account = Account(account, bitshares_instance=ctx.bitshares)
    imported = False

    if role == "owner":
        owner_key = PasswordKey(account["name"], password, role="owner")
        owner_pubkey = format(owner_key.get_public_key(),
                              ctx.bitshares.rpc.chain_params["prefix"])
        if owner_pubkey in [x[0] for x in account["owner"]["key_auths"]]:
            click.echo("Importing owner key!")
            owner_privkey = owner_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(owner_privkey)
            imported = True

    if role == "active":
        active_key = PasswordKey(account["name"], password, role="active")
        active_pubkey = format(active_key.get_public_key(),
                               ctx.bitshares.rpc.chain_params["prefix"])
        if active_pubkey in [x[0] for x in account["active"]["key_auths"]]:
            click.echo("Importing active key!")
            active_privkey = active_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(active_privkey)
            imported = True

    if role == "memo":
        memo_key = PasswordKey(account["name"], password, role=role)
        memo_pubkey = format(memo_key.get_public_key(),
                             ctx.bitshares.rpc.chain_params["prefix"])
        if memo_pubkey == account["memo_key"]:
            click.echo("Importing memo key!")
            memo_privkey = memo_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(memo_privkey)
            imported = True

    if not imported:
        click.echo("No matching key(s) found. Password correct?")
Beispiel #4
0
def getcloudloginkey(ctx, account):
    """ Return keys for cloudlogin
    """
    from bitsharesbase.account import PasswordKey

    password = click.prompt("Passphrase", hide_input=True).strip()
    t = [["role", "wif", "pubkey", "accounts"]]
    for role in ["owner", "active", "memo"]:
        wif = PasswordKey(account, password, role=role)
        pubkey = format(wif.get_public_key(),
                        ctx.bitshares.rpc.chain_params["prefix"])

        t.append([
            role,
            str(wif.get_private_key()),
            pubkey,
            ctx.bitshares.wallet.getAccountFromPublicKey(pubkey) or "",
        ])

    print_table(t)
Beispiel #5
0
def main(debug, config, wallet_password, password, broadcast, account_name):
    """ Use this script to change account keys. By default, a random will be
        generated. By default, transaction will not be broadcasted (dry-run mode).
    """
    # create logger
    if debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    conf = yaml.safe_load(config)

    b = not broadcast
    bitshares = BitShares(node=conf['node_bts'], nobroadcast=b)
    account = Account(account_name, bitshares_instance=bitshares)

    # Wallet unlock
    try:
        bitshares.unlock(wallet_password)
    except WrongMasterPasswordException:
        log.critical('Wrong wallet password provided')
        sys.exit(1)

    # random password
    if password:
        password = password
    else:
        password = generate_password()

    print('password: {}\n'.format(password))

    key = dict()
    for key_type in key_types:
        # PasswordKey object
        k = PasswordKey(account_name, password, role=key_type)

        privkey = k.get_private_key()
        print('{} private: {}'.format(key_type, str(privkey)))  # we need explicit str() conversion!

        # pubkey with default prefix GPH
        pubkey = k.get_public_key()

        # pubkey with correct prefix
        key[key_type] = format(pubkey, bitshares.prefix)
        print('{} public: {}\n'.format(key_type, key[key_type]))

    # prepare for json format
    account['options']['memo_key'] = key['memo']
    owner_key_authority = [[key['owner'], 1]]
    active_key_authority = [[key['active'], 1]]
    owner_accounts_authority = []
    active_accounts_authority = []
    posting_accounts_authority = []

    s = {
        'account': account['id'],
        'new_options': account['options'],
        'owner': {'account_auths': owner_accounts_authority, 'key_auths': owner_key_authority, 'weight_threshold': 1},
        'active': {
            'account_auths': active_accounts_authority,
            'key_auths': active_key_authority,
            'weight_threshold': 1,
        },
        'fee': {'amount': 0, 'asset_id': '1.3.0'},
        'extensions': {},
        'prefix': bitshares.prefix,
    }

    # pprint(s)
    op = operations.Account_update(**s)

    try:
        bitshares.finalizeOp(op, account_name, 'owner')
    except MissingKeyError:
        log.critical('No key for {} in storage, use `uptick addkey` to add'.format(account_name))
        sys.exit(1)
Beispiel #6
0
    def create_account(
        self,
        account_name,
        registrar=None,
        referrer="1.2.35641",
        referrer_percent=50,
        owner_key=None,
        active_key=None,
        memo_key=None,
        password=None,
        additional_owner_keys=[],
        additional_active_keys=[],
        additional_owner_accounts=[],
        additional_active_accounts=[],
        proxy_account="proxy-to-self",
        storekeys=True,
    ):
        """ Create new account on BitShares

            The brainkey/password can be used to recover all generated keys (see
            `bitsharesbase.account` for more details.

            By default, this call will use ``default_account`` to
            register a new name ``account_name`` with all keys being
            derived from a new brain key that will be returned. The
            corresponding keys will automatically be installed in the
            wallet.

            .. warning:: Don't call this method unless you know what
                          you are doing! Be sure to understand what this
                          method does and where to find the private keys
                          for your account.

            .. note:: Please note that this imports private keys
                      (if password is present) into the wallet by
                      default. However, it **does not import the owner
                      key** for security reasons. Do NOT expect to be
                      able to recover it from the wallet if you lose
                      your password!

            :param str account_name: (**required**) new account name
            :param str registrar: which account should pay the registration fee
                                (defaults to ``default_account``)
            :param str owner_key: Main owner key
            :param str active_key: Main active key
            :param str memo_key: Main memo_key
            :param str password: Alternatively to providing keys, one
                                 can provide a password from which the
                                 keys will be derived
            :param array additional_owner_keys:  Additional owner public keys
            :param array additional_active_keys: Additional active public keys
            :param array additional_owner_accounts: Additional owner account names
            :param array additional_active_accounts: Additional acctive account names
            :param bool storekeys: Store new keys in the wallet (default: ``True``)
            :raises AccountExistsException: if the account already exists on the blockchain

        """
        if not registrar and config["default_account"]:
            registrar = config["default_account"]
        if not registrar:
            raise ValueError(
                "Not registrar account given. Define it with " +
                "registrar=x, or set the default_account using uptick")
        if password and (owner_key or active_key or memo_key):
            raise ValueError("You cannot use 'password' AND provide keys!")

        try:
            Account(account_name, bitshares_instance=self)
            raise AccountExistsException
        except:
            pass

        referrer = Account(referrer, bitshares_instance=self)
        registrar = Account(registrar, bitshares_instance=self)

        " Generate new keys from password"
        from bitsharesbase.account import PasswordKey, PublicKey
        if password:
            active_key = PasswordKey(account_name, password, role="active")
            owner_key = PasswordKey(account_name, password, role="owner")
            memo_key = PasswordKey(account_name, password, role="memo")
            active_pubkey = active_key.get_public_key()
            owner_pubkey = owner_key.get_public_key()
            memo_pubkey = memo_key.get_public_key()
            active_privkey = active_key.get_private_key()
            # owner_privkey   = owner_key.get_private_key()
            memo_privkey = memo_key.get_private_key()
            # store private keys
            if storekeys:
                # self.wallet.addPrivateKey(owner_privkey)
                self.wallet.addPrivateKey(active_privkey)
                self.wallet.addPrivateKey(memo_privkey)
        elif (owner_key and active_key and memo_key):
            active_pubkey = PublicKey(active_key,
                                      prefix=self.rpc.chain_params["prefix"])
            owner_pubkey = PublicKey(owner_key,
                                     prefix=self.rpc.chain_params["prefix"])
            memo_pubkey = PublicKey(memo_key,
                                    prefix=self.rpc.chain_params["prefix"])
        else:
            raise ValueError(
                "Call incomplete! Provide either a password or public keys!")
        owner = format(owner_pubkey, self.rpc.chain_params["prefix"])
        active = format(active_pubkey, self.rpc.chain_params["prefix"])
        memo = format(memo_pubkey, self.rpc.chain_params["prefix"])

        owner_key_authority = [[owner, 1]]
        active_key_authority = [[active, 1]]
        owner_accounts_authority = []
        active_accounts_authority = []

        # additional authorities
        for k in additional_owner_keys:
            owner_key_authority.append([k, 1])
        for k in additional_active_keys:
            active_key_authority.append([k, 1])

        for k in additional_owner_accounts:
            addaccount = Account(k, bitshares_instance=self)
            owner_accounts_authority.append([addaccount["id"], 1])
        for k in additional_active_accounts:
            addaccount = Account(k, bitshares_instance=self)
            active_accounts_authority.append([addaccount["id"], 1])

        # voting account
        voting_account = Account(proxy_account or "proxy-to-self")

        op = {
            "fee": {
                "amount": 0,
                "asset_id": "1.3.0"
            },
            "registrar": registrar["id"],
            "referrer": referrer["id"],
            "referrer_percent": referrer_percent * 100,
            "name": account_name,
            'owner': {
                'account_auths': owner_accounts_authority,
                'key_auths': owner_key_authority,
                "address_auths": [],
                'weight_threshold': 1
            },
            'active': {
                'account_auths': active_accounts_authority,
                'key_auths': active_key_authority,
                "address_auths": [],
                'weight_threshold': 1
            },
            "options": {
                "memo_key": memo,
                "voting_account": voting_account["id"],
                "num_witness": 0,
                "num_committee": 0,
                "votes": [],
                "extensions": []
            },
            "extensions": {},
            "prefix": self.rpc.chain_params["prefix"]
        }
        op = operations.Account_create(**op)
        return self.finalizeOp(op, registrar, "active")
Beispiel #7
0
def main(debug, config, wallet_password, password, broadcast, parent_account,
         account_name):
    """ Use this script to create new account. By default, a random password will be
        generated. By default, transaction will not be broadcasted (dry-run mode).
    """
    # create logger
    if debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    conf = yaml.safe_load(config)

    b = not broadcast
    bitshares = BitShares(node=conf['node_bts'], nobroadcast=b)
    account = Account(parent_account, bitshares_instance=bitshares)

    # Wallet unlock
    try:
        bitshares.unlock(wallet_password)
    except WrongMasterPasswordException:
        log.critical('Wrong wallet password provided')
        sys.exit(1)

    # random password
    if password:
        password = password
    else:
        password = generate_password()

    print('password: {}\n'.format(password))

    key = dict()
    for key_type in key_types:
        # PasswordKey object
        k = PasswordKey(account_name, password, role=key_type)

        privkey = k.get_private_key()
        print('{} private: {}'.format(
            key_type, str(privkey)))  # we need explicit str() conversion!

        # pubkey with default prefix GPH
        pubkey = k.get_public_key()

        # pubkey with correct prefix
        key[key_type] = format(pubkey, bitshares.prefix)
        print('{} public: {}\n'.format(key_type, key[key_type]))

    try:
        bitshares.create_account(
            account_name,
            registrar=parent_account,
            referrer=account['id'],
            referrer_percent=0,
            password=password,
            storekeys=broadcast,
        )
    except MissingKeyError:
        log.critical(
            'No key for {} in storage, use `uptick addkey` to add'.format(
                parent_account))
        sys.exit(1)