Ejemplo n.º 1
0
def get_block_trx_data(block_num):
    block = GetBlock(block_num, is_verbose=False)
    trxs = block.json["transactions"]
    if not len(trxs):
        logger.OUT("No transactions in block {}.".format(block_num))
    else:
        for trx in trxs:
            logger.OUT(trx["trx"]["transaction"]["actions"][0]["data"])
Ejemplo n.º 2
0
def print_stats(
        accounts, params, 
        last_col="%s", col="%15s"
    ):
    def find(element, json):
        try:
            keys = element.split('.')
            rv = json
            for key in keys:
                rv = rv[key]
        except:
            rv = "n/a"
        return rv

    jsons = []
    for account in accounts:
        json = cleos.GetAccount(account, is_info=False, is_verbose=0).json
        json["account_object_name"] = account.account_object_name
        jsons.append(json)

    header = ""
    for json in jsons:
        header = header + col % (json["account_object_name"])
    output = ".\n" + header + "\n"

    for param in params:
        for json in jsons:
            output = output + col % find(param, json)
        output = output + "  " + last_col % (param) + "\n" 

    logger.OUT(output, translate=False)
    
Ejemplo n.º 3
0
    def push_action(
            account_object, action, data,
            permission=None, expiration_sec=30, 
            skip_signature=0, dont_broadcast=0, forceUnique=0,
            max_cpu_usage=0, max_net_usage=0,
            ref_block=None, json=False):
        data = _data_json(data)

        result = cleos.PushAction(
            account_object, action, data,
            permission, expiration_sec, 
            skip_signature, dont_broadcast, forceUnique,
            max_cpu_usage, max_net_usage,
            ref_block,
            is_verbose=False, json=True)

        logger.INFO('''
            * Push action ``{}``:
            '''.format(action))

        logger.INFO('''
            {}
        '''.format(re.sub(' +',' ', data)))

        account_object.action = result
        try:
            account_object._console = result.console
            logger.DEBUG(account_object._console)
        except:
            pass
        if json:
            logger.OUT(result.out_msg)

        account_object.action = result
Ejemplo n.º 4
0
    def __init__(self, name=None, password="", verbosity=None, file=False):

        cleos.set_local_nodeos_address_if_none()
        if name is None:
            name = setup.wallet_default_name
        else:
            name = setup.file_prefix() + name

        if not self.wallet is None:
            raise errors.Error('''
            It can be only one ``Wallet`` object in the script; there is one
            named ``{}``.
            '''.format(wallet.name))
            return

        self.wallet_dir = manager.wallet_dir()

        logger.INFO('''
                * Wallet name is ``{}``, wallet directory is
                    {}.
                '''.format(name, self.wallet_dir))

        if not password:  # look for password:
            passwords = wallet_json_read()
            if name in passwords:
                password = passwords[name]
                logger.INFO(
                    '''
                    The password is restored from the file:
                    {}
                    '''.format(
                        os.path.join(self.wallet_dir, setup.password_map)),
                    verbosity)

        cleos.WalletCreate.__init__(self, name, password, is_verbose=False)

        if self.is_created:  # new password
            logger.INFO(
                '''
                * Created wallet ``{}``.
                '''.format(self.name), verbosity)
            if manager.is_local_testnet() or file:
                password_map = wallet_json_read()
                password_map[name] = self.password
                wallet_json_write(password_map)
                logger.INFO(
                    '''
                    * Password is saved to the file ``{}`` in the wallet directory.
                    '''.format(setup.password_map), verbosity)
            else:
                logger.OUT(self.out_msg)
        else:
            logger.TRACE('''
                    Opened wallet ``{}``
                    '''.format(self.name))
Ejemplo n.º 5
0
    def is_name_taken(self, account_object_name, account_name):
        while True:
            account_map_json = manager.account_map(self)
            if account_map_json is None:
                return False

            is_taken = False
            for name, object_name in account_map_json.items():
                if object_name == account_object_name:
                    if not name == account_name:
                        logger.OUT('''
                The given account object name
                ``{}``
                points to an existing account, of the name {},
                mapped in a file in directory:
                {}
                Cannot overwrite it.

                However, you can free the name by changing the mapping. 
                Do you want to edit the file?
                '''.format(account_object_name, name, self.wallet_dir))
                        is_taken = True
                        break

            if is_taken:
                temp = None
                if account_object_name in Wallet.globals:
                    temp = Wallet.globals[account_object_name]
                    del Wallet.globals[account_object_name]

                answer = input("y/n <<< ")

                if answer == "y":
                    manager.edit_account_map()
                    continue
                else:
                    if temp:
                        Wallet.globals[account_object_name] = temp
                    raise errors.Error('''
            Use the function 'manager.edit_account_map(text_editor="nano")'
            or the corresponding method of any object of the 'pyteos.wallet.Wallet` 
            class to edit the file.
                    ''')
            else:
                break
