def main():

    parser = argparse.ArgumentParser(
            description='Calculate actual voting power',
            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='specify account which VP should be estimated')

    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("%(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'])
    vp = functions.get_voting_power(golos, args.account)
    log.info('VP of {}: {:.2f}'.format(args.account, vp))
Beispiel #2
0
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))
Beispiel #4
0
def main():

    parser = argparse.ArgumentParser(
        description='Create account',
        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('-p', '--password', help='manually specify a password')
    parser.add_argument('creator',
                        help='parent account who will create child account')
    parser.add_argument('account', help='new account name')
    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'])

    # random password
    if args.password:
        password = args.password
    else:
        password = functions.generate_password()

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

    golos.create_account(args.account, creator=args.creator, password=password)
def main():

    parser = argparse.ArgumentParser(
        description='transfer GOLOS to GOLOS POWER',
        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('--broadcast',
                        action='store_true',
                        default=False,
                        help='broadcast transactions'),
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    parser.add_argument('f', help='from'),
    parser.add_argument('to', help='to'),
    parser.add_argument('amount', help='amount'),
    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)

    # initialize steem instance
    log.debug('broadcast: %s', args.broadcast)
    # toggle args.broadcast
    b = not args.broadcast
    golos = Steem(nodes=conf['nodes_old'], no_broadcast=b, keys=conf['keys'])

    golos.transfer_to_vesting(args.amount, to=args.to, account=args.f)
Beispiel #6
0
def inspect_steemd_implementation():
    """ Compare implemented methods with current live deployment of steemd. """
    _apis = distinct(pluck('api', api_methods))
    _methods = set(pluck('method', api_methods))

    avail_methods = []
    s = Steem(re_raise=False)
    for api in _apis:
        err = s.exec('nonexistentmethodcall', api=api)
        [
            avail_methods.append(x)
            for x in err['data']['stack'][0]['data']['api'].keys()
        ]

    avail_methods = set(avail_methods)

    print("\nMissing Methods:")
    pprint(avail_methods - _methods)

    print("\nLikely Deprecated Methods:")
    pprint(_methods - avail_methods)
def main():

    parser = argparse.ArgumentParser(
        description='This script is for generating a keypair.',
        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')
    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=False,
                  keys=conf['keys'])

    password = functions.generate_password()

    a = bytes(password, 'utf8')
    s = hashlib.sha256(a).digest()

    privkey = PrivateKey(hexlify(s).decode('ascii'))
    print('private: {}'.format(
        str(privkey)))  # we need explicit str() conversion!

    # pubkey with correct prefix
    key = format(privkey.pubkey, golos.chain_params["prefix"])
    print('public: {}'.format(key))
Beispiel #8
0
def main():

    parser = argparse.ArgumentParser(
        description='Get witnesses price feed and estimate futher median price',
        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')
    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("%(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'])

    if args.debug:
        verbose = True
    else:
        verbose = False

    log.info('current median price: {:.3f}'.format(
        functions.get_median_price(golos)))
    log.info('estimated median price: {:.3f}'.format(
        functions.estimate_median_price(golos, verbose=verbose)))
    log.info('estimated median price (from feed): {:.3f}'.format(
        functions.estimate_median_price_from_feed(golos)))
Beispiel #9
0
 def __init__(self, *args, **kwargs):
     super(Testcases, self).__init__(*args, **kwargs)
     self.maxDiff = None
     self.steem = Steem()
Beispiel #10
0
NODE = 'wss://ws.golos.io'
AUTHOR = 'whaler-fund'

VOTER = 'feb'

posts = ['bod-na-golose-1-nedelya',
         'bod-na-colose-nedelya-2',
         'bod-na-golose-nedelya-3',
         'bod-na-golose-nedelya-4',
         'bod-na-golose-nedelya-5-skrytaya-ugroza',
         'bod-na-golose-nedelya-6-miloserdie-grizli-i-predlozhenie-k-avtoram',
         'bod-na-golose-nedelya-7-nedostizhimyij-idealxnyij-stroij',
         'bod-na-golose-nedelya-8-vremya-i-regiony']

s = Steem([NODE], no_broadcast=True)

print('Исследуем вотера', VOTER)
print()

hit = 0
hit2 = 0

for pl in posts:
    try:
        p = s.get_content(AUTHOR, pl, 1000)
    except Exception as e:
        print("Ошибка сети", e)
        print('Выполнение прервано. Перезапустите скрипт.')
        exit(1)
    for el in p['active_votes']:
def main():

    parser = argparse.ArgumentParser(
        description='Find all vesting withdrawals with rates and dates',
        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(
        '-m',
        '--min-mgests',
        default=100,
        type=float,
        help=
        'look for account with vesting shares not less than X MGESTS, default is 100'
    )
    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'])

    c = golos.get_account_count()
    log.debug('total accounts: {}'.format(c))

    accs = golos.get_all_usernames()

    start = datetime.utcnow()

    # get all accounts in one batch
    all_accounts = golos.get_accounts(accs)

    # we well get summary info about total withdrawal rate and number of accounts
    sum_rate = float()
    count = int()

    cv = Converter(golos)
    steem_per_mvests = cv.steem_per_mvests()

    for a in all_accounts:
        vshares = Amount(a['vesting_shares'])
        mgests = vshares.amount / 1000000
        rate = Amount(a['vesting_withdraw_rate'])
        d = datetime.strptime(a['next_vesting_withdrawal'],
                              '%Y-%m-%dT%H:%M:%S')

        if mgests > args.min_mgests and rate.amount > 1000:
            # We use own calculation instead of cv.vests_to_sp() to speed up execution
            # avoiding API call on each interation
            rate_gp = rate.amount / 1e6 * steem_per_mvests
            gp = vshares.amount / 1e6 * steem_per_mvests
            sum_rate += rate_gp
            count += 1

            print('{:<16} {:<18} {:>6.0f} {:>8.0f}'.format(
                a['name'], d.strftime('%Y-%m-%d %H:%M'), rate_gp, gp))


# non-pretty format
#            log.info('{} {} {:.0f} / {:.0f}'.format(
#                                       a['name'],
#                                       d.strftime('%Y-%m-%d %H:%M'),
#                                       rate_gp, gp))

    log.debug('accounts iteration took {:.2f} seconds'.format(
        (datetime.utcnow() - start).total_seconds()))

    log.info(
        'numbers of matching accounts on vesting withdrawal: {}'.format(count))
    log.info('sum rate: {:.0f}'.format(sum_rate))
def main():

    parser = argparse.ArgumentParser(
        description='Use this script to estimate potential upvote profit',
        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='specify account which upvote should be estimated')
    parser.add_argument('-p',
                        '--percent',
                        default=100,
                        type=float,
                        help='specify upvote percent')
    parser.add_argument('--curve',
                        default='linear',
                        choices=['quadratic', 'linear'],
                        help='select curve type')
    parser.add_argument('-u',
                        '--url',
                        help='post id in format @author/article or full url')
    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("%(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'])

    if args.curve == 'quadratic':
        if not args.url:
            log.critical(
                'you need to provide --url when using quadratic curve')
            sys.exit(1)
        # extract author and post permlink from args.url
        p = re.search('@(.*?)/([^/]+)', args.url)
        if p == None:
            log.critical('Wrong post id specified')
            sys.exit(1)
        else:
            author = p.group(1)
            log.debug('author: {}'.format(author))

            post_permlink = p.group(2)
            log.debug('permlink: {}'.format(post_permlink))

        post = functions.get_post_content(golos, author, post_permlink)
        if not post:
            log.critical('could not find post in blockchain')
            sys.exit(1)

        # current post rshares
        net_rshares = int(post['net_rshares'])

        # current pending_payout_value, GBG
        current_pending_payout_value = post['pending_payout_value']
        log.info('current pending_payout_value: {}'.format(
            current_pending_payout_value))

        # estimate current expected author reward
        author_payout_gp, author_payout_gbg, author_payout_golos = functions.estimate_author_payout(
            golos, current_pending_payout_value)
        log.info(
            'estimated author payout: {:.3f} GBG, {:.3f} GOLOS, {:.3f} GP'.
            format(author_payout_gbg, author_payout_golos, author_payout_gp))

        rshares = functions.calc_rshares(golos, args.account, args.percent)
        new_rshares = net_rshares + rshares

        new_payout = functions.calc_payout(golos, new_rshares)
        new_payout_gbg = functions.convert_golos_to_gbg(golos,
                                                        new_payout,
                                                        price_source='median')
        new_payout_gbg = Amount('{} GBG'.format(new_payout_gbg))
        log.info('new pending_payout_value: {}'.format(new_payout_gbg))

        payout_diff = new_payout_gbg.amount - current_pending_payout_value.amount
        log.info('pending_payout diff: {:.3f}'.format(payout_diff))

        # estimate new author reward
        author_payout_gp, author_payout_gbg, author_payout_golos = functions.estimate_author_payout(
            golos, new_payout_gbg)
        log.info(
            'new estimated author payout: {:.3f} GBG, {:.3f} GOLOS, {:.3f} GP'.
            format(author_payout_gbg, author_payout_golos, author_payout_gp))

    elif args.curve == 'linear':

        rshares = functions.calc_rshares(golos, args.account, args.percent)
        payout = functions.calc_payout(golos, rshares)
        payout_gbg = functions.convert_golos_to_gbg(golos,
                                                    payout,
                                                    price_source='median')
        payout_gbg = Amount('{} GBG'.format(payout_gbg))
        log.info('raw upvote value: {} or {:.3f} GOLOS'.format(
            payout_gbg, payout))
        author_payout_gp, author_payout_gbg, author_payout_golos = functions.estimate_author_payout(
            golos, payout_gbg)
        log.info(
            'estimated author payout: {:.3f} GBG, {:.3f} GOLOS, {:.3f} GP'.
            format(author_payout_gbg, author_payout_golos, author_payout_gp))

        author_payout_gbg_repr = author_payout_gbg
        author_payout_gbg_repr += functions.convert_golos_to_gbg(
            golos, author_payout_golos, price_source='market')
        author_payout_gbg_repr += functions.convert_golos_to_gbg(
            golos, author_payout_gp, price_source='market')
        log.info(
            'estimated author payout in GBG representation: {:.3f} GBG'.format(
                author_payout_gbg_repr))
Beispiel #13
0
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))
Beispiel #14
0
 def setUp(self):
     self.node = Steem([config["node_url"]])
     self.client = MongoClient(config["database_url"])
     self.client.drop_database(config["database_name"])
     self.database = self.client[config["database_name"]]
Beispiel #15
0
def get_node():
  return Steem([config["node_url"]])
def main():

    parser = argparse.ArgumentParser(
        description='Estimate current bandwidth usage for an account',
        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(
        '-t',
        '--type',
        default='market',
        choices=['market', 'forum'],
        help=
        'bandwidth type to estimate. Market - transfers, forum - posting ops')
    parser.add_argument(
        '-w',
        '--warning',
        default=99,
        type=float,
        help=
        'exit with 1 error code whether bandwidth exceeded specified percent')
    parser.add_argument(
        'account', help='specify account which bandwidth should be estimated')

    verbosity_args = parser.add_mutually_exclusive_group()
    verbosity_args.add_argument(
        '-q',
        '--quiet',
        action='store_true',
        help=
        'do not show any output except errors, just return 0 if has_bandwidth or 1 if not'
    )
    verbosity_args.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)
    if args.quiet == True:
        log.setLevel(logging.CRITICAL)

    handler = logging.StreamHandler()
    #formatter = logging.Formatter("%(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'])

    ratio = functions.get_bandwidth(golos, args.account, args.type)

    if ratio > args.warning:
        log.warning(
            'bandwidth usage ratio execeeded limit: {:.2f}'.format(ratio))
        sys.exit(1)
    else:
        sys.exit(0)
Beispiel #17
0
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))
Beispiel #18
0
def main():

    parser = argparse.ArgumentParser(
        description='Find all GBG conversion requests',
        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('-n',
                        '--notify',
                        action='store_true',
                        help='send message to accounts who uses conversions')
    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'])

    c = golos.get_account_count()
    log.debug('total accounts: {}'.format(c))

    accs = golos.get_all_usernames()

    # obtain median and market prices whether we're going to send a notification
    if args.notify:
        bid = functions.get_market_price(golos)
        median = functions.get_median_price(golos)
        if not bid or not median:
            log.critical('failed to obtain price')
            sys.exit(1)

    start = datetime.utcnow()
    for acc in accs:
        r = golos.get_conversion_requests(acc)
        if r:
            d = datetime.strptime(r[0]['conversion_date'], '%Y-%m-%dT%H:%M:%S')
            print('{:<16} {:<18} {:>7}'.format(r[0]['owner'], r[0]['amount'],
                                               d.strftime('%Y-%m-%d %H:%M')))

            if args.notify:
                msg = conf['notify_message'].format(median, bid)
                functions.transfer(golos, conf['notify_account'], acc, '0.001',
                                   'GBG', msg)

    log.debug('getting conversion requests took {:.2f} seconds'.format(
        (datetime.utcnow() - start).total_seconds()))
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")
def main():

    parser = argparse.ArgumentParser(
        description=
        'withdraw from vesting balance of multiple accounts to specified account',
        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('--broadcast',
                        action='store_true',
                        default=False,
                        help='broadcast transactions'),
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    parser.add_argument(
        '-m',
        '--min-balance',
        default=5,
        type=float,
        help=
        'minimal Golos Power balance which will be left on withdrawing account'
    )
    parser.add_argument('to', help='to'),
    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)

    # initialize steem instance
    log.debug('broadcast: %s', args.broadcast)
    # toggle args.broadcast
    b = not args.broadcast
    golos = Steem(nodes=conf['nodes_old'], no_broadcast=b, keys=conf['keys'])

    cv = Converter(golos)
    min_balance = cv.sp_to_vests(args.min_balance)

    for account in conf['accs']:

        b = golos.get_balances(account=account)
        vests = b['available']['GESTS']
        withdraw_amount = vests - min_balance

        log.info('withdrawing {:.4f} MGESTS ({:.3f} GOLOS): {} -> {}'.format(
            withdraw_amount.amount / 1000000,
            cv.vests_to_sp(withdraw_amount.amount), account, args.to))
        golos.set_withdraw_vesting_route(args.to,
                                         percentage=100,
                                         account=account,
                                         auto_vest=False)
        golos.withdraw_vesting(withdraw_amount.amount, account=account)
Beispiel #21
0
class SyncCommentsTestCase(unittest.TestCase):
    def setUp(self):
        self.node = Steem([config["node_url"]])
        self.client = MongoClient(config["database_url"])
        self.client.drop_database(config["database_name"])
        self.database = self.client[config["database_name"]]

    def test_no_posts(self):
        first_result = no_posts()
        self.database.comment.insert_one({'test': 1})
        second_result = no_posts()
        assert first_result
        assert not second_result

    def insert_posts(self):
        self.database.comment.insert_one({
            '_id':
            1,
            "created":
            datetime.now() - timedelta(1)
        })
        self.database.comment.insert_one({'_id': 2, "created": datetime.now()})
        self.database.comment.insert_one({
            '_id':
            3,
            "created":
            datetime.now() - timedelta(2)
        })

    def test_find_newest_post(self):
        self.insert_posts()
        newest_post = find_newest_post()
        assert newest_post == 2

    def test_find_oldest_post(self):
        self.insert_posts()
        oldest_post = find_oldest_post()
        assert oldest_post == 3

    def test_get_newest_post_as_consistent(self):
        self.insert_posts()
        newest_post = get_newest_post_as_consistent()
        post_in_database = self.database.comment.find_one({"_id": newest_post})
        assert newest_post == 2
        assert post_in_database["consistent"]

    def test_find_newest_consistent_post(self):
        self.insert_posts()
        self.database.comment.update({"_id": 1},
                                     {"$set": {
                                         "consistent": True
                                     }})
        newest_consistent_post = find_newest_consistent_post()
        assert newest_consistent_post == 1

    def test_find_newest_consistent_post_initially(self):
        self.insert_posts()
        newest_consistent_post = find_newest_consistent_post()
        post_in_database = self.database.comment.find_one(
            {"_id": newest_consistent_post})
        assert newest_consistent_post == 2
        assert post_in_database["consistent"]

    def test_save_posts(self):
        posts = self.node.get_posts(limit=10, sort='trending')
        save_posts(posts)
        posts_in_database = self.database.comment.find({})
        for index, post_in_database in enumerate(posts_in_database):
            post = posts[index]
            self.assertCountEqual(
                post_in_database, {
                    "_id": post.identifier[1:],
                    "permlink": post.permlink,
                    "author": post.author,
                    "parent_permlink": post.parent_permlink,
                    "created": post.created,
                    "json_metadata": post.json_metadata,
                    "body": post.body,
                    "depth": 0
                })

    def test_unique_save_posts(self):
        posts = self.node.get_posts(limit=10, sort='trending')
        save_posts(posts)
        save_posts(posts)
        number_of_posts_in_database = self.database.comment.count({})
        assert number_of_posts_in_database == len(posts)

    def test_set_index(self):
        set_index()
        indices = self.database.comment.index_information()
        indices = [value["key"][0] for key, value in indices.items()]
        assert ("created", DESCENDING) in indices

    def test_initial_step(self):
        do_initial_step()
        number_of_posts_in_database = self.database.comment.count({})
        consistent_posts = list(
            self.database.comment.find({"consistent": True}))
        newest_post = self.database.comment.find({}).sort([("created",
                                                            DESCENDING)])[0]
        assert number_of_posts_in_database == STEP_BACKWARD_SIZE

    def test_step_backward(self):
        last_post = do_step_backward("khorunzha/uznai-o-svoem-potenciale")
        last_post_in_database = self.database.comment.find_one(
            {"_id": last_post})
        number_of_extracted_posts = self.database.comment.count(
            {"created": {
                "$gte": last_post_in_database["created"]
            }})
        assert last_post == "sinilga/ya-uzhe-dykhane-beregu"
        assert number_of_extracted_posts == STEP_BACKWARD_SIZE

    def test_step_forward(self):
        last_consistent_post, last_post = do_step_forward(
            "hipster/post-dobra", "sashapoplavskiy/skyfchain-ico")
        last_post_in_database = self.database.comment.find_one(
            {"_id": last_post})
        number_of_extracted_posts = self.database.comment.count(
            {"created": {
                "$gte": last_post_in_database["created"]
            }})
        assert last_post == "markonly/localcoinswap-kyc-teper-ne-nuzhen-ico-live"
        assert last_consistent_post == "hipster/post-dobra"
        assert number_of_extracted_posts == STEP_FORWARD_SIZE

    def test_final_step_forward(self):
        self.database.comment.insert_one({
            '_id': "some/new-post",
            "created": datetime.now()
        })
        previous_post = "sashapoplavskiy/skyfchain-ico"
        last_consistent_post, last_post = do_step_forward(
            "markonly/localcoinswap-kyc-teper-ne-nuzhen-ico-live",
            previous_post)
        number_of_posts = self.database.comment.count({})
        newest_post_in_database = self.database.comment.find_one(
            {"_id": "some/new-post"})
        assert last_consistent_post == "some/new-post"
        assert not last_post
        assert newest_post_in_database["consistent"] == True

    def test_sync_comments(self):
        do_initial_step()
        oldest_post = find_oldest_post()
        oldest_post_in_database = self.database.comment.find_one(
            {"_id": oldest_post})
        self.database.comment.remove({"_id": {"$ne": oldest_post}})
        sync_comments(max_iterations=1)
        number_of_newest_posts = self.database.comment.count(
            {"created": {
                "$gt": oldest_post_in_database["created"]
            }})
        number_of_oldest_posts = self.database.comment.count(
            {"created": {
                "$lt": oldest_post_in_database["created"]
            }})
        assert number_of_oldest_posts == STEP_BACKWARD_SIZE
        assert number_of_newest_posts == STEP_FORWARD_SIZE

    def test_initial_sync_comments(self):
        sync_comments(max_iterations=0)
        number_of_posts = self.database.comment.count({})
        indices = self.database.comment.index_information()
        indices = [value["key"][0] for key, value in indices.items()]
        assert number_of_posts == STEP_BACKWARD_SIZE
        assert ("created", DESCENDING) in indices
Beispiel #22
0
def main():

    parser = argparse.ArgumentParser(
            description='',
            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('url',
            help='post id in format @author/article or full url')
    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'])

    # extract author and post permlink from args.url
    p = re.search('@(.*?)/([^/]+)', args.url)
    if p == None:
        log.critical('Wrong post id specified')
        sys.exit(1)
    else:
        author = p.group(1)
        log.debug('author: {}'.format(author))

        post_permlink = p.group(2)
        log.debug('permlink: {}'.format(post_permlink))


    post = functions.get_post_content(golos, author, post_permlink)
    total_pending_payout_value = post['total_pending_payout_value'].amount
    from pprint import pprint
    #pprint(post)
    #pprint(post.export())
    if not post:
        log.critical('could not find post in blockchain')
        sys.exit(1)

    if post['mode'] != 'first_payout':
        log.critical('post already got a payout')
        sys.exit(1)

    total_vote_weight = int(post['total_vote_weight'])
    if total_vote_weight == 0:
        log.critical('curation rewards disabled')
        sys.exit(1)

    pending_payout = functions.convert_gbg_to_golos(golos, total_pending_payout_value)
    active_votes = sorted(post['active_votes'], key=lambda k: datetime.strptime(k['time'], '%Y-%m-%dT%H:%M:%S'))
    sum_weight = int()

    for vote in active_votes:
        sum_weight += int(vote['weight'])
        weight_pct = int(vote['weight']) / total_vote_weight
        reward = pending_payout * 0.25 * weight_pct
        time_passed = datetime.strptime(vote['time'], '%Y-%m-%dT%H:%M:%S') - post['created']
        print('weight percent: {:.2%}, reward: {:.3f} GP, voter: {:<16}, time: {}, weight: {:.2f}'.format(
            weight_pct, reward, vote['voter'], time_passed, float(vote['weight'])/100000000000000))

    curators_pct = sum_weight / int(post['total_vote_weight']) * 0.25
    print('curation real percent: {:.4%}'.format(curators_pct))