def execute(self, arguments): item = get_arg(arguments) if item is not None: if item.lower() == "all": assets = Blockchain.Default().ShowAllAssets() assetlist = [] for asset in assets: state = Blockchain.Default().GetAssetState(asset.decode('utf-8')).ToJson() asset_dict = {state['name']: state['assetId']} assetlist.append(asset_dict) print(json.dumps(assetlist, indent=4)) return assetlist if item.lower() == 'neo': assetId = Blockchain.Default().SystemShare().Hash elif item.lower() == 'gas': assetId = Blockchain.Default().SystemCoin().Hash else: try: assetId = UInt256.ParseString(item) except Exception: print("Could not find asset from args: %s" % arguments) return asset = Blockchain.Default().GetAssetState(assetId.ToBytes()) if asset is not None: print(json.dumps(asset.ToJson(), indent=4)) return asset.ToJson() else: print("Asset %s not found" % item) return else: print('Please specify the required parameter') return
def execute(self, arguments): asset_id = None from_addr = None watch_only = False do_count = False wallet = PromptData.Wallet arguments, from_addr_str = PromptUtils.get_from_addr(arguments) if from_addr_str: if not isValidPublicAddress(from_addr_str): print("Invalid address specified") return from_addr = wallet.ToScriptHash(from_addr_str) for item in arguments: if item == '--watch': watch_only = True elif item == '--count': do_count = True else: asset_id = PromptUtils.get_asset_id(wallet, item) return ShowUnspentCoins(wallet, asset_id, from_addr, watch_only, do_count)
def execute(self, arguments): jsn = get_arg(arguments) if not jsn: print("Please specify the required parameter") return False return parse_and_sign(PromptData.Wallet, jsn)
def BuildAndRun(arguments, wallet, verbose=True, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True): arguments, from_addr = get_from_addr(arguments) arguments, invoke_attrs = get_tx_attr_from_args(arguments) arguments, owners = get_owners_from_params(arguments) path = get_arg(arguments) contract_script = Build(arguments) if contract_script is not None: debug_map_path = path.replace('.py', '.debug.json') debug_map = None if os.path.exists(debug_map_path): with open(debug_map_path, 'r') as dbg: debug_map = json.load(dbg) return DoRun(contract_script, arguments, wallet, path, verbose, from_addr, min_fee, invocation_test_mode, debug_map=debug_map, invoke_attrs=invoke_attrs, owners=owners) else: print('Please check the path to your Python (.py) file to compile') return None, None, None, None
def execute(self, arguments=None): try: res = start_output_config() except KeyboardInterrupt: print('Output configuration cancelled') return return res
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) != 1: print("Please specify the required parameter") return False hash_string = arguments[0] try: script_hash = UInt160.ParseString(hash_string) except Exception: # because UInt160 throws a generic exception. Should be fixed in the future print("Invalid script hash") return False # try to find token and collect some data try: token = ModelNEP5Token.get(ContractHash=script_hash) except peewee.DoesNotExist: print(f"Could not find a token with script_hash {arguments[0]}") return False success = wallet.DeleteNEP5Token(script_hash) if success: print( f"Token {token.Symbol} with script_hash {arguments[0]} deleted" ) else: # probably unreachable to due token check earlier. Better safe than sorrow print(f"Could not find a token with script_hash {arguments[0]}") return success
def ImportContractAddr(wallet, contract_hash, pubkey_script_hash): """ Args: wallet (Wallet): a UserWallet instance contract_hash (UInt160): hash of the contract to import pubkey_script_hash (UInt160): Returns: neo.SmartContract.Contract.Contract """ contract = Blockchain.Default().GetContract(contract_hash) if not contract or not pubkey_script_hash: print("Could not find contract") return reedeem_script = contract.Code.Script.hex() # there has to be at least 1 param, and the first one needs to be a signature param param_list = bytearray(b'\x00') # if there's more than one param # we set the first parameter to be the signature param if len(contract.Code.ParameterList) > 1: param_list = bytearray(contract.Code.ParameterList) param_list[0] = 0 verification_contract = Contract.Create(reedeem_script, param_list, pubkey_script_hash) address = verification_contract.Address wallet.AddContract(verification_contract) print(f"Added contract address {address} to wallet") return verification_contract
def execute(self, arguments): if PromptData.Wallet: PromptData.close_wallet() path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify the required parameter") return if not os.path.exists(path): print("Wallet file not found") return try: passwd = prompt("[password]> ", is_password=True) except KeyboardInterrupt: print("Wallet opening cancelled") return password_key = to_aes_key(passwd) try: PromptData.Wallet = UserWallet.Open(path, password_key) PromptData.Prompt.start_wallet_loop() print("Opened wallet at %s" % path) return PromptData.Wallet except Exception as e: print("Could not open wallet: %s" % e)
def execute(self, arguments): if len(arguments) != 1: print("Please specify the required parameter") return False what = arguments[0] if what == 'reset': DebugStorage.instance().reset() print("Reset debug storage") return True try: flag = bool(util.strtobool(what)) except ValueError: print("Invalid option") return False settings.USE_DEBUG_STORAGE = flag if flag: print("Debug storage ON") else: print("Debug storage OFF") return True
def execute(self, arguments): item = get_arg(arguments) if item is not None: if item.lower() == "all": contracts = Blockchain.Default().ShowAllContracts() contractlist = [] for contract in contracts: state = Blockchain.Default().GetContract( contract.decode('utf-8')).ToJson() contract_dict = {state['name']: state['hash']} contractlist.append(contract_dict) print(json.dumps(contractlist, indent=4)) return contractlist try: hash = UInt160.ParseString(item).ToBytes() except Exception: print("Could not find contract from args: %s" % arguments) return contract = Blockchain.Default().GetContract(hash) if contract is not None: contract.DetermineIsNEP5() print(json.dumps(contract.ToJson(), indent=4)) return contract.ToJson() else: print("Contract %s not found" % item) return else: print('Please specify the required parameter') return
def execute(self, arguments=None): height = Blockchain.Default().Height headers = Blockchain.Default().HeaderHeight diff = height - PromptData.Prompt.start_height now = datetime.datetime.utcnow() difftime = now - PromptData.Prompt.start_dt mins = difftime / datetime.timedelta(minutes=1) secs = mins * 60 bpm = 0 tps = 0 if diff > 0 and mins > 0: bpm = diff / mins tps = Blockchain.Default().TXProcessed / secs syncmngr = SyncManager() out = "Progress: %s / %s\n" % (height, headers) out += "Block-cache length %s\n" % len(syncmngr.block_cache) out += "Blocks since program start %s\n" % diff out += "Time elapsed %s mins\n" % mins out += "Blocks per min %s \n" % bpm out += "TPS: %s \n" % tps print(out) return out
def execute(self, arguments): start_block = PromptUtils.get_arg(arguments, 0, convert_to_int=True) if not start_block or start_block < 0: start_block = 0 print(f"Restarting at block {start_block}") task = asyncio.create_task( PromptData.Wallet.sync_wallet(start_block, rebuild=True)) return task
def execute(self, arguments): addr_to_delete = PromptUtils.get_arg(arguments, 0) if not addr_to_delete: print("Please specify the required parameter") return False return DeleteAddress(PromptData.Wallet, addr_to_delete)
def execute(self, arguments=None): process = psutil.Process(os.getpid()) total = process.memory_info().rss totalmb = total / (1024 * 1024) out = "Total: %s MB\n" % totalmb out += "Total buffers: %s\n" % StreamManager.TotalBuffers() print(out) return out
def execute(self, arguments): if len(arguments) != 1: print("Please specify the required parameter") return Blockchain.Default().Pause() contract_script = Build(arguments) Blockchain.Default().Resume() return contract_script
def execute(self, arguments=None): if len(NodeLeader.Instance().Peers) > 0: out = "Total Connected: %s\n" % len(NodeLeader.Instance().Peers) for i, peer in enumerate(NodeLeader.Instance().Peers): out += f"Peer {i} {peer.Name():>12} - {peer.address:>21} - IO {peer.IOStats()}\n" print(out) return out else: print("Not connected yet\n") return
def TestInvokeContract(wallet, args, withdrawal_tx=None, from_addr=None, min_fee=DEFAULT_MIN_FEE, invoke_attrs=None, owners=None): BC = GetBlockchain() contract = BC.GetContract(args[0]) if contract: # params = args[1:] if len(args) > 1 else [] params, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments(params) params, parse_addresses = PromptUtils.get_parse_addresses(params) params.reverse() if '--i' in params: params = [] for index, iarg in enumerate(contract.Code.ParameterList): param, abort = PromptUtils.gather_param(index, iarg) if abort: return None, None, None, None, False params.append(param) params.reverse() sb = ScriptBuilder() for p in params: process_params(sb, p, wallet, parse_addresses) sb.EmitAppCall(contract.Code.ScriptHash().Data) out = sb.ToArray() outputs = [] if neo_to_attach: output = TransactionOutput(AssetId=Blockchain.SystemShare().Hash, Value=neo_to_attach, script_hash=contract.Code.ScriptHash(), ) outputs.append(output) if gas_to_attach: output = TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=gas_to_attach, script_hash=contract.Code.ScriptHash()) outputs.append(output) return test_invoke(out, wallet, outputs, withdrawal_tx, from_addr, min_fee, invoke_attrs=invoke_attrs, owners=owners) else: print("Contract %s not found" % args[0]) return None, None, None, None, False
def execute(self, arguments): PromptData.Prompt.stop_wallet_loop() start_block = PromptUtils.get_arg(arguments, 0, convert_to_int=True) if not start_block or start_block < 0: start_block = 0 print(f"Restarting at block {start_block}") PromptData.Wallet.Rebuild(start_block) PromptData.Prompt.start_wallet_loop()
def InvokeContract(wallet, tx, fee=Fixed8.Zero(), from_addr=None, owners=None): if from_addr is not None: from_addr = PromptUtils.lookup_addr_str(wallet, from_addr) try: wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True, from_addr=from_addr) except ValueError: print("Insufficient funds") return False if wallet_tx: if owners: for owner in list(owners): wallet_tx.Attributes.append( TransactionAttribute( usage=TransactionAttributeUsage.Script, data=owner)) wallet_tx.Attributes = make_unique_script_attr(tx.Attributes) context = ContractParametersContext(wallet_tx) wallet.Sign(context) if owners: gather_signatures(context, wallet_tx, list(owners)) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("SENDING TX: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def Build(arguments): path = get_arg(arguments) try: contract_script = Compiler.instance().load_and_save( path, use_nep8=settings.COMPILER_NEP_8) except FileNotFoundError: return newpath = path.replace('.py', '.avm') print("Saved output to %s " % newpath) return contract_script
def execute(self, arguments): if len(arguments) != 1: print("Please specify the required parameter") return try: contract_hash = UInt160.ParseString(arguments[0]).ToBytes() except Exception: print(f"Invalid contract hash: {arguments[0]}") return return ImportToken(PromptData.Wallet, contract_hash)
def execute(self, arguments): item = PromptUtils.get_arg(arguments) if not item: print(f"run `{self.command_desc().command} help` to see supported queries") return try: return self.execute_sub_command(item, arguments[1:]) except KeyError: print(f"{item} is an invalid parameter") return
def AddAlias(wallet, addr, title): if wallet is None: print("Please open a wallet") return False try: script_hash = wallet.ToScriptHash(addr) wallet.AddNamedAddress(script_hash, title) return True except Exception as e: print(e) return False
def execute(self, arguments): if len(arguments) in [1, 2]: if len(arguments) == 2: try: return NodeLeader.Instance().setBlockReqSizeAndMax(int(arguments[0]), int(arguments[1])) except ValueError: print("Invalid values. Please specify a block request part and max size for each node, like 30 and 1000") return False elif len(arguments) == 1: return NodeLeader.Instance().setBlockReqSizeByName(arguments[0]) else: print("Please specify the required parameter") return False
def Rebuild(self, start_block=0): try: super(UserWallet, self).Rebuild(start_block) logger.debug("wallet rebuild: deleting %s coins and %s transactions" % (Coin.select().count(), Transaction.select().count())) for c in Coin.select(): c.delete_instance() for tx in Transaction.select(): tx.delete_instance() except Exception as e: print("Could not rebuild %s " % e)
def execute(self, arguments): wallet = PromptData.Wallet item = PromptUtils.get_arg(arguments) if not wallet: print("Please open a wallet") return try: return self.execute_sub_command(item, arguments[1:]) except KeyError: print(f"{item} is an invalid parameter") return
def execute(self, arguments): item = get_arg(arguments) txarg = get_arg(arguments, 1) if item is not None: block = Blockchain.Default().GetBlock(item) if block is not None: block.LoadTransactions() if txarg and 'tx' in txarg: txs = [] for tx in block.FullTransactions: print(json.dumps(tx.ToJson(), indent=4)) txs.append(tx.ToJson()) return txs print(json.dumps(block.ToJson(), indent=4)) return block.ToJson() else: print("Could not locate block %s" % item) return else: print("Please specify the required parameter") return
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) != 3: print("Please specify the required parameters") return False token_str = arguments[0] from_addr = arguments[1] to_addr = arguments[2] try: token = PromptUtils.get_token(wallet, token_str) except ValueError as e: print(str(e)) return False try: allowance = token_get_allowance(wallet, token_str, from_addr, to_addr) print( f"{token.symbol} allowance for {from_addr} from {to_addr} : {allowance} " ) return True except ValueError as e: print(str(e)) return False
def execute(self, arguments=None): show_verbose = get_arg(arguments) == 'verbose' show_queued = get_arg(arguments) == 'queued' show_known = get_arg(arguments) == 'known' show_bad = get_arg(arguments) == 'bad' nodemgr = NodeManager() len_nodes = len(nodemgr.nodes) out = "" if len_nodes > 0: out = f"Connected: {len_nodes} of max {nodemgr.max_clients}\n" for i, node in enumerate(nodemgr.nodes): out += f"Peer {i} {node.version.user_agent:>12} {node.address:>21} height: {node.best_height:>8}\n" else: print("No nodes connected yet\n") if show_verbose: out += f"\n" out += f"Addresses in queue: {len(nodemgr.queued_addresses)}\n" out += f"Known addresses: {len(nodemgr.known_addresses)}\n" out += f"Bad addresses: {len(nodemgr.bad_addresses)}\n" if show_queued: out += f"\n" if len(nodemgr.queued_addresses) == 0: out += "No queued addresses" else: out += f"Queued addresses:\n" for addr in nodemgr.queued_addresses: out += f"{addr}\n" if show_known: out += f"\n" if len(nodemgr.known_addresses) == 0: out += "No known addresses other than connect peers" else: out += f"Known addresses:\n" for addr in nodemgr.known_addresses: out += f"{addr}\n" if show_bad: out += f"\n" if len(nodemgr.bad_addresses) == 0: out += "No bad addresses" else: out += f"Bad addresses:\n" for addr in nodemgr.bad_addresses: out += f"{addr}\n" print(out) return out
def execute(self, arguments): if len(arguments) < 6: print("Please specify the required parameters") return None, None, None, None Blockchain.Default().Pause() try: tx, result, total_ops, engine = BuildAndRun(arguments, PromptData.Wallet) except TypeError: print(f'run `{CommandSC().command_desc().command} {self.command_desc().command} help` to see supported queries') Blockchain.Default().Resume() return None, None, None, None Blockchain.Default().Resume() return tx, result, total_ops, engine