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)))
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
async def test_update_memo_key(bitshares, ltm_account, default_account): from bitsharesbase.account import PasswordKey account = ltm_account password = "******" memo_key = PasswordKey(account, password, role="memo") pubkey = memo_key.get_public_key() await bitshares.update_memo_key(pubkey, account=account)
def keys(): password = "******" # P5JNdP5NtnuaispDGX4gUdx6WkEXYLCrkvKYm6dH7mbXgX76VzLz keys = dict(active_key=str( PasswordKey("faucet", password, role="active").get_private_key()), owner_key=str( PasswordKey("faucet", password, role="owner").get_private_key()), memo_key=str( PasswordKey("faucet", password, role="memo").get_private_key())) click.echo(keys)
def newassociation(ctx, association_name, account, password, members): """ Create a new account """ members_arr = [] members_arr.append(members) ctx.bitshares.create_account(association_name, registrar="vel-ma", referrer="vel-ma", referrer_percent=50, owner_key=None, active_key=None, memo_key=None, additional_owner_keys=[], additional_active_keys=[], additional_owner_accounts=members, additional_active_accounts=[], proxy_account="proxy-to-self", storekeys=True, password=password) foreign_account = format( PasswordKey(association_name, password, "active").get_public(), "TEST") ctx.bitshares.allow(foreign_account, weight=1, account="vel-ma", permission="active", threshold=int((len(members_arr) / 2) + 1))
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)
def allow(ctx, foreign_account, permission, weight, threshold, account): if not foreign_account: from bitsharesbase.account import PasswordKey pwd = click.prompt("Password for Key Derivation", hide_input=True, confirmation_prompt=True) foreign_account = format( PasswordKey(account, pwd, permission).get_public(), "BTS") pprint( ctx.bitshares.allow(foreign_account, weight=weight, account=account, permission=permission, threshold=threshold))
def buy(ordertype, base, price, amount, expiration=None, killfill=False, account=None, returnOrderId=False): from bitsharesbase.account import PasswordKey, PublicKey active_key = str( PasswordKey(account=MEMBER["account_name"], password=MEMBER["password"], role="active").get_private_key()) bts_obj = BitShares(node=BITSHARES_NODE, keys=active_key, nobroadcast=NOBROADCAST) market = Market(base, bitshares_instance=bts_obj) order = market.buy(price, amount, expiration, killfill, account, returnOrderId) print(" * Placed order: " + str( market.buy(price, amount, expiration, killfill, account, returnOrderId))) bts_obj.clear() print()
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?")
def validateCurrentPage(self): c = self.currentId() if (c == AccountWizard.PAGE_INTRO): self.ui.passwordConfirm.setText("") if self.ui.rNewBrain.isChecked(): generated = self.ui.brainkeyView.toPlainText() if not generated: bk = BrainKey() # this will generate a new one self.ui.brainkeyView.setPlainText(bk.get_brainkey()) if self.ui.rOldBrain.isChecked(): self.ui.brainkeyView.setPlainText("") #self.button(QtGui.QWizard.NextButton).clicked.emit(True) if (c == AccountWizard.PAGE_OLD_BRAIN): entered = self.ui.brainkeyEdit.toPlainText() if not (entered): return False bk = BrainKey(entered) generated = self.ui.brainkeyView.toPlainText() if generated: # compare normalized brainkeys old_bk = BrainKey(generated) if old_bk.get_brainkey() != bk.get_brainkey(): showerror( "Brainkey does not match the generated one", additional= "If you lose your brainkey, you will lose your account and funds." ) return False # TODO: proper way to verify brain key? if len(bk.get_brainkey()) < 25 * 2: showerror("This does not look like a brain key") return False bk.sequence = 0 owner_key = bk.get_private() active_key_index = 0 #find_first_unused_derived_key_index( owner_key ) active_key = owner_key.derive_private_key(active_key_index) memo_key_index = 0 #find_first_unused_derived_key_index( active_key ) memo_key = active_key.derive_private_key(memo_key_index) #bk.sequence = 0; active_key = bk.get_private() #bk.sequence = 1; owner_key = bk.get_private() #bk.sequence = 2; memo_key = bk.get_private() privs = "" privs += str(active_key) + "\n" privs += str(owner_key) + "\n" privs += str(memo_key) + "\n" print("Private keys (a,o,m)" + privs) #pubs = "" #pubs += str(active_key.pubkey) + "\n" #pubs += str(owner_key.pubkey) + "\n" #pubs += str(memo_key.pubkey) + "\n" self.ui.pubkeyOwner.setText(str(owner_key.pubkey)) self.ui.pubkeyActive.setText(str(active_key.pubkey)) self.ui.pubkeyMemo.setText(str(memo_key.pubkey)) #self.ui.publicKeys.setPlainText(pubs) self.ui.privateKeys.setPlainText(privs) if (c == AccountWizard.PAGE_NEW_PASS): account_name = self.ui.inventAccount.text() password = self.ui.inventPassword.text() if not (account_name) or not (password): return False if len(password) < 12: showerror("Password should contain at least 12 characters") return False self.ui.oldAccount.setText(account_name) self.ui.inventPassword.setReadOnly(True) self.ui.passwordConfirm.setText("Confirm your password") if (c == AccountWizard.PAGE_OLD_PASS): account_name = self.ui.oldAccount.text() password = self.ui.oldPassword.text() if not (account_name) or not (password): return False old_password = self.ui.inventPassword.text() if old_password and (password != old_password): showerror( "Password you entered during previous step does not match this one", additional= "If you lose your password, you will lose your account and funds." ) return False active_key = PasswordKey(account_name, password, role="active") owner_key = PasswordKey(account_name, password, role="owner") memo_key = PasswordKey(account_name, password, role="memo") #print("Active key:", active_key.get_private(), active_key.get_public()) #print("Owner key:", owner_key.get_private(), owner_key.get_public()) #print("Memo key:", memo_key.get_private(), memo_key.get_public()) privs = "" privs += str(active_key.get_private()) + "\n" privs += str(owner_key.get_private()) + "\n" privs += str(memo_key.get_private()) + "\n" print("Private keys (a,o,m)\n" + privs) #pubs = "" #pubs += str(active_key.get_public()) + "\n" #pubs += str(owner_key.get_public()) + "\n" #pubs += str(memo_key.get_public()) + "\n" self.ui.pubkeyOwner.setText(str(owner_key.get_public())) self.ui.pubkeyActive.setText(str(active_key.get_public())) self.ui.pubkeyMemo.setText(str(memo_key.get_public())) self.ui.accountName.setText(account_name) #self.ui.publicKeys.setPlainText(pubs) self.ui.accountEdit.setText(account_name) self.ui.privateKeys.setPlainText(privs) if (c == AccountWizard.PAGE_REGISTER): account_name = self.ui.accountName.text() self.ui.accountEdit.setText(account_name) #pubkeys = self.ui.publicKeys.toPlainText() #privkeys = self.ui.privateKeys.toPlainText() owner_key = self.ui.pubkeyOwner.text() active_key = self.ui.pubkeyActive.text() memo_key = self.ui.pubkeyMemo.text() if not account_name: showerror("Please enter account name", account_name) return False if not owner_key or not active_key or not memo_key: showerror("Please enter all three (owner, active, memo) keys") return False if self.ui.faucetBox.isVisible() == True: #config = self.iso.store.configStorage proxy = self.iso.get_proxy_config() print("Faucet using proxy", proxy) selected = self.ui.faucetBox.currentText() faucet = None for name, url, refurl, factory in KnownFaucets: if name == selected: faucet = BTSFaucet(url, refurl, proxyUrl=proxy) break if not faucet: showerror("No faucet selected") return False try: reg = faucet.register(account_name, owner_key, active_key, memo_key, refcode=None, referrer=None) except Exception as e: import traceback traceback.print_exc() showexc(e) return False except: import traceback traceback.print_exc() return False from pprint import pprint print("REG:") pprint(reg) if self.ui.registrarBox.isVisible() == True: selected = self.ui.registrarBox.currentText() data = { 'name': account_name, 'owner_key': owner_key, 'active_key': active_key, 'memo_key': memo_key, } try: trx = QTransactionBuilder.QRegisterAccount( selected, selected, data, isolator=self.iso) if not trx: return False except BaseException as error: showexc(error) return False self.ui.accountStatus.setText("") self.ui.privkeysStatus.setText("Your account has been registered.") #self.button(QtGui.QWizard.NextButton).clicked.emit(True) return True
memo_key=None, owner_account="vel-ma", active_account=None, password="******", additional_owner_keys=[], additional_active_keys=[], additional_owner_accounts=["vel-ma", "oatrick1995"], additional_active_accounts=[], proxy_account="proxy-to-self", storekeys=True)) testnet.broadcast() ##allow - change threashold foreign_account = format( PasswordKey("mutual-insurance-fund-993", "somethingstupid", "active").get_public(), "TEST") print_tx( testnet.allow( foreign_account, weight=1, account="vel-ma", permission="active", threshold=2, )) ##transfer funds print_tx( testnet.transfer("mutual-insurance-fund-993", 5, "TEST", account=account)) ##proposal - claim ##vote - vote
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)
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")
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)