Ejemplo n.º 6
0
    def set_contract(
            account_object, contract_dir, 
            wast_file="", abi_file="", 
            permission=None, expiration_sec=30, 
            skip_signature=0, dont_broadcast=0, forceUnique=0,
            max_cpu_usage=0, max_net_usage=0,
            ref_block=None):

        result = cleos.SetContract(
            account_object, contract_dir, 
            wast_file, abi_file, 
            permission, expiration_sec, 
            skip_signature, dont_broadcast, forceUnique,
            max_cpu_usage, max_net_usage,
            ref_block,
            is_verbose=False
            )
        logger.OUT(result)
        account_object.set_contract = result
Ejemplo n.º 7
0
def account_map(logger=None):
    '''Return json account map

Attempt to open the account map file named ``setup.account_map``, located 
in the wallet directory ``wallet_dir()``, to return its json contents. If the 
file does not exist, return an empty json.

If the file is corrupted, offer editing the file with the ``nano`` linux 
editor. Return ``None`` if the the offer is rejected.
    '''
    wallet_dir_ = wallet_dir()
    path = os.path.join(wallet_dir_, setup.account_map)
    while True:
        try:  # whether the setup map file exists:
            with open(path, "r") as input_file:
                return json.load(input_file)

        except Exception as e:
            if isinstance(e, FileNotFoundError):
                return {}
            else:
                logger.OUT('''
            The account mapping file is misformed. The error message is:
            {}
            
            Do you want to edit the file?
            '''.format(str(e)))

                answer = input("y/n <<< ")
                if answer == "y":
                    edit_account_map()
                    continue
                else:
                    raise errors.Error('''
        Use the function 'efman.edit_account_map(text_editor="nano")'
        or the corresponding method of any object of the 'pyteos.wallet.Wallet` 
        class to edit the file.
                    ''')
                    return None
Ejemplo n.º 8
0
    def table(
            account_object, table_name, scope="", 
            binary=False, 
            limit=10, key="", lower="", upper=""):

        logger.INFO('''
        * Table ``{}`` for ``{}``
        '''.format(table_name, scope))
        
        result = cleos.GetTable(
                    account_object, table_name, scope,
                    binary, 
                    limit, key, lower, upper,
                    is_verbose=False)

        try:
            account_map = manager.account_map()
            scope = account_map[str(scope)]
        except:
            pass

        logger.OUT(result.out_msg)
        return result
Ejemplo n.º 9
0
    def printself(self, is_verbose=None):
        if not hasattr(self, "is_verbose"):
            self.is_verbose = is_verbose

        if self.is_verbose:
            logger.OUT(self.__str__())
Ejemplo n.º 10
0
def get_block_trx_count(block_num):
    block = GetBlock(block_num, is_verbose=False)
    trxs = block.json["transactions"]
    if not len(trxs):
        logger.OUT("No transactions in block {}.".format(block_num))
    return len(trxs)
Ejemplo n.º 11
0
 def index(self):
     ''' Lists opened wallets, * marks unlocked.
     Returns `cleos.WalletList` object
     '''
     result = cleos.WalletList(is_verbose=0)
     logger.OUT(result.out_msg)
Ejemplo n.º 12
0
 def code(account_object, code="", abi="", wasm=False):
     result = cleos.GetCode(account_object, code, abi, is_verbose=False)
     logger.INFO('''
     * code()
     ''')
     logger.OUT(result.out_msg)
