8000 eos/tests/testUtils.py at dan2 · dominic22/eos · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
executable file
·
1678 lines (1434 loc) · 66.3 KB

testUtils.py

File metadata and controls

executable file
·
1678 lines (1434 loc) · 66.3 KB
import copy
import decimal
import subprocess
import time
import glob
import shutil
import time
import os
from collections import namedtuple
import re
import string
import signal
import time
import datetime
import inspect
import sys
import random
import io
import json
###########################################################################################
class Utils:
Debug=False
FNull = open(os.devnull, 'w')
EosClientPath="programs/eosioc/eosioc"
EosWalletName="eosiowd"
EosWalletPath="programs/eosiowd/"+ EosWalletName
EosServerName="eosiod"
EosServerPath="programs/eosiod/"+ EosServerName
EosLauncherPath="programs/eosio-launcher/eosio-launcher"
MongoPath="mongo"
@staticmethod
def Print(*args, **kwargs):
stackDepth=len(inspect.stack())-2
str=' '*stackDepth
sys.stdout.write(str)
print(*args, **kwargs)
SyncStrategy=namedtuple("ChainSyncStrategy", "name id arg")
SyncNoneTag="none"
SyncReplayTag="replay"
SyncResyncTag="resync"
SigKillTag="kill"
SigTermTag="term"
systemWaitTimeout=60
# mongoSyncTime: eosiod mongodb plugin seems to sync with a 10-15 seconds delay. This will inject
# a wait period before the 2nd DB check (if first check fails)
mongoSyncTime=25
amINoon=True
# Configure for the NOON branch
@staticmethod
def iAmNotNoon():
Utils.amINoon=False
Utils.EosClientPath="programs/eosc/eosc"
Utils.EosWalletName="eos-walletd"
Utils.EosWalletPath="programs/eos-walletd/"+ Utils.EosWalletName
Utils.EosServerName="eosd"
Utils.EosServerPath="programs/eosd/"+ Utils.EosServerName
@staticmethod
def setMongoSyncTime(syncTime):
Utils.mongoSyncTime=syncTime
@staticmethod
def setSystemWaitTimeout(timeout):
Utils.systemWaitTimeout=timeout
@staticmethod
def getChainStrategies():
chainSyncStrategies={}
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncNoneTag, 0, "")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStrategy
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncReplayTag, 1, "--replay-blockchain")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStrategy
chainSyncStrategy=Utils.SyncStrategy(Utils.SyncResyncTag, 2, "--resync-blockchain")
chainSyncStrategies[chainSyncStrategy.name]=chainSyncStr 8000 ategy
return chainSyncStrategies
@staticmethod
def checkOutput(cmd):
assert(isinstance(cmd, list))
retStr=subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
return retStr
@staticmethod
def errorExit(msg="", raw=False, errorCode=1):
Utils.Print("ERROR:" if not raw else "", msg)
exit(errorCode)
###########################################################################################
class Table(object):
def __init__(self, name):
self.name=name
self.keys=[]
self.data=[]
###########################################################################################
class Transaction(object):
def __init__(self, transId):
self.transId=transId
self.tType=None
self.amount=0
###########################################################################################
class Account(object):
def __init__(self, name):
self.name=name
self.balance=0
self.ownerPrivateKey=None
self.ownerPublicKey=None
self.activePrivateKey=None
self.activePublicKey=None
def __str__(self):
return "Name; %s" % (self.name)
###########################################################################################
class Node(object):
def __init__(self, host, port, pid=None, cmd=None, alive=None, enableMongo=False, mongoHost="localhost", mongoPort=27017, mongoDb="EOStest"):
self.host=host
self.port=port
self.pid=pid
self.cmd=cmd
self.alive=alive
self.enableMongo=enableMongo
self.mongoSyncTime=None if Utils.mongoSyncTime < 1 else Utils.mongoSyncTime
self.mongoHost=mongoHost
self.mongoPort=mongoPort
self.mongoDb=mongoDb
self.endpointArgs="--host %s --port %d" % (self.host, self.port)
self.mongoEndpointArgs=""
if self.enableMongo:
self.mongoEndpointArgs += "--host %s --port %d %s" % (mongoHost, mongoPort, mongoDb)
def __str__(self):
#return "Host: %s, Port:%d, Pid:%s, Alive:%s, Cmd:\"%s\"" % (self.host, self.port, self.pid, self.alive, self.cmd)
return "Host: %s, Port:%d" % (self.host, self.port)
@staticmethod
def runCmdReturnJson(cmd, trace=False):
retStr=Utils.checkOutput(cmd.split())
jStr=Node.filterJsonObject(retStr)
trace and Utils.Print ("RAW > %s"% retStr)
trace and Utils.Print ("JSON> %s"% jStr)
try:
jsonData=json.loads(jStr)
except json.decoder.JSONDecodeError as ex:
Utils.Print ("RAW > %s"% retStr)
Utils.Print ("JSON> %s"% jStr)
return jsonData
@staticmethod
def __runCmdArrReturnJson(cmdArr, trace=False):
retStr=Utils.checkOutput(cmdArr)
jStr=Node.filterJsonObject(retStr)
trace and Utils.Print ("RAW > %s"% retStr)
trace and Utils.Print ("JSON> %s"% jStr)
jsonData=json.loads(jStr)
return jsonData
@staticmethod
def runCmdReturnStr(cmd, trace=False):
retStr=Node.__checkOutput(cmd.split())
trace and Utils.Print ("RAW > %s"% retStr)
return retStr
@staticmethod
def filterJsonObject(data):
firstIdx=data.find('{')
lastIdx=data.rfind('}')
retStr=data[firstIdx:lastIdx+1]
return retStr
@staticmethod
def __checkOutput(cmd):
retStr=subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
#retStr=subprocess.check_output(cmd).decode("utf-8")
return retStr
# Passes input to stdin, executes cmd. Returns tuple with return code(int),
# stdout(byte stream) and stderr(byte stream).
@staticmethod
def stdinAndCheckOutput(cmd, subcommand):
outs=None
errs=None
try:
popen=subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outs,errs=popen.communicate(input=subcommand.encode("utf-8"))
ret=popen.wait()
except subprocess.CalledProcessError as ex:
msg=ex.output
return (ex.returncode, msg, None)
return (0, outs, errs)
@staticmethod
def normalizeJsonObject(extJStr):
tmpStr=extJStr
tmpStr=re.sub(r'ObjectId\("(\w+)"\)', r'"ObjectId-\1"', tmpStr)
tmpStr=re.sub(r'ISODate\("([\w|\-|\:|\.]+)"\)', r'"ISODate-\1"', tmpStr)
return tmpStr
@staticmethod
def runMongoCmdReturnJson(cmdArr, subcommand, trace=False):
retId,outs,errs=Node.stdinAndCheckOutput(cmdArr, subcommand)
if retId is not 0:
return None
outStr=Node.byteArrToStr(outs)
if not outStr:
return None
extJStr=Node.filterJsonObject(outStr)
if not extJStr:
return None
jStr=Node.normalizeJsonObject(extJStr)
if not jStr:
return None
trace and Utils.Print ("RAW > %s"% outStr)
#trace and Utils.Print ("JSON> %s"% jStr)
jsonData=json.loads(jStr)
return jsonData
@staticmethod
def getTransId(trans):
#Utils.Print("%s" % trans)
transId=trans["transaction_id"]
return transId
@staticmethod
def byteArrToStr(arr):
return arr.decode("utf-8")
def setWalletEndpointArgs(self, args):
self.endpointArgs="--host %s --port %d %s" % (self.host, self.port, args)
def getBlock(self, blockNum, retry=True, silentErrors=False):
if not self.enableMongo:
cmd="%s %s get block %s" % (Utils.EosClientPath, self.endpointArgs, blockNum)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get block. %s" % (msg))
return None
else:
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Blocks.findOne( { "block_num": %s } )' % (blockNum)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get block. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def getBlockById(self, blockId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Blocks.findOne( { "block_id": "%s" } )' % (blockId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during db get block by id. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def doesNodeHaveBlockNum(self, blockNum):
assert isinstance(blockNum, int)
info=self.getInfo(silentErrors=True)
last_irreversible_block_num=int(info["last_irreversible_block_num"])
if blockNum > last_irreversible_block_num:
return False
else:
return True
def getTransaction(self, transId, retry=True, silentErrors=False):
if not self.enableMongo:
cmd="%s %s get transaction %s" % (Utils.EosClientPath, self.endpointArgs, transId)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during account by transaction retrieval. %s" % (msg))
return None
else:
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Transactions.findOne( { $and : [ { "transaction_id": "%s" }, {"pending":false} ] } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get trans. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def getTransByBlockId(self, blockId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Transactions.find( { "block_id": "%s" } )' % (blockId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand, True)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during db get trans by blockId. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def getActionFromDb(self, transId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Actions.findOne( { "transaction_id": "%s" } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get message. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def getMessageFromDb(self, transId, retry=True, silentErrors=False):
for i in range(2):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Messages.findOne( { "transaction_id": "%s" } )' % (transId)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
if trans is not None:
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db node get message. %s" % (msg))
return None
if not retry:
break
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def doesNodeHaveTransId(self, transId):
trans=self.getTransaction(transId, silentErrors=True)
if trans is None:
return False
blockNum=None
if not self.enableMongo:
blockNum=int(trans["transaction"]["data"]["ref_block_num"])
else:
blockNum=int(trans["ref_block_num"])
blockNum += 1
return self.doesNodeHaveBlockNum(blockNum)
def createInitAccounts(self):
eosio = copy.copy(Cluster.initaAccount)
eosio.name = "eosio"
# publish system contract
wastFile="contracts/eosio.system/eosio.system.wast"
abiFile="contracts/eosio.system/eosio.system.abi"
Utils.Print("Publish eosio.system contract")
trans=self.publishContract(eosio.name, wastFile, abiFile, waitForTransBlock=True)
if trans is None:
Utils.errorExit("Failed to publish eosio.system.")
Utils.Print("push issue action to eosio contract")
contract=eosio.name
action="issue"
data="{\"to\":\"eosio\",\"quantity\":\"1000000000.0000 EOS\"}"
opts="--permission eosio@active"
trans=self.pushMessage(contract, action, data, opts)
transId=Node.getTransId(trans[1])
self.waitForTransIdOnNode(transId)
expectedAmount=10000000000000
Utils.Print("Verify eosio issue, Expected: %d" % (expectedAmount))
actualAmount=self.getAccountBalance(eosio.name)
if expectedAmount != actualAmount:
Utils.errorExit("Issue verification failed. Excepted %d, actual: %d" % (expectedAmount, actualAmount))
initx = copy.copy(Cluster.initaAccount)
self.createAccount(Cluster.initaAccount, eosio, 0)
for i in range(2, 21):
initx.name = "init" + chr(ord('a')+i)
self.createAccount(initx, eosio, 0)
self.createAccount(Cluster.initbAccount, eosio, 0, True)
for i in range(0, 21):
initx.name = "init" + chr(ord('a')+i)
trans = self.transferFunds(eosio, initx, 10000000000, "init")
transId=Node.getTransId(trans)
self.waitForTransIdOnNode(transId)
# Create account and return creation transactions. Return transaction json object
# waitForTransBlock: wait on creation transaction id to appear in a block
def createAccount(self, account, creatorAccount, stakedDeposit=1000, waitForTransBlock=False):
cmd=None
if Utils.amINoon:
cmd="%s %s create account %s %s %s %s" % (
Utils.EosClientPath, self.endpointArgs, creatorAccount.name, account.name,
account.ownerPublicKey, account.activePublicKey)
else:
cmd="%s %s create account %s %s %s %s" % (Utils.EosClientPath, self.endpointArgs,
creatorAccount.name, account.name,
account.ownerPublicKey, account.activePublicKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
transId=Node.getTransId(trans)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during account creation. %s" % (msg))
return None
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
if stakedDeposit > 0:
trans = self.transferFunds(creatorAccount, account, stakedDeposit, "init")
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getEosAccount(self, name):
cmd="%s %s get account %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get account. %s" % (msg))
return None
def getEosAccountFromDb(self, name):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand='db.Accounts.findOne({"name" : "%s"})' % (name)
Utils.Debug and Utils.Print("cmd: echo '%s' | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get account from db. %s" % (msg))
return None
def getEosCurrencyBalance(self, name):
cmd="%s %s get currency balance eosio %s EOS" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnStr(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get EOS balance. %s" % (msg))
return None
def getCurrencyBalance(self, contract, account, symbol):
cmd="%s %s get currency balance %s %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, account, symbol)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnStr(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get currency balance. %s" % (msg))
return None
def getCurrencyStats(self, contract, symbol=""):
cmd="%s %s get currency stats %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, symbol)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get currency stats. %s" % (msg))
return None
# Verifies account. Returns "get account" json return object
def verifyAccount(self, account):
if not self.enableMongo:
ret=self.getEosAccount(account.name)
if ret is not None:
account_name=ret["account_name"]
if account_name is None:
Utils.Print("ERROR: Failed to verify account creation.", account.name)
return None
return ret
else:
for i in range(2):
ret=self.getEosAccountFromDb(account.name)
if ret is not None:
account_name=ret["name"]
if account_name is None:
Utils.Print("ERROR: Failed to verify account creation.", account.name)
return None
return ret
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
return None
def waitForBlockNumOnNode(self, blockNum, timeout=None):
if timeout is None:
timeout=Utils.systemWaitTimeout
startTime=time.time()
remainingTime=timeout
Utils.Debug and Utils.Print("cmd: remaining time %d seconds" % (remainingTime))
while time.time()-startTime < timeout:
if self.doesNodeHaveBlockNum(blockNum):
return True
sleepTime=3 if remainingTime > 3 else (3 - remainingTime)
remainingTime -= sleepTime
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (sleepTime))
time.sleep(sleepTime)
return False
def waitForTransIdOnNode(self, transId, timeout=None):
if timeout is None:
timeout=Utils.systemWaitTimeout
startTime=time.time()
remainingTime=timeout
Utils.Debug and Utils.Print("cmd: remaining time %d seconds" % (remainingTime))
while time.time()-startTime < timeout:
if self.doesNodeHaveTransId(transId):
return True
sleepTime=3 if remainingTime > 3 else (3 - remainingTime)
remainingTime -= sleepTime
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (sleepTime))
time.sleep(sleepTime)
return False
def waitForNextBlock(self, timeout=None):
if timeout is None:
timeout=Utils.systemWaitTimeout
startTime=time.time()
remainingTime=timeout
Utils.Debug and Utils.Print("cmd: remaining time %d seconds" % (remainingTime))
num=self.getIrreversibleBlockNum()
Utils.Debug and Utils.Print("Current block number: %s" % (num))
while time.time()-startTime < timeout:
nextNum=self.getIrreversibleBlockNum()
if nextNum > num:
Utils.Debug and Utils.Print("Next block number: %s" % (nextNum))
return True
sleepTime=.5 if remainingTime > .5 else (.5 - remainingTime)
remainingTime -= sleepTime
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (sleepTime))
time.sleep(sleepTime)
return False
# Trasfer funds. Returns "transfer" json return object
def transferFunds(self, source, destination, amount, memo="memo", force=False):
cmd="%s %s -v transfer %s %s %d" % (
Utils.EosClientPath, self.endpointArgs, source.name, destination.name, amount)
cmdArr=cmd.split()
cmdArr.append(memo)
if force:
cmdArr.append("-f")
Utils.Debug and Utils.Print("cmd: %s" % (cmdArr))
trans=None
try:
trans=Node.__runCmdArrReturnJson(cmdArr)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during funds transfer. %s" % (msg))
return None
def validateSpreadFundsOnNode(self, adminAccount, accounts, expectedTotal):
actualTotal=self.getAccountBalance(adminAccount.name)
for account in accounts:
fund = self.getAccountBalance(account.name)
if fund != account.balance:
Utils.Print("ERROR: validateSpreadFunds> Expected: %d, actual: %d for account %s" %
(account.balance, fund, account.name))
return False
actualTotal += fund
if actualTotal != expectedTotal:
Utils.Print("ERROR: validateSpreadFunds> Expected total: %d , actual: %d" % (
expectedTotal, actualTotal))
return False
return True
def getSystemBalance(self, adminAccount, accounts):
balance=self.getAccountBalance(adminAccount.name)
for account in accounts:
balance += self.getAccountBalance(account.name)
return balance
# Gets accounts mapped to key. Returns json object
def getAccountsByKey(self, key):
cmd="%s %s get accounts %s" % (Utils.EosClientPath, self.endpointArgs, key)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during accounts by key retrieval. %s" % (msg))
return None
# Gets accounts mapped to key. Returns array
def getAccountsArrByKey(self, key):
trans=self.getAccountsByKey(key)
accounts=trans["account_names"]
return accounts
def getServants(self, name):
cmd="%s %s get servants %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during servants retrieval. %s" % (msg))
return None
def getServantsArr(self, name):
trans=self.getServants(name)
servants=trans["controlled_accounts"]
return servants
def getAccountBalance(self, name):
if not self.enableMongo:
amount=self.getEosCurrencyBalance(name)
Utils.Debug and Utils.Print("getEosCurrencyBalance", name, amount)
balanceStr=amount.split()[0]
balance=int(decimal.Decimal(balanceStr[1:])*10000)
return balance
else:
if self.mongoSyncTime is not None:
Utils.Debug and Utils.Print("cmd: sleep %d seconds" % (self.mongoSyncTime))
time.sleep(self.mongoSyncTime)
account=self.getEosAccountFromDb(name)
if account is not None:
field=account["eos_balance"]
balanceStr=field.split()[0]
balance=int(float(balanceStr)*10000)
return balance
return None
# transactions lookup by id. Returns json object
def getTransactionsByAccount(self, name):
cmd="%s %s get transactions %s" % (Utils.EosClientPath, self.endpointArgs, name)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during transactions by account retrieval. %s" % (msg))
return None
# transactions lookup by id. Returns list of transaction ids
def getTransactionsArrByAccount(self, name):
trans=self.getTransactionsByAccount(name)
transactions=trans["transactions"]
transArr=[]
for transaction in transactions:
id=transaction["transaction_id"]
transArr.append(id)
return transArr
def getAccountCodeHash(self, account):
cmd="%s %s get code %s" % (Utils.EosClientPath, self.endpointArgs, account)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
retStr=Utils.checkOutput(cmd.split())
#Utils.Print ("get code> %s"% retStr)
p=re.compile('code\shash: (\w+)\n', re.MULTILINE)
m=p.search(retStr)
if m is None:
msg="Failed to parse code hash."
Utils.Print("ERROR: "+ msg)
return None
return m.group(1)
trans=Node.runCmdReturnJson(cmd, True)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during code hash retrieval. %s" % (msg))
return None
# publish contract and return transaction as json object
def publishContract(self, account, wastFile, abiFile, waitForTransBlock=False, shouldFail=False):
cmd="%s %s -v set contract %s %s %s" % (Utils.EosClientPath, self.endpointArgs, account, wastFile, abiFile)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
if not shouldFail:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during code hash retrieval. %s" % (msg))
return None
else:
retMap={}
retMap["returncode"]=ex.returncode
retMap["cmd"]=ex.cmd
retMap["output"]=ex.output
# commented below as they are available only in Python3.5 and above
# retMap["stdout"]=ex.stdout
# retMap["stderr"]=ex.stderr
return retMap
if shouldFail:
Utils.Print("ERROR: The publish contract did not fail as expected.")
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
# create producer and return transaction as json object
def createProducer(self, account, ownerPublicKey, waitForTransBlock=False):
cmd="%s %s create producer %s %s" % (Utils.EosClientPath, self.endpointArgs, account, ownerPublicKey)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during producer creation. %s" % (msg))
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getTable(self, account, contract, table):
cmd="%s %s get table %s %s %s" % (Utils.EosClientPath, self.endpointArgs, account, contract, table)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during table retrieval. %s" % (msg))
return None
def getTableRows(self, account, contract, table):
jsonData=self.getTable(account, contract, table)
if jsonData is None:
return None
rows=jsonData["rows"]
return rows
def getTableRow(self, account, contract, table, idx):
if idx < 0:
Utils.Print("ERROR: Table index cannot be negative. idx: %d" % (idx))
return None
rows=self.getTableRows(account, contract, table)
if rows is None or idx >= len(rows):
Utils.Print("ERROR: Retrieved table does not contain row %d" % idx)
return None
row=rows[idx]
return row
def getTableColumns(self, account, contract, table):
row=self.getTableRow(account, contract, table, 0)
keys=list(row.keys())
return keys
# returns tuple with transaction and
def pushMessage(self, contract, action, data, opts, silentErrors=False):
cmd=None
if Utils.amINoon:
cmd="%s %s push action %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, action)
else:
cmd="%s %s push message %s %s" % (Utils.EosClientPath, self.endpointArgs, contract, action)
cmdArr=cmd.split()
if data is not None:
cmdArr.append(data)
if opts is not None:
cmdArr += opts.split()
Utils.Debug and Utils.Print("cmd: %s" % (cmdArr))
try:
trans=Node.__runCmdArrReturnJson(cmdArr)
return (True, trans)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
if not silentErrors:
Utils.Print("ERROR: Exception during push message. %s" % (msg))
return (False, msg)
def setPermission(self, account, code, pType, requirement, waitForTransBlock=False):
cmd="%s %s set action permission %s %s %s %s" % (
Utils.EosClientPath, self.endpointArgs, account, code, pType, requirement)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
trans=None
try:
trans=Node.runCmdReturnJson(cmd)
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during set permission. %s" % (msg))
return None
transId=Node.getTransId(trans)
if waitForTransBlock and not self.waitForTransIdOnNode(transId):
return None
return trans
def getInfo(self, silentErrors=False):
cmd="%s %s get info" % (Utils.EosClientPath, self.endpointArgs)
Utils.Debug and Utils.Print("cmd: %s" % (cmd))
try:
trans=Node.runCmdReturnJson(cmd)
return trans
except subprocess.CalledProcessError as ex:
if not silentErrors:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get info. %s" % (msg))
return None
def getBlockFromDb(self, idx):
cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
subcommand="db.Blocks.find().sort({\"_id\":%d}).limit(1).pretty()" % (idx)
Utils.Debug and Utils.Print("cmd: echo \"%s\" | %s" % (subcommand, cmd))
try:
trans=Node.runMongoCmdReturnJson(cmd.split(), subcommand)
return trans
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during get db block. %s" % (msg))
return None
def checkPulse(self):
info=self.getInfo(True)
if info is not None:
self.alive=True
return True
else:
self.alive=False
return False
def getHeadBlockNum(self):
if not self.enableMongo:
info=self.getInfo()
if info is not None:
headBlockNumTag="head_block_num"
return info[headBlockNumTag]
else:
block=self.getBlockFromDb(-1)
if block is not None:
blockNum=block["block_num"]
return blockNum
return None
def getIrreversibleBlockNum(self):
if not self.enableMongo:
info=self.getInfo()
if info is not None:
return info["last_irreversible_block_num"]
else:
block=self.getBlockFromDb(-1)
if block is not None:
blockNum=block["block_num"]
return blockNum
return None
###########################################################################################
Wallet=namedtuple("Wallet", "name password host port")
class WalletMgr(object):
__walletLogFile="test_walletd_output.log"
__walletDataDir="test_wallet_0"
# walletd [True|False] Will wallet me in a standalone process
def __init__(self, walletd, eosiodPort=8888, eosiodHost="localhost", port=8899, host="localhost"):
self.walletd=walletd
self.eosiodPort=eosiodPort
self.eosiodHost=eosiodHost
self.port=port
self.host=host
self.wallets={}
self.__walletPid=None
self.endpointArgs="--host %s --port %d" % (self.eosiodHost, self.eosiodPort)
if self.walletd:
self.endpointArgs += " --wallet-host %s --wallet-port %d" % (self.host, self.port)
def launch(self):
if not self.walletd:
Utils.Print("ERROR: Wallet Manager wasn't configured to launch walletd")
return False
cmd="%s --data-dir %s --config-dir %s --http-server-address=%s:%d" % (
Utils.EosWalletPath, WalletMgr.__walletDataDir, WalletMgr.__walletDataDir, self.host, self.port)
Utils.Print("cmd: %s" % (cmd))
with open(WalletMgr.__walletLogFile, 'w') as sout, open(WalletMgr.__walletLogFile, 'w') as serr:
popen=subprocess.Popen(cmd.split(), stdout=sout, stderr=serr)
self.__walletPid=popen.pid
# Give walletd time to warm up
time.sleep(1)
return True
0