def restore_accounts(self): ''' ''' self.open_unlock() account_map = manager.account_map() new_map = {} wallet_keys = cleos.WalletKeys(is_verbose=0) if len(account_map) > 0: logger.INFO(''' ######### Restore cached account objects: ''') for name, object_name in account_map.items(): try: account_ = cleos.GetAccount(name, is_info=False, is_verbose=False) if account_.owner_key in wallet_keys.json and \ account_.active_key in wallet_keys.json: new_map[name] = object_name from shell.account import create_account create_account(object_name, name, restore=True, verbosity=None) except errors.AccountDoesNotExistError: pass manager.save_account_map(new_map) else: logger.INFO(''' * The wallet is empty. ''')
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
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))
def node_probe(verbosity=None): count = 15 num = 5 block_num = None while True: time.sleep(1) try: get_info = cleos.GetInfo(is_verbose=0) count = count - 1 head_block_num = int(get_info.json["head_block_num"]) except: head_block_num = 0 finally: print(".", end="", flush=True) if block_num is None: block_num = head_block_num if head_block_num - block_num >= num: print() logger.INFO( ''' Local node is running. Block number is {} '''.format(head_block_num), verbosity) break if count <= 0: raise errors.Error(''' The local node does not respond. ''')
def delegate_bw( account_object, stake_net_quantity, stake_cpu_quantity, receiver=None, permission=None, transfer=False, expiration_sec=30, skip_signature=0, dont_broadcast=0, forceUnique=0, max_cpu_usage=0, max_net_usage=0, ref_block=None, is_verbose=1): if manager.is_local_testnet(): return if receiver is None: receiver = account_object result = cleosys.DelegateBw( account_object, receiver, stake_net_quantity, stake_cpu_quantity, permission, transfer, expiration_sec, skip_signature, dont_broadcast, forceUnique, max_cpu_usage, max_net_usage, ref_block, is_verbose=0 ) logger.INFO(''' * Delegated stake from {} to {} NET: {} CPU: {} '''.format( result.payer, result.receiver, result.stake_net_quantity, result.stake_cpu_quantity))
def buy_ram( account_object, amount_kbytes, receiver=None, expiration_sec=30, skip_signature=0, dont_broadcast=0, forceUnique=0, max_cpu_usage=0, max_net_usage=0, ref_block=None): if manager.is_local_testnet(): return if receiver is None: receiver = account_object buy_ram_kbytes = 1 result = cleosys.BuyRam( account_object, receiver, amount_kbytes, buy_ram_kbytes, expiration_sec, skip_signature, dont_broadcast, forceUnique, max_cpu_usage, max_net_usage, ref_block, is_verbose=0 ) logger.INFO(''' * Transfered RAM from {} to {} kbytes: {} '''.format(result.payer, result.receiver, result.amount))
def project_from_template(name, template="", user_workspace=None, remove_existing=False, visual_studio_code=False, verbosity=None): '''Given the template type and a name, create a contract workspace. - **parameters**:: name: The name of the new wallet, defaults to ``default``. template: The name of the template used. user_workspace: If set, the folder for the work-space. Defaults to the value of the ``EOSIO_CONTRACT_WORKSPACE`` env. variable. remove_existing: If set, overwrite any existing workspace. visual_studio_code: If set, open the ``VSCode``, if available. verbosity: The logging configuration. ''' logger.INFO(''' ######### Create contract ``{}`` from template ``{}``. '''.format(name, template)) contract_path_absolute = teos.template_create(name, template, user_workspace, remove_existing, visual_studio_code) return contract_path_absolute
def status(): ''' Display EOS node status. ''' get_info = cleos.GetInfo(is_verbose=0) logger.INFO(''' ######### Node ``{}``, head block number ``{}``. '''.format(setup.nodeos_address(), get_info.json["head_block_num"]))
def testnets(): mapping = get_mapping() if not mapping: logger.INFO(''' Testnet mapping is empty. ''') return for alias, testnet in mapping.items(): print("%25s: %13s @ %s" % (alias, testnet["account_name"], testnet["url"]))
def resume(verbosity=None): ''' Resume the EOSIO local node. ''' if not cleos.set_local_nodeos_address_if_none(): logger.INFO( ''' Not local nodeos is set: {} '''.format(setup.nodeos_address()), verbosity) teos.node_start(verbosity=verbosity)
def deploy(self, permission=None, dont_broadcast=None, payer=None): if not self.is_built(): raise errors.Error(''' Contract needs to be built before deployment. ''') return if dont_broadcast is None: dont_broadcast = self.dont_broadcast try: result = cleos.SetContract(self.account, self.contract_dir, self.wasm_file, self.abi_file, permission, self.expiration_sec, self.skip_signature, dont_broadcast, self.forceUnique, self.max_cpu_usage, self.max_net_usage, self.ref_block, is_verbose=False, json=True) except errors.LowRamError as e: logger.TRACE(''' * RAM needed is {}.kByte, buying RAM {}.kByte. '''.format(e.needs_kbyte, e.deficiency_kbyte)) buy_ram_kbytes = str(e.deficiency_kbyte + 1) if not payer: payer = self.account payer.buy_ram(buy_ram_kbytes, self.account) result = cleos.SetContract(self.account, self.contract_dir, self.wasm_file, self.abi_file, permission, self.expiration_sec, self.skip_signature, dont_broadcast, self.forceUnique, self.max_cpu_usage, self.max_net_usage, self.ref_block, is_verbose=False, json=True) logger.INFO(''' * Contract {} is deployed. '''.format(self.contract_dir)) self.contract = result
def reset(verbosity=None): ''' Start clean the EOSIO local node. ''' if not cleos.set_local_nodeos_address_if_none(): logger.INFO( ''' No local nodeos is set: {} '''.format(setup.nodeos_address()), verbosity) clear_testnet_cache() teos.node_start(clear=True, verbosity=verbosity)
def verify_testnet_production(): result = is_head_block_num() domain = "LOCAL" if is_local_testnet() else "REMOTE" if not result: raise errors.Error(''' {} testnet is not running or is not responding @ {}. '''.format(domain, setup.nodeos_address())) else: logger.INFO(''' {} testnet is active @ {}. '''.format(domain, setup.nodeos_address())) return result
def config_file(): if not "EOSIO_EOSFACTORY_DIR" in os.environ: raise errors.Error(''' EOSIO_EOSFACTORY_DIR not defined ''') file = os.path.join(os.environ["EOSIO_EOSFACTORY_DIR"], setup.CONFIG_JSON) if os.path.exists(file): return file with open(file, "w") as output: output.write("{}") logger.INFO('''Creating an empty config file: {}'''.format(file)) return file
def config_file(): trace = "Environment variable EOSIO_EOSFACTORY_DIR + setup.CONFIG_DIR:\n" trace = "os.environ" if "EOSIO_EOSFACTORY_DIR" in os.environ: env = os.environ["EOSIO_EOSFACTORY_DIR"] trace = trace + env if env else "EOSIO_EOSFACTORY_DIR not defined" file = os.path.join(env, setup.CONFIG_DIR, setup.CONFIG_JSON) trace = trace + file + "\n\n" if os.path.exists(file): return file setup_dir = os.path.dirname(setup.__file__) file = os.path.join(setup_dir, setup.CONFIG_JSON) trace = trace + file + "\n" if os.path.exists(file): return file setup_dir = os.path.dirname(setup_dir) file = os.path.join(setup_dir, setup.CONFIG_JSON) trace = trace + file + "\n" if os.path.exists(file): return file setup_dir = os.path.dirname(setup_dir) file = os.path.join(setup_dir, setup.CONFIG_JSON) trace = trace + file + "\n" if os.path.exists(file): return file else: with open(file, "w") as output: output.write("{}") logger.INFO(''' Cannot find the config json file. It is expected in any of the following locations: {} -- searched in the same order. Creating an empty config file: {} '''.format(file, trace)) return file
def reboot(): logger.INFO(''' ######### Reboot EOSFactory session. ''') manager.stop([]) #cleos.reboot() global wallet_singleton if wallet_singleton: wallet_singleton.delete_globals() wallet.Wallet.wallet = None try: del wallet_singleton except: pass wallet_singleton = None global wallet_globals wallet_globals = None
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
def node_stop(verbosity=None): # You can see if the process is a zombie by using top or # the following command: # ps aux | awk '$8=="Z" {print $2}' pid = get_pid() count = 10 if pid: os.system("kill " + str(pid[0])) while count > 0: time.sleep(1) if not is_local_node_process_running(): break count = count - 1 if count <= 0: raise errors.Error(''' Failed to kill {}. Pid is {}. '''.format(config.getDaemonName(), pid[0])) else: logger.INFO( ''' Local node is stopped {}. '''.format(pid), verbosity)
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)
def create_account( account_object_name, creator, account_name="", owner_key="", active_key="", stake_net=3, stake_cpu=3, permission=None, buy_ram_kbytes=8, buy_ram="", transfer=False, expiration_sec=30, skip_signature=0, dont_broadcast=0, forceUnique=0, max_cpu_usage=0, max_net_usage=0, ref_block=None, restore=False, verbosity=None): global wallet_singleton globals = inspect.stack()[1][0].f_globals ''' Check the conditions: * a ``Wallet`` object is defined; * the account object name is not in use, already. ''' is_wallet_defined(logger) if wallet_singleton is None: return #wallet_singleton.is_name_taken(account_object_name, account_name) 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 logger.INFO(''' ######### Create an account object ``{}``. '''.format(account_object_name)) ''' Create an account object. ''' account_object = None if restore: if creator: account_name = creator logger.INFO(''' ... for an existing blockchain account ``{}`` mapped as ``{}``. '''.format(account_name, account_object_name), translate=False) account_object = RestoreAccount(account_name, verbosity) account_object.account_object_name = account_object_name else: if not account_name: account_name = cleos.account_name() if owner_key: if not active_key: active_key = owner_key else: owner_key = cleos.CreateKey("owner", is_verbose=False) active_key = cleos.CreateKey("active", is_verbose=False) if stake_net and not manager.is_local_testnet(): logger.INFO(''' ... delegating stake to a new blockchain account ``{}`` mapped as ``{}``. '''.format(account_name, account_object_name)) try: account_object = SystemNewaccount( creator, account_name, owner_key, active_key, stake_net, stake_cpu, permission, buy_ram_kbytes, buy_ram, transfer, expiration_sec, skip_signature, dont_broadcast, forceUnique, max_cpu_usage, max_net_usage, ref_block, verbosity ) except errors.LowRamError as e: logger.TRACE(''' * RAM needed is {}.kByte, buying RAM {}.kByte. '''.format( e.needs_kbyte, e.deficiency_kbyte)) buy_ram_kbytes = str( e.deficiency_kbyte + 1) account_object = SystemNewaccount( creator, account_name, owner_key, active_key, stake_net, stake_cpu, permission, buy_ram_kbytes, buy_ram, transfer, expiration_sec, skip_signature, dont_broadcast, forceUnique, max_cpu_usage, max_net_usage, ref_block, verbosity ) else: logger.INFO(''' ... for a new blockchain account ``{}``. '''.format(account_name)) account_object = CreateAccount( creator, account_name, owner_key, active_key, permission, expiration_sec, skip_signature, dont_broadcast, forceUnique, max_cpu_usage, max_net_usage, ref_block, verbosity ) account_object.account_object_name = account_object_name account_object.owner_key = owner_key account_object.active_key = active_key logger.TRACE(''' * The account object is created. ''') append_account_methods_and_finish(account_object_name, account_object)
def ABI(contract_dir_hint=None, code_name=None, include_dir=None): '''Given a hint to a contract directory, produce ABI file. ''' contract_dir = config.getContractDir(contract_dir_hint) srcs = config.getContractSourceFiles(contract_dir) if not srcs: raise errors.Error(''' "The source is empty. The assumed contract dir is {} '''.format(contract_dir)) return targetDirPath = getTargetDirPath(contract_dir) for src in srcs: srcPath = src if os.path.splitext(src)[1].lower() == ".abi": logger.INFO(''' NOTE: An ABI exists in the source directory. Cannot overwrite it: {} Just copying it to the target directory. '''.format(src)) shutil.move(srcPath, os.path.join(targetDirPath, os.path.basename(srcPath))) return sourcePath = srcs[0] source_dir = os.path.dirname(srcs[0]) if not code_name: code_name = os.path.splitext(os.path.basename(srcs[0]))[0] command_line = [ config.get_eosio_abigen(), "-extra-arg=-c", "-extra-arg=--std=c++14", "-extra-arg=--target=wasm32", "-extra-arg=-nostdinc", "-extra-arg=-nostdinc++", "-extra-arg=-DABIGEN", "-extra-arg=-I" + config.getSourceDir() + "/contracts/libc++/upstream/include", "-extra-arg=-I" + config.getSourceDir() + "/contracts/musl/upstream/include", "-extra-arg=-I" + config.getSourceDir() + "/externals/magic_get/include", "-extra-arg=-I" + config.getEOSIO_BOOST_INCLUDE_DIR(), "-extra-arg=-I" + config.getSourceDir() + "/contracts", "-extra-arg=-I" + config.getSourceDir() + "/build/contracts", "-extra-arg=-I" + source_dir ] if include_dir: include_dirs = include_dir.split(",") for dir in include_dirs: command_line.append("-extra-arg=-I " + dir) command_line.extend([ "-extra-arg=-fparse-all-comments", "-destination-file=" + os.path.join(targetDirPath, code_name + ".abi"), # "-verbose=" + to_string(verbose), "-context=" + source_dir, sourcePath, "--" ]) if setup.is_print_command_line: print("######## {}:".format(config.get_eosio_abigen())) print(" ".join(command_line)) process(command_line) logger.TRACE(''' ABI file writen to file: {} '''.format(targetDirPath))
def info(): ''' Display EOS node info. ''' get_info = cleos.GetInfo(is_verbose=False) logger.INFO(str(get_info))
def template_create(project_name, template_name=None, workspace_dir=None, remove_existing=False, open_vscode=False): '''Given the project name and template name, create a smart contract project. ''' project_name = project_name.strip() if not template_name: template_name = config.DEFAULT_TEMPLATE template_name = template_name.strip() if not workspace_dir \ or not os.path.isabs(workspace_dir) \ or not os.path.exists(workspace_dir): workspace_dir = config.getContractWorkspace() workspace_dir = workspace_dir.strip() template_dir = os.path.join(config.getEosFactoryDir(), config.templContractsDir, template_name) if not os.path.exists(template_dir): raise errors.Error(''' TemplateCreate '{}' does not exist. '''.format(template_dir)) project_dir = os.path.join(workspace_dir, project_name) if os.path.exists(project_dir): if remove_existing: try: shutil.rmtree(project_dir) except Exception as e: raise errors.Error(str(e)) else: logger.INFO(''' NOTE: Contract workspace '{}' already exists. Cannot owerwrite it. '''.format(project_dir)) return try: # make contract directory and its build directory: os.makedirs(os.path.join(project_dir, "build")) except Exception as e: raise errors.Error(str(e)) def copy_dir_contents(project_dir, template_dir, directory, project_name): contents = os.listdir(os.path.join(template_dir, directory)) for item in contents: path = os.path.join(directory, item) template_path = os.path.join(template_dir, path) contract_path = os.path.join( project_dir, path.replace(config.TEMPLATE_TOKEN, project_name)) if os.path.isdir(template_path): os.mkdir(contract_path) copy_dir_contents(project_dir, template_dir, path, project_name) elif os.path.isfile(template_path): copy(template_path, contract_path, project_name) def copy(template_path, contract_path, project_name): with open(template_path, "r") as input: template = input.read() template = template.replace("@" + config.TEMPLATE_TOKEN + "@", project_name) with open(contract_path, "w") as output: output.write(template) copy_dir_contents(project_dir, template_dir, "", project_name) logger.TRACE(''' * Contract project '{}' created from template '{}' in directory {} '''.format(project_name, template_name, project_dir)) if open_vscode: if is_windows_ubuntu(): commandLine = "cmd.exe /C code {}".format( utils.wslMapLinuxWindows(project_dir)) elif uname() == "Darwin": commandLine = "open -n -b com.microsoft.VSCode --args {}".format( project_dir) else: commandLine = "code {}".format(project_dir) os.system(commandLine) return project_dir
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