Ejemplo n.º 13
0
def create_master_account(
            account_object_name, account_name=None, 
            owner_key=None, active_key=None,
            verbosity=None):
    '''Create account object in caller's global namespace.

    - **parameters**::

        account_object_name:: the name of the account object
        account_name: the name of the account; random, if not set
        verbosity: argument to the internal logger

    ### Preconditions

    Check the following conditions:
    * precisely one ``Wallet`` object is defined;
    
    ### Local testnet

    If the local testnet is running, create an account object representing 
    the ``eosio`` account. Put the account into the wallet. Put the account
    object into the global namespace of the caller, and **return**.

    ### Remote testnet

    Otherwise, an outer testnet has to be defined with 
    ``setup.set_nodeos_address(<url>)``.

    ### Existing account

    If the ``account_name`` argument is set, check the testnet for presence of the 
    account. If present, create the corresponding object and put the account 
    into the wallet, and put the account object into the global namespace of 
    the caller. and **return**. Otherwise start a  registration procedure, 
    described in the next paragraph.

    ### Registration to a remote testnet

    If the ``account_name`` argument is not set or it does not address any existing
    account, see the previous paragraph, start a registration procedure.

    * if the ``account_name`` argument is not set, make it random
    * print registration data, namely:
        * account name
        * owner public key
        * active public key
        * owner private key
        * active private key
    * wait for the user to register the master account
    * . . . . 
    * detect the named account on the remote testnet
    * put the account into the wallet
    * put the account object into the global namespace of the caller
    
    ### Name conflict between account objects

    If the new account object is going to be added to the wallet, an error
    is reported. Then an offer is given to edith the mapping file in order
    to resolve the conflict. When the conflict is resolved, the procedure
    finishes successfully.
    '''

    globals = inspect.stack()[1][0].f_globals
 
    if account_object_name: # account_object_name==None in register_testnet
        '''
        Check the conditions:
        * a ``Wallet`` object is defined.
        * the account object name is not in use, already.    
        ''' 
        is_wallet_defined(logger, globals)

        global wallet_singleton
        if wallet_singleton is None:
            return

        if account_object_name in globals:

            if not isinstance(globals[account_object_name], interface.Account):
                raise errors.Error('''
                The global variable {} type is not ``Account``.
                '''.format(account_object_name))
                return

            logger.INFO('''
                ######## Account object ``{}`` restored from the blockchain.
                '''.format(account_object_name)) 
            return

            #wallet_singleton.is_name_taken(account_object_name, account_name)

    if isinstance(account_name, testnet.Testnet):
        owner_key = account_name.owner_key
        active_key = account_name.active_key
        account_name = account_name.account_name

    logger.INFO('''
        ######### Create a master account object ``{}``.
        '''.format(account_object_name))                

    '''
    If the local testnet is running, create an account object representing 
    the ``eosio`` account. Put the account into the wallet. Put the account
    object into the global namespace of the caller, and **return**.
    '''   
    account_object = Eosio(account_object_name)

    if is_local_testnet_running(account_object):
        put_account_to_wallet_and_on_stack(
            account_object_name, account_object, logger)
        return

    '''
    Otherwise, an outer testnet has to be defined with 
    ``setup.set_nodeos_address(<url>)``.
    '''

    if manager.is_local_testnet():
        raise errors.Error('''
        If the local testnet is not running, an outer testnet has to be 
        defined with `setup.set_nodeos_address(<url>)`.
        Use 'setup.set_nodeos_address(<URL>)'
        ''')
        return

    '''
    If the ``account_name`` argument is not set, it is randomized. Check the testnet for 
    presence of the account. If present, create the corresponding object and see 
    whether it is in the wallets. If so, put the account object into the global 
    namespace of the caller. and **return**. 
    '''
    first_while = True
    while True:
        account_object = GetAccount(
            account_object_name, account_name, owner_key, active_key, verbosity)

        if first_while and account_name and owner_key and active_key \
                        and not account_object.exists:
            raise errors.Error('''
            There is no account named ``{}`` in the blockchain.
            '''.format(account_name))
            return
        first_while = False

        if account_object.exists:
            if account_object.has_keys: # it is your account
                logger.TRACE('''
                    * Checking whether the wallet has keys to the account ``{}``
                    '''.format(account_object.name))

                logger.TRACE('''
                    * The account object is created.
                    ''')

                if account_object_name:
                    if append_account_methods_and_finish(
                        account_object_name, account_object):
                        logger.TRACE('''
                            * The account ``{}`` is in the wallet.
                            '''.format(account_object.name))
                        return
                else:
                    return account_object

            else: # the name is taken by somebody else
                logger.TRACE('''
                ###
                You can try another name. Do you wish to do this?
                ''')
                decision = input("y/n <<< ")
                if decision == "y":
                    account_name = input(
                        "enter the account name or nothing to make the name random <<< ")
                else:
                    return
        else:
            owner_key_new = cleos.CreateKey("owner", is_verbose=False)
            active_key_new = cleos.CreateKey("active", is_verbose=False)

            logger.OUT('''
            Use the following data to register a new account on a public testnet:
            Account Name: {}
            Owner Public Key: {}
            Active Public Key: {}

            Owner Private Key: {}
            Active Private Key: {}
            '''.format(
                account_object.name,
                owner_key_new.key_public,
                active_key_new.key_public,
                owner_key_new.key_private,
                active_key_new.key_private
                ))
                
            while True:
                is_ready = input("enter 'go' when ready or 'q' to quit <<< ")
                if is_ready == "q":
                    return
                else: 
                    if is_ready == "go":
                        break
            account_name = account_object.name
            owner_key = owner_key_new
            active_key = active_key_new