def calc_rshares(steemd_instance, account, vote_percent): """ Calc current rshares for an account :param Steem steemd_instance: Steem() instance to use when accesing a RPC :param str account: :param float vote_percent: up percent, 0-100 """ a = Account(account, steemd_instance=steemd_instance) cv = Converter(steemd_instance) try: voting_power = get_voting_power(steemd_instance, account) b = a.get_balances() log.info('current voting_power: {}, {:.2f}'.format( account, voting_power)) except Exception as e: log.error('error in calc_rshares(): %s', e) return False # look for detailed code in libraries/chain/steem_evaluator.cpp, search used_power vesting_shares = b['available']['GESTS'] sp = cv.vests_to_sp(vesting_shares) rshares = cv.sp_to_rshares(sp, voting_power=voting_power * 100, vote_pct=vote_percent * 100) return rshares
def main(): parser = argparse.ArgumentParser( description='show user balances', epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues' ) parser.add_argument('account', help='account name') parser.add_argument('-c', '--config', default='./common.yml', help='specify custom path for config file') args = parser.parse_args() # parse config with open(args.config, 'r') as ymlfile: conf = yaml.load(ymlfile) golos = Steem(nodes=conf['nodes_old'], no_broadcast=True) a = Account(args.account, steemd_instance=golos) b = a.get_balances() cv = Converter(golos) gp = cv.vests_to_sp(b['total']['GESTS']) for asset in b['savings']: print('{:<15}{:>18.3f}'.format('SAVINGS_{}'.format(asset), b['savings'][asset])) for asset in b['total']: print('{:<15}{:>18.3f}'.format('{}:'.format(asset), b['available'][asset])) print('{:<15}{:>18.3f}'.format('GP:', gp)) print('{:<15}{:>18.3f}'.format('MGESTS:', b['total']['GESTS'] / 1000000))
def main(): parser = argparse.ArgumentParser( description='Scan account history looking for transfers', epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues' ) parser.add_argument('-d', '--debug', action='store_true', help='enable debug output'), parser.add_argument('-c', '--config', default='./common.yml', help='specify custom path for config file') parser.add_argument( '-a', '--amount', type=float, default=0, help='minimal transfer amount to look for (default: 0)') parser.add_argument( '-l', '--limit', type=int, default=50, help='limit number of transactions to scan, default: 50') parser.add_argument('account', help='account to scan') 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.load(ymlfile) golos = Steem(nodes=conf['nodes_old'], keys=conf['keys']) account = Account(args.account, steemd_instance=golos) history = account.rawhistory(only_ops=['transfer'], limit=args.limit) for item in history: #pprint(item) timestamp = datetime.strptime(item[1]['timestamp'], '%Y-%m-%dT%H:%M:%S') t_from = item[1]['op'][1]['from'] to = item[1]['op'][1]['to'] amount = Amount(item[1]['op'][1]['amount']) if amount.amount > args.amount: print('{}: {:<16} -> {:<16}, {}'.format(timestamp, t_from, to, amount))
def main(ctx, no_header, no_sum): """Show multiple users balances.""" if not no_header: print('{:<20} {:>10} {:>11} {:>11}'.format('Account', 'GBG', 'GOLOS', 'GP')) print('--------------------') sum_gbg = float() sum_golos = float() sum_gp = float() for acc in ctx.config['accs']: account = Account(acc) balance = account.get_balances() cv = ctx.helper.converter gp = cv.vests_to_sp(balance['total']['GESTS']) print('{:<20} {:>10} {:>10} {:>10.0f}'.format( acc, balance['total']['GBG'], balance['total']['GOLOS'], gp)) sum_gbg += balance['total']['GBG'] sum_golos += balance['total']['GOLOS'] sum_gp += gp if not no_sum: print('--------------------') print('{:<20} {:>10.3f} {:>10.3f} {:>10.0f}'.format( 'Totals:', sum_gbg, sum_golos, sum_gp))
def __init__(self, account_name: str, comments_only: bool = False, steemd_instance=None): self.steem = steemd_instance or shared_steemd_instance() self.comments_only = comments_only self.account = Account(account_name, steemd_instance=steemd_instance) self.history = self.account.history_reverse(filter_by="comment") self.seen_items = set()
def main(ctx, to, amount, to_vesting, account): """Claim funds from accumulative balance to tip balance or to vesting.""" if not amount: acc = Account(account) balance = acc.get_balances() amount = balance['accumulative']['GOLOS'] if not to: to = account ctx.helper.claim(to, amount, to_vesting=to_vesting, account=account)
def main(ctx, account): """Calculate profit from vesting holdings.""" props = ctx.helper.get_dynamic_global_properties() acc = Account(account) balance = acc.get_balances() account_vesting = balance['total']['GESTS'] vesting_fund = Amount(props['total_vesting_shares']) daily_emission = ctx.helper.calc_inflation() vesting_share = account_vesting / vesting_fund.amount ctx.log.info(f'{account} vesting share: {vesting_share:.4%}') daily_account_vesting = vesting_share * daily_emission.vesting ctx.log.info(f'{account} daily vesting: {daily_account_vesting:.0f}')
def appendSigner(self, account, permission): assert permission in ["active", "owner", "posting"], "Invalid permission" account = Account(account, steemd_instance=self.steemd) required_treshold = account[permission]["weight_threshold"] def fetchkeys(account, level=0): if level > 2: return [] r = [] for authority in account[permission]["key_auths"]: wif = self.wallet.getPrivateKeyForPublicKey(authority[0]) if wif: r.append([wif, authority[1]]) if sum([x[1] for x in r]) < required_treshold: # go one level deeper for authority in account[permission]["account_auths"]: auth_account = Account(authority[0], steemd_instance=self.steemd) r.extend(fetchkeys(auth_account, level + 1)) return r keys = fetchkeys(account) self.wifs.extend([x[0] for x in keys])
def main(ctx, amount_limit, limit, account): """Scan account history looking for transfers.""" account = Account(account) history = account.rawhistory(only_ops=['transfer'], limit=limit) for item in history: ctx.log.debug(pformat(item)) timestamp = parse_time(item[1]['timestamp']) from_ = item[1]['op'][1]['from'] to = item[1]['op'][1]['to'] amount = Amount(item[1]['op'][1]['amount']) memo = item[1]['op'][1]['memo'] if amount.amount > amount_limit: print('{}: {:<16} -> {:<16}, {}, {}'.format(timestamp, from_, to, amount, memo))
def addFollower(account_name, follower): print('addFollower', account_name, follower) res = tnt_server.call('add_follower', account_name, follower) if not res[0]: with suppress(Exception): followers = getFollowersWithDirection(Account(account_name)) followers.append(follower) followers_space.insert((account_name, followers)) tnt_server.call('add_follower', account_name, follower)
def get_voting_power(self, account: str) -> float: """ Calculate real voting power instead of stale info in get_account() :param str account: account name :return: voting power 0-100 """ acc = Account(account) vp = acc.voting_power() last_vote_time = parse_time(acc['last_vote_time']) elapsed_time = datetime.utcnow() - last_vote_time regenerated_power = STEEMIT_100_PERCENT * elapsed_time.total_seconds( ) / STEEMIT_VOTE_REGENERATION_SECONDS current_power = min(vp + regenerated_power / 100, 100) return current_power
def main(ctx, min_balance, to): """Withdraw from vesting balance of multiple accounts to specified account.""" cv = ctx.helper.converter min_balance = cv.sp_to_vests(min_balance) for account in ctx.config['accs']: acc = Account(account) balance = acc.get_balances() vests = balance['available']['GESTS'] withdraw_amount = vests - min_balance ctx.log.info( 'withdrawing {:.4f} MGESTS ({:.3f} GOLOS): {} -> {}'.format( withdraw_amount / 1000000, cv.vests_to_sp(withdraw_amount), account, to ) ) ctx.helper.set_withdraw_vesting_route(to, percentage=100, account=account, auto_vest=False) ctx.helper.withdraw_vesting(withdraw_amount, account=account)
def addSigningInformation(self, account, permission): """ This is a private method that adds side information to a unsigned/partial transaction in order to simplify later signing (e.g. for multisig or coldstorage) """ accountObj = Account(account, steemd_instance=self.steemd) authority = accountObj[permission] # We add a required_authorities to be able to identify # how to sign later. This is an array, because we # may later want to allow multiple operations per tx self.update({"required_authorities": {account: authority}}) for account_auth in authority["account_auths"]: account_auth_account = Account(account_auth[0], steemd_instance=self.steemd) self["required_authorities"].update( {account_auth[0]: account_auth_account.get(permission)}) # Try to resolve required signatures for offline signing self["missing_signatures"] = [x[0] for x in authority["key_auths"]] # Add one recursion of keys from account_auths: for account_auth in authority["account_auths"]: account_auth_account = Account(account_auth[0], steemd_instance=self.steemd) self["missing_signatures"].extend( [x[0] for x in account_auth_account[permission]["key_auths"]]) self["blockchain"] = self.steemd.chain_params
def main(ctx, account): """Show account balances.""" account = Account(account) balance = account.get_balances() print('{:<15}{:>18.3f}'.format('Claim GOLOS:', balance['accumulative']['GOLOS'])) print('{:<15}{:>18.3f}'.format('Tip GOLOS:', balance['tip']['GOLOS'])) for asset in balance['savings']: print('{:<15}{:>18.3f}'.format('SAVINGS_{}'.format(asset), balance['savings'][asset])) for asset in balance['available']: print('{:<15}{:>18.3f}'.format('{}:'.format(asset), balance['available'][asset])) gp = ctx.helper.converter.vests_to_sp(balance['total']['GESTS']) print('{:<15}{:>18.3f}'.format('GP:', gp)) print('{:<15}{:>18.3f}'.format('MGESTS:', balance['total']['GESTS'] / 1000000))
def get_voting_power(steemd_instance, account): """ Calculate real voting power instead of stale info in get_account() :param Steem steemd_instance: Steem() instance to use when accesing a RPC :param str account: account name """ try: a = Account(account, steemd_instance=steemd_instance) vp = a.voting_power() except Exception as e: log.error('error in get_voting_power(): %s', e) return False last_vote_time = datetime.strptime(a['last_vote_time'], '%Y-%m-%dT%H:%M:%S') elapsed_time = datetime.utcnow() - last_vote_time regenerated_power = STEEMIT_100_PERCENT * elapsed_time.total_seconds( ) / STEEMIT_VOTE_REGENERATION_SECONDS current_power = vp + regenerated_power / 100 if current_power > 100: current_power = 100 return current_power
def fetchkeys(account, level=0): if level > 2: return [] r = [] for authority in account[permission]["key_auths"]: wif = self.wallet.getPrivateKeyForPublicKey(authority[0]) if wif: r.append([wif, authority[1]]) if sum([x[1] for x in r]) < required_treshold: # go one level deeper for authority in account[permission]["account_auths"]: auth_account = Account(authority[0], steemd_instance=self.steemd) r.extend(fetchkeys(auth_account, level + 1)) return r
def test_history(): a = Account('barbara2') h1 = [x['index'] for x in list(a.history())] h2 = [x['index'] for x in list(a.history_reverse())] # pprint(list(zip(h1, h2[::-1]))) # various tests of equality should pass assert len(h1) == len(h2) assert set(h1) == set(h2) == set(range(a.virtual_op_count() + 1)) assert h1 == h2[::-1] == list(range(a.virtual_op_count() + 1))
def getAccount(self, pub): """Get the account data for a public key.""" name = self.getAccountFromPublicKey(pub) if not name: return {"name": None, "type": None, "pubkey": pub} else: try: account = Account(name) except: return keyType = self.getKeyType(account, pub) return { "name": name, "account": account, "type": keyType, "pubkey": pub }
def processComment(op): comment_body = op['body'] if not comment_body or comment_body.startswith('@@ '): return try: post = Post(op, steemd_instance=steem) except PostDoesNotExist as err: print('Err update post', err) return pkey = getPostKey(post) print('post: ', pkey) if not pkey or pkey in processed_posts: return processed_posts[pkey] = True author_account = Account(op['author'], steemd_instance=steem) processMentions(author_account, comment_body, op) if op['parent_author']: if op['parent_author'] != op['author']: # no need to notify self of own comments title = 'Golos' body = '@%s replied to your post or comment' % (op['author']) url = '%s/@%s/recent-replies' % ( STEEMIT_WEBCLIENT_ADDRESS, op['parent_author'] ) profile = author_account.profile pic = img_proxy_prefix + profile['profile_image'] \ if profile and 'profile_image' in profile else '' tnt_server.call( 'notification_add', op['parent_author'], NTYPES['comment_reply'], title, body, url, pic ) else: followers = getFollowers(author_account) for follower in followers: tnt_server.call('notification_add', follower, NTYPES['feed'])
class Blog: """ Obtain a list of blog posts for an account. Args: account_name (str): Name of the account comments_only (bool): (Default False). Toggle between posts and comments. steemd_instance (Steemd): Steemd instance overload Returns: Generator with Post objects in reverse chronological order. Example: To get all posts, you can use either generator: :: gen1 = Blog('furion') gen2 = b.all() next(gen1) next(gen2) To get some posts, you can call `take()`: :: b = Blog('furion') posts = b.take(5) """ def __init__(self, account_name: str, comments_only: bool = False, steemd_instance=None): self.steem = steemd_instance or shared_steemd_instance() self.comments_only = comments_only self.account = Account(account_name, steemd_instance=steemd_instance) self.history = self.account.history_reverse(filter_by="comment") self.seen_items = set() def take(self, limit=5): """ Take up to n (n = limit) posts/comments at a time. You can call this method as many times as you want. Once there are no more posts to take, it will return []. Returns: List of posts/comments in a batch of size up to `limit`. """ # get main posts only comment_filter = is_comment if self.comments_only else complement( is_comment) hist = filter(comment_filter, self.history) # filter out reblogs hist2 = filter(lambda x: x["author"] == self.account.name, hist) # post edits will re-appear in history # we should therefore filter out already seen posts def ensure_unique(post): if post["permlink"] not in self.seen_items: self.seen_items.add(post["permlink"]) return True unique = filter(ensure_unique, hist2) serialized = filter(bool, map(silent(Post), unique)) batch = take(limit, serialized) return batch def all(self): """A generator that will return ALL of account history.""" while True: chunk = self.take(10) if chunk: yield from iter(chunk) else: break def __iter__(self): return self def __next__(self): next_item = first(self.take(1)) if not next_item: raise StopIteration return next_item
def main(ctx, account): """Show account object.""" acc = Account(account) js = json.dumps(acc, indent=4) print(js)
def get_bandwidth(self, account: str, type_: str = 'market') -> bandwidth: """ Estimate current account bandwidth and usage ratio. :param str account: account name :param str type_: 'market' used for transfer operations, forum - for posting and voting, custom - custom ops """ acc = Account(account) global_props = self.get_dynamic_global_properties() account_vshares = Amount(acc['vesting_shares'])['amount'] delegated_vshares = Amount(acc['delegated_vesting_shares'])['amount'] received_vshares = Amount(acc['received_vesting_shares'])['amount'] account_vshares = account_vshares - delegated_vshares + received_vshares log.debug('{:.<30}{:.>30.0f}'.format('account_vshares:', account_vshares)) # get bandwidth info from network if type_ == 'market': account_average_bandwidth = int(acc['average_market_bandwidth']) last_bw_update_time = parse_time( acc['last_market_bandwidth_update']) elif type_ == 'forum': account_average_bandwidth = int(acc['average_bandwidth']) last_bw_update_time = parse_time(acc['last_bandwidth_update']) elif type == 'custom': raise NotImplementedError # seconds passed since last bandwidth update elapsed_time = (datetime.utcnow() - last_bw_update_time).total_seconds() max_virtual_bandwidth = int(global_props['max_virtual_bandwidth']) log.debug('{:.<30}{:.>30.0f}'.format('max_virtual_bandwidth:', max_virtual_bandwidth)) log.debug('{:.<30}{:.>30.0f}'.format( 'max_virtual_bandwidth, KB:', max_virtual_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024)) total_vesting_shares = Amount( global_props['total_vesting_shares']).amount log.debug('{:.<30}{:.>30.0f}'.format('total_vesting_shares:', total_vesting_shares)) # calculate bandwidth regeneration if elapsed_time > STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS: new_bandwidth = 0 else: new_bandwidth = ( (STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS - elapsed_time) * account_average_bandwidth ) / STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS # example code to estimate whether your new transaction will exceed bandwidth or not # trx_size = 1024*2 # imagine 2 KB trx # trx_bandwidth = trx_size * STEEMIT_BANDWIDTH_PRECISION # account_average_bandwidth = new_bandwidth + trx_bandwidth account_average_bandwidth = new_bandwidth log.debug('{:.<30}{:.>30.0f}'.format('account_average_bandwidth:', account_average_bandwidth)) # c++ code: # has_bandwidth = (account_vshares * max_virtual_bandwidth) > (account_average_bandwidth * total_vshares); avail = account_vshares * max_virtual_bandwidth used = account_average_bandwidth * total_vesting_shares log.debug('{:.<30}{:.>30.0f}'.format('used:', used)) log.debug('{:.<30}{:.>30.0f}'.format('avail:', avail)) used_ratio = used / avail log.debug('{:.<30}{:.>30.2%}'.format('used ratio:', used_ratio)) # account bandwidth is actually a representation of sent bytes, so get these bytes used_kb = account_average_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024 # market ops uses x10 bandwidth if type_ == 'market': used_kb = used_kb / 10 log.debug('{:.<30}{:.>30.2f}'.format('used KB:', used_kb)) # available account bandwidth is a fraction of max_virtual_bandwidth based on his portion of # total_vesting_shares avail_kb = account_vshares / total_vesting_shares * max_virtual_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024 if type_ == 'market': avail_kb = avail_kb / 10 log.debug('{:.<30}{:.>30.2f}'.format('avail KB:', avail_kb)) if used < avail: log.debug('has bandwidth') else: log.debug('no bandwidth') return bandwidth(used_kb, avail_kb, used_ratio)
def get_bandwidth(steemd_instance, account, type='market'): """ Estimate current account bandwidth and usage ratio :param Steem steemd_instance: Steem() instance to use when accesing a RPC :param str account: account name :param str type: 'market' used for transfer operations, forum - for posting and voting """ a = Account(account, steemd_instance=steemd_instance) global_props = steemd_instance.get_dynamic_global_properties() account_vshares = Amount(a['vesting_shares']).amount log.debug('{:.<30}{:.>30.0f}'.format('account_vshares:', account_vshares)) # get bandwidth info from network if type == 'market': account_average_bandwidth = int(a['average_market_bandwidth']) last_bw_update_time = datetime.strptime( a['last_market_bandwidth_update'], '%Y-%m-%dT%H:%M:%S') elif type == 'forum': account_average_bandwidth = int(a['average_bandwidth']) last_bw_update_time = datetime.strptime(a['last_bandwidth_update'], '%Y-%m-%dT%H:%M:%S') # seconds passed since last bandwidth update elapsed_time = (datetime.utcnow() - last_bw_update_time).total_seconds() max_virtual_bandwidth = int(global_props['max_virtual_bandwidth']) log.debug('{:.<30}{:.>30.0f}'.format('max_virtual_bandwidth:', max_virtual_bandwidth)) log.debug('{:.<30}{:.>30.0f}'.format( 'max_virtual_bandwidth, KB:', max_virtual_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024)) total_vesting_shares = Amount(global_props['total_vesting_shares']).amount log.debug('{:.<30}{:.>30.0f}'.format('total_vesting_shares:', total_vesting_shares)) # calculate bandwidth regeneration if elapsed_time > STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS: new_bandwidth = 0 else: new_bandwidth = ( ((STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS - elapsed_time) * account_average_bandwidth) / STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS) # example code to estimate whether your new transaction will exceed bandwidth or not #trx_size = 1024*2 # imagine 2 KB trx #trx_bandwidth = trx_size * STEEMIT_BANDWIDTH_PRECISION #account_average_bandwidth = new_bandwidth + trx_bandwidth account_average_bandwidth = new_bandwidth log.debug('{:.<30}{:.>30.0f}'.format('account_average_bandwidth:', account_average_bandwidth)) # c++ code: # has_bandwidth = (account_vshares * max_virtual_bandwidth) > (account_average_bandwidth * total_vshares); avail = account_vshares * max_virtual_bandwidth used = account_average_bandwidth * total_vesting_shares log.debug('{:.<30}{:.>30.0f}'.format('used:', used)) log.debug('{:.<30}{:.>30.0f}'.format('avail:', avail)) used_ratio = used / avail log.info('{:.<30}{:.>30.2%}'.format('used ratio:', used_ratio)) # account bandwidth is actually a representation of sent bytes, so get these bytes used_kb = account_average_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024 # market ops uses x10 bandwidth if type == 'market': used_kb = used_kb / 10 log.info('{:.<30}{:.>30.2f}'.format('used KB:', used_kb)) # available account bandwidth is a fraction of max_virtual_bandwidth based on his portion of total_vesting_shares avail_kb = account_vshares / total_vesting_shares * max_virtual_bandwidth / STEEMIT_BANDWIDTH_PRECISION / 1024 if type == 'market': avail_kb = avail_kb / 10 log.info('{:.<30}{:.>30.2f}'.format('avail KB:', avail_kb)) if used < avail: log.debug('has bandwidth') else: log.debug('no bandwidth') return used / avail * 100
def main(): parser = argparse.ArgumentParser( description= 'Scan account history looking for author or curator payouts', epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues' ) parser.add_argument('-d', '--debug', action='store_true', help='enable debug output'), parser.add_argument('-c', '--config', default='./common.yml', help='specify custom path for config file') parser.add_argument( '-t', '--type', default='author', choices=['author', 'curator'], help='reward type, "author" or "curator", default: author') parser.add_argument('account', help='account to scan') 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.load(ymlfile) if args.type == 'author': ops = ['author_reward'] elif args.type == 'curator': ops = ['curation_reward'] golos = Steem(nodes=conf['nodes_old'], keys=conf['keys']) cv = Converter(golos) account = Account(args.account, steemd_instance=golos) history = account.rawhistory(only_ops=ops) for item in history: #pprint(item) permlink = item[1]['op'][1]['permlink'] payout_timestamp = datetime.strptime(item[1]['timestamp'], '%Y-%m-%dT%H:%M:%S') sbd_payout = Amount(item[1]['op'][1]['sbd_payout']) steem_payout = Amount(item[1]['op'][1]['steem_payout']) vesting_payout = Amount(item[1]['op'][1]['vesting_payout']) gp = cv.vests_to_sp(vesting_payout.amount) golos_payout = steem_payout.amount + gp gpg_repr = sbd_payout.amount + functions.convert_golos_to_gbg( golos, golos_payout, price_source='market') print('{} {}: {} {} {:.3f} GP, GBG repr: {:.3f}'.format( payout_timestamp, permlink, sbd_payout, steem_payout, gp, gpg_repr))
def main(): parser = argparse.ArgumentParser( description='show multiple users balances', epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues' ) parser.add_argument('-c', '--config', default='./common.yml', help='specify custom path for config file') parser.add_argument('--no-header', action='store_true', help='supress header') parser.add_argument('--no-sum', action='store_true', help='supress summary output') parser.add_argument('-d', '--debug', action='store_true', help='enable debug output'), 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.load(ymlfile) golos = Steem(nodes=conf['nodes_old'], no_broadcast=True) if not args.no_header: print('{:<20} {:>10} {:>11} {:>11}'.format('Account', 'GBG', 'GOLOS', 'GP')) print('--------------------') sum_gbg = float() sum_golos = float() sum_gp = float() for acc in conf['accs']: a = Account(acc, steemd_instance=golos) b = a.get_balances() cv = Converter(golos) gp = cv.vests_to_sp(b['total']['GESTS']) print('{:<20} {:>10} {:>10} {:>10.0f}'.format( acc, b['total']['GBG'], b['total']['GOLOS'], gp)) sum_gbg += b['total']['GBG'] sum_golos += b['total']['GOLOS'] sum_gp += gp if not args.no_sum: print('--------------------') print('{:<20} {:>10.3f} {:>10.3f} {:>10.0f}'.format( 'Totals:', sum_gbg, sum_golos, sum_gp))
def main(): parser = argparse.ArgumentParser( description= 'This script is for changing account keys. By default, random password are geneeated.', epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues' ) parser.add_argument('-d', '--debug', action='store_true', help='enable debug output'), parser.add_argument('-c', '--config', default='./common.yml', help='specify custom path for config file') parser.add_argument('account', help='account name'), parser.add_argument('-p', '--password', help='manually specify a password'), parser.add_argument('--broadcast', action='store_true', default=False, help='broadcast transactions'), 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.load(ymlfile) b = not args.broadcast golos = Steem(nodes=conf['nodes_old'], no_broadcast=False, keys=conf['keys']) account_name = args.account account = Account(args.account, steemd_instance=golos) # random password if args.password: password = args.password else: password = functions.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, golos.chain_params["prefix"]) print('{} public: {}\n'.format(key_type, key[key_type])) # prepare for json format owner_key_authority = [[key['owner'], 1]] active_key_authority = [[key['active'], 1]] posting_key_authority = [[key['posting'], 1]] owner_accounts_authority = [] active_accounts_authority = [] posting_accounts_authority = [] s = { 'account': account_name, 'memo_key': key['memo'], '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 }, 'posting': { 'account_auths': posting_accounts_authority, 'key_auths': posting_key_authority, 'weight_threshold': 1 }, 'prefix': golos.chain_params["prefix"] } #pprint(s) op = operations.AccountUpdate(**s) golos.finalizeOp(op, args.account, "owner")