Beispiel #1
0
class Testcases(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(Testcases, self).__init__(*args, **kwargs)
        self.account = Account(testaccount)

    def test_readAccount(self):
        self.assertEqual(self.account["id"], 1489)

    def test_getbalance(self):
        self.account.get_balances()
Beispiel #2
0
def calc_rshares(steem_instance, account, vote_percent):
    """ Calc current rshares for an account
        :param Steem steem_instance: Steem() instance to use when accesing a RPC
        :param str account:
        :param float vote_percent: up percent, 0-100
    """

    a = Account(account, steem_instance=steem_instance)
    cv = Converter(steem_instance)
    try:
        voting_power = get_voting_power(steem_instance, account)
        b = steem_instance.get_balances(account=account)
        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['vesting_shares']
    sp = cv.vests_to_sp(vesting_shares.amount)
    rshares = cv.sp_to_rshares(sp,
                               voting_power=voting_power * 100,
                               vote_pct=vote_percent * 100)

    return rshares
Beispiel #3
0
def get_voting_power(steem_instance, account):
    """ Calculate real voting power instead of stale info in get_account()
        :param Steem steem_instance: Steem() instance to use when accesing a RPC
        :param str account: account name
    """

    try:
        a = Account(account, steem_instance=steem_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
Beispiel #4
0
 def account_history(self,
                     account,
                     first=99999999999,
                     limit=-1,
                     only_ops=[],
                     exclude_ops=[]):
     warnings.warn(
         "The block_stream() call has been moved to `steem.account.Account.rawhistory()`",
         DeprecationWarning)
     from piston.account import Account
     return Account(account, steem_instance=self.steem).rawhistory(
         first=first,
         limit=limit,
         only_ops=only_ops,
         exclude_ops=exclude_ops)
Beispiel #5
0
    def all(self):
        self.current_index = Account(
            self.name, steem_instance=self.steem).virtual_op_count()

        # prevent duplicates
        self.seen_items = set()

        while True:
            # fetch the next batch
            if self.current_index == 0:
                raise StopIteration

            limit = 1000
            if self.current_index < 1000:
                # avoid duplicates on last batch
                limit = 1000 - self.current_index
                self.current_index = 1000

            h = self.steem.rpc.get_account_history(self.name,
                                                   self.current_index,
                                                   limit,
                                                   api='database_api')
            if not h:
                raise StopIteration

            self.current_index -= 1000

            # filter out irrelevant items
            def blogpost_only(item):
                op_type, op = item[1]['op']
                return op_type == 'comment' and not is_comment(op)

            hist = filter(blogpost_only, h)
            hist = map(lambda x: x[1]['op'][1], hist)
            hist = [x for x in hist if x['author'] == self.name]

            # filter out items that have been already passed on
            # this is necessary because post edits create multiple entries in the chain
            hist_uniq = []
            for item in hist:
                if item['permlink'] not in self.seen_items:
                    self.seen_items.add(item['permlink'])
                    hist_uniq.append(item)

            for p in hist_uniq:
                yield Post(p, steem_instance=self.steem)
Beispiel #6
0
        while i < 300:
            date = convertInvestingcomDate(row[0], (86400 * i))
            if date not in eur and (i == 0 or i != len(eur)):
                eur[date] = float(row[1])
            else:
                i = 300

            i = i + 1

myfile = open('author_rewards.csv', 'w')
wr = csv.writer(myfile, delimiter=';')
wr.writerow(['date', 'reward', 'btc', 'eur', 'post'])

i = 10000000
while i > 1:
    a = Account(user, s)
    tx = a.rawhistory(i, 1000)
    tx = list(tx)

    for ndx, member in enumerate(tx):
        i = member[0] - 1
        if member[1]['op'][0] == 'author_reward':
            id = '@' + member[1]['op'][1]['author'] + '/' + member[1]['op'][1][
                'permlink']
            p = Post(id, s)
            reward = float(str(p.reward)[:-4])
            post = p.export()
            dt = post['last_payout']
            unixtime = time.mktime(dt.timetuple())
            value = datetime.datetime.fromtimestamp(unixtime)
            year = int(value.strftime('%Y'))
Beispiel #7
0
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'),
    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(node=conf['nodes_old'], nobroadcast=False, keys=conf['keys'])
    account_name = args.account
    account = Account(args.account, steem_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.rpc.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.rpc.chain_params["prefix"]
    }

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

    golos.finalizeOp(op, args.account, "owner")
Beispiel #8
0
 def __init__(self, *args, **kwargs):
     super(Testcases, self).__init__(*args, **kwargs)
     self.account = Account(testaccount)
Beispiel #9
0
    def create_account(
        self,
        account_name,
        json_meta={},
        creator=None,
        owner_key=None,
        active_key=None,
        posting_key=None,
        memo_key=None,
        password=None,
        additional_owner_keys=[],
        additional_active_keys=[],
        additional_posting_keys=[],
        additional_owner_accounts=[],
        additional_active_accounts=[],
        additional_posting_accounts=[],
        storekeys=True,
    ):
        """ Create new account in Steem
            The brainkey/password can be used to recover all generated keys (see
            `steembase.account` for more details.
            By default, this call will use ``default_author`` 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.
            .. note:: Account creations cost a fee that is defined by
                       the network. If you create an account, you will
                       need to pay for that fee!
            .. 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 json_meta: Optional meta data for the account
            :param str creator: which account should pay the registration fee
                                (defaults to ``default_author``)
            :param str owner_key: Main owner key
            :param str active_key: Main active key
            :param str posting_key: Main posting 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_posting_keys: Additional posting public keys
            :param array additional_owner_accounts: Additional owner account names
            :param array additional_active_accounts: Additional acctive account names
            :param array additional_posting_accounts: Additional posting account names
            :param bool storekeys: Store new keys in the wallet (default: ``True``)
            :raises AccountExistsException: if the account already exists on the blockchain
        """
        assert len(
            account_name) <= 16, "Account name must be at most 16 chars long"

        if not creator:
            raise ValueError(
                "Not creator account given. Define it with " +
                "creator=x, or set the default_author using piston")
        if password and (owner_key or posting_key or active_key or memo_key):
            raise ValueError("You cannot use 'password' AND provide keys!")

        account = None
        try:
            account = Account(account_name)
        except:
            pass
        if account:
            raise AccountExistsException

        " Generate new keys from password"
        from pistonbase.account import PasswordKey, PublicKey
        if password:
            posting_key = PasswordKey(account_name, password, role="posting")
            active_key = PasswordKey(account_name, password, role="active")
            owner_key = PasswordKey(account_name, password, role="owner")
            memo_key = PasswordKey(account_name, password, role="memo")
            posting_pubkey = posting_key.get_public_key()
            active_pubkey = active_key.get_public_key()
            owner_pubkey = owner_key.get_public_key()
            memo_pubkey = memo_key.get_public_key()
            posting_privkey = posting_key.get_private_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(posting_privkey)
                self.wallet.addPrivateKey(memo_privkey)
        elif (owner_key and posting_key and active_key and memo_key):
            posting_pubkey = PublicKey(posting_key,
                                       prefix=self.rpc.chain_params["prefix"])
            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"])
        posting = format(posting_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]]
        posting_key_authority = [[posting, 1]]
        owner_accounts_authority = []
        active_accounts_authority = []
        posting_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_posting_keys:
            posting_key_authority.append([k, 1])

        for k in additional_owner_accounts:
            owner_accounts_authority.append([k, 1])
        for k in additional_active_accounts:
            active_accounts_authority.append([k, 1])
        for k in additional_posting_accounts:
            posting_accounts_authority.append([k, 1])

        props = self.rpc.get_chain_properties()
        fee = props["account_creation_fee"]
        s = {
            'creator': creator,
            'fee': fee,
            'json_metadata': json_meta,
            'memo_key': memo,
            'new_account_name': account_name,
            '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': self.rpc.chain_params["prefix"]
        }

        op = operations.Account_create(**s)

        return self.finalizeOp(op, creator, "active")
Beispiel #10
0
def get_bandwidth(steem_instance, account, type='market'):
    """ Estimate current account bandwidth and usage ratio
        :param Steem steem_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, steem_instance=steem_instance)

    global_props = steem_instance.info()

    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['new_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['new_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))

    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.info('{:.<30}{:.>30.0f}'.format('used:', used))
    log.info('{:.<30}{:.>30.0f}'.format('avail:', avail))
    log.info('{:.<30}{:.>30.2%}'.format('used ratio:', used / avail))

    if used < avail:
        log.debug('has bandwidth')
    else:
        log.debug('no bandwidth')

    return used / avail * 100
Beispiel #11
0
                    # Is post in within time limit
                    if elapsed_time < cutofftime:
                        # Get comment info
                        identifier = "@" + event['author'] + "/" + event['permlink']
                        postid = Post(identifier,s)
                        # If we haven't already voted, add to list
                        if accountname not in postid['active_votes']:
                            oldest_id.append(identifier)
                        
    print(oldest_id)
    return oldest_id


s = Steem(node=nodes)
upvoter = Steem(node=nodes, wif=posting_key)
account = Account(accountname, s)

# Mainloop
while True:
    # Get current VP
    VP = getactiveVP()
    
    # If VP is below MaxVP go to sleep
    while VP < MaxVP:
        VP = getactiveVP()
        # Time to sleep til we're above the MaxVP if no further votes are made
        sleeptime = ( MaxVP - VP + 0.01 ) * (86400 / 20)
        
        print
        (
        " VP = " + str(VP) 
Beispiel #12
0
def multifeed(puppet, puppet_posting_key):

    upvote_history = []
    pupp = Account(puppet)
    print("{}'s VOTING POWER: {}".format(puppet, pupp.voting_power()))
    vests = str(Account(puppet).get_balances()['VESTS']).split(" ")[0]
    if float(vests) >= 100000:
        vote_weight = 5
    else:
        vote_weight = 100

    if pupp.voting_power() >= 70:
        print("{} : Waiting for new posts by {}".format(
            puppet, my_subscriptions))
        steem = Steem(wif=puppet_posting_key)

        for comment in steem.stream_comments():
            try:
                if comment.author in my_subscriptions:

                    if comment.identifier in upvote_history:
                        print(
                            "Comment has been previously voted on: {}".format(
                                comment.identifier))

                    print("New post by @{} {}".format(comment.author,
                                                      url_builder(comment)))

                    try:
                        print("Voting from {} account".format(puppet))
                        curation_time = random.randint(1800, 2200)
                        dice = random.randint(1, 100)
                        print("Curation time {} for {}, with chance of {}".
                              format(curation_time, puppet, dice))
                        if dice > 77:
                            print("Time to wait {} for {} to vote.".format(
                                curation_time, puppet))
                            t = threading.Thread(
                                target=curation_delay_vote,
                                args=(puppet_posting_key, puppet,
                                      comment.identifier, curation_time,
                                      vote_weight))
                            t.start()
                            upvote_history.append(comment.identifier)
                        else:
                            print("Failed dice:{}".format(dice))
                    except BroadcastingError as e:
                        print("Upvoting failed...")
                        print(
                            "We have probably reached the upvote rate limit. {}"
                            .format(e))
                    except VoteWeightTooSmall:
                        print("Low Vote Weight for: {}".format(puppet))
                        pass
                    except Exception as er:
                        print("Error:{}".format(er))
            except PostDoesNotExist:
                print("Post Does not exist")
                pass

    else:
        print("Skipping vote from {} due to low voting power: {}".format(
            puppet, pupp.voting_power()))
        sys.exit(0)