def CreateFirmware(_actor, _num): if os.path.exists(firmwareDir): for the_file in os.listdir(firmwareDir): file_path = os.path.join(firmwareDir, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: printError('Cannot clean a firmware directory', [e]) return False cmd = [VendorExe, '--bat', str(_num)] _ret = runCmdWithActor(cmd, _actor) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval num_files = 0 files = [] if os.path.exists(firmwareDir): for the_file in os.listdir(firmwareDir): file_path = os.path.join(firmwareDir, the_file) files.append(file_path) if os.path.isfile(file_path): num_files = num_files + 1 retval = num_files == _num if not retval: printError('Number of generated firmwares is not correct', files) return retval
def ScenterRegTwoOptions(_actor, _failed=False): setAcc(_actor, scenterFile) cmd = [ScenterExe, '--reg'] _ret = runCmd(cmd, _miner=True) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval try: flag = mgmtContract.functions.serviceCenters(_actor["account"]).call() except ValueError as error: printError("Cannot call serviceCenters()", [error]) return retval if not flag: printError("Got 'False' from contract", _ret[1]) return retval if not _failed: forma = ['Registered successfully'] else: forma = ['Already registered'] return checkOutput(_ret[1], forma)
def insertTweet(self, tweet): try: userId = self.insertUser(tweet.user) hashtagsIds = self.insertHashtags(tweet.hashtags) table = 'Tweet' columns = [ 'Texto', 'Data', 'Retweets', 'Likes', 'Usuario_idUsuario', 'idTweetOrigem', 'Lugar_idLugar' ] selectWhere = self.select('*', table, "idTweetOrigem = '" + tweet.id + "'") if selectWhere == (): lugarId = self.insertLocation(tweet.user.location) values = [ tweet.tweetText, tweet.tweetDate, tweet.retweetCount, tweet.likes, userId, tweet.id, lugarId ] tweetId = self.insert(table, columns, values) for x in hashtagsIds: self.insertTweetHashtag(tweetId, x) self.insertTweetcandidate(tweetId, tweet.candidato, tweet.sentimento) else: tweetId = selectWhere[0] return tweetId except: printError()
def CarRegTwoOptions(_actor, _failed=False): data = {'key': privKeys[_actor['account']]} writeDataBase(data, carFile) cmd = [CarExe, '--reg'] _ret = runCmd(cmd, _miner=True) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval try: flag = mgmtContract.functions.cars(_actor["account"]).call() except ValueError as error: printError("Cannot call cars()", [error]) return retval if not flag: printError("Got 'False' from contract", _ret[1]) return retval if not _failed: forma = ['Registered successfully'] else: forma = ['Already registered'] return checkOutput(_ret[1], forma)
def VendorRegFewBatteries(_actor, _num, _value=0): walletContractAddress = mgmtContract.functions.walletContract().call() prev_balance = w3.eth.getBalance(walletContractAddress) batId = None if _value == 0: cmd = [VendorExe, '--bat', str(_num)] else: cmd = [VendorExe, '--bat', str(_num), str(_value)] _ret = runCmdWithActor(cmd, _actor) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval cur_balance = w3.eth.getBalance(walletContractAddress) wei_value = w3.toWei(_value, 'ether') if not (prev_balance + wei_value == cur_balance): printError("Wallet balance was not changed", _ret[1]) return retval if (len(_ret[1]) != _num): printError("Not enough new batteries", _ret[1]) else: retval = True return retval
def VendorRegisterNotUniqueAddressFail(_actor, _name, _value): walletContractAddress = mgmtContract.functions.walletContract().call() prev_balance = w3.eth.getBalance(walletContractAddress) cmd = [VendorExe, '--reg', _name, str(_value)] _ret = runCmdWithActor(cmd, _actor) retval = False if not _ret[0]: print("The command executed too long") return retval cur_balance = w3.eth.getBalance(walletContractAddress) if not (cur_balance - prev_balance == 0): printError("Wallet balance was changed", _ret[1]) return retval try: deposit = mgmtContract.functions.vendorDeposit( _actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval retval = checkOutput(_ret[1], ['Failed. The vendor address already used.']) return retval
def getTweet(self, id): tweet = '' try: tweet =self.api.get_status(id,tweet_mode='extended') tweet = Tweet(tweet,id) except: printError() return tweet
def insert(self, table, columns, values): try: columns = tratarColumnsDao(columns) values = tratarValuesDao(values) valor = "INSERT INTO {}({}) VALUES ('{}')".format( table, columns, values) self.cursor.execute(valor) self.dbHelper.conn.commit() return self.cursor.lastrowid except: printError()
def selectIds(self, lastid): rangeId = lastid + 2000 try: table = 'manager' result = self.select( '*', table, "idMining > " + str(lastid) + " and idMining <" + str(rangeId)) if result != (): return result except: printError()
def insertUser(self, user): try: table = 'Usuario' columns = ['Nome', 'Followers', 'TotalTweets'] values = [user.userName, user.usersFollowers, user.usersTweets] selectWhere = self.select('*', table, "Nome= '" + user.userName + "'") if selectWhere == (): userId = self.insert(table, columns, values) else: userId = selectWhere[0]['idUsuario'] return userId except: printError()
def select(self, columns, table, whereArg=''): try: if whereArg != '': selectWhere = 'SELECT {} FROM {} WHERE {};'.format( columns, table, whereArg) self.cursor.execute(selectWhere) result = self.cursor.fetchall() else: self.cursor.execute('SELECT {} FROM {};'.format( columns, table)) result = self.cursor.fetchall() return result except: printError()
def insertTweetHashtag(self, idTweet, idHashtag): try: table = 'tweet_has_hashtag' columns = ['tweet_idTweet', 'hashtag_idHashTag'] values = [idTweet, idHashtag] selectWhere = self.select( '*', table, "tweet_idTweet = '" + str(idTweet) + "' AND hashtag_idHashTag = '" + str(idHashtag) + "'") if selectWhere == (): result = self.insert(table, columns, values) else: result = 0 return result except: printError()
def CarNewAccount(): cmd = [CarExe, "--new"] _ret = runCmd(cmd) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval data = openDataBase(carFile) if 'key' not in data: printError("Incorrect database", _ret[1]) return retval return checkOutput(_ret[1], [privtopub(data['key'])])
def FirmwareCheckCharges(): files = [] if os.path.exists(firmwareDir): for the_file in os.listdir(firmwareDir): file_path = os.path.join(firmwareDir, the_file) if os.path.isfile(file_path): files.append(the_file) retval = False curdir = os.getcwd() os.chdir(firmwareDir) fw = choice(files) cmd = [fw, '--charge'] _ret = runCmd(cmd) if _ret[0]: printError("Output is not expected, or something went wrong", _ret[1]) return retval _ret = runCmd(cmd, True) if _ret[0]: printError("Output is not expected, or something went wrong", _ret[1]) return retval _ret = runCmd(cmd, True) if _ret[0]: printError("Output is not expected, or something went wrong", _ret[1]) return retval cmd = [fw, '--get'] _ret = runCmd(cmd, True) os.chdir(curdir) if not _ret[0]: print("The command executed too long or there is nothing on output") return retval if len(_ret[1]) != 5: printError('Firwmare output is not correct', _ret[1]) else: retval = int(_ret[1][0]) == 3 if not retval: printError('Firwmare output is not correct', _ret[1]) return retval
def insertTweetcandidate(self, idTweet, idCandidato, idSentimento): try: table = 'tweetcandidato' columns = [ 'Tweet_idTweet', 'Candidato_idCandidato', 'Sentimento_idSentimento' ] values = [idTweet, idCandidato, idSentimento] selectWhere = self.select('*', table, "Tweet_idTweet = '" + str(idTweet) + "'") if selectWhere == (): result = self.insert(table, columns, values) else: result = 'error' return result except: printError()
def insertLocation(self, location): try: table = 'lugar' columns = ['Cidade', 'Estado', 'Pais'] city = location['city'] state = location['state'] country = location['country'] values = [city, state, country] selectWhere = self.select( '*', table, "Cidade = '" + city + "' AND Estado = '" + state + "'") if selectWhere == (): result = self.insert(table, columns, values) else: result = selectWhere[0]['idLugar'] return result except: printError()
def insertHashtags(self, hashtags): try: table = 'Hashtag' columns = 'Texto' hashtagIds = [] for hashtag in hashtags: values = [hashtag['text']] selectWhere = self.select('*', table, "Texto = '" + values[0] + "'") if selectWhere == (): hashtagIds.append(self.insert(table, [columns], values)) else: hashtagId = selectWhere[0]['idHashTag'] hashtagIds.append(hashtagId) return hashtagIds except: printError()
def updateLugar(self): try: table = 'lugar' select = self.select('*', table) formatPlace = FormatPlace() print(len(select)) for x in range(len(select)): endereco = "{} {} {}".format(select[x]['Cidade'], select[x]['Estado'], select[x]['Pais']) print(endereco) endereco = formatPlace.localizationCoord(endereco) query = "UPDATE lugar SET lat = {} , lng = {} WHERE idLugar = {}".format( endereco['lat'], endereco['lng'], select[x]['idLugar']) print(query) self.cursor.execute(query) self.dbHelper.conn.commit() except: printError()
def VendorDeposit(_actor): cmd = [VendorExe, '--deposit'] _ret = runCmdWithActor(cmd, _actor) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval try: cur_deposit = mgmtContract.functions.vendorDeposit( _actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval forma = ['Deposit: {}'.format(w3.fromWei(cur_deposit, 'ether'))] return checkOutput(_ret[1], forma)
def visitFuncdef(self, ctx: EasyParser.FuncdefContext): """ This function handles function traslation :param ctx: :return: """ #It resets symbolic table -> so no global variables are allowed self.funcs_symtab.reset() funcname = str(ctx.NAME()) param = utils.getVarArgList(ctx.varparameters().varargslist()) arg_types = list(map(lambda x: x[1], param)) functype = ir.FunctionType(utils.getDtype(ctx.d_type()), arg_types) if funcname in self.module.globals: utils.printError(ctx, "Function already declared") sys.exit(0) else: func = ir.Function(self.module, functype, funcname) entry = func.append_basic_block('entry') self.builder = ir.IRBuilder(entry) for i, arg in enumerate(func.args): alloca = self.alloc(*param[i]) self.builder.store(arg, alloca) self.funcs_symtab.set(ctx, param[i][0], alloca) self.generateCode(ctx.block()) # Build the inner body of function if not self.builder.block.is_terminated: if functype.return_type == ir.VoidType(): # if the function is void type, we automatcaly # add return void self.builder.ret_void() else: utils.printError( ctx, "Function :{} is not terminated!!! " "by return statement".format(funcname)) sys.exit(0)
def testSetupCreateManagementContract(_actor, _fee): global mgmtContract, currentBatFee, currentRegFee currentBatFee = _fee currentRegFee = 1000 * currentBatFee _cmd = [SetupExe, '--setup', str(currentBatFee)] _ret = runCmdWithActor(_cmd, _actor) retval = False if not _ret[0]: print("The command executed too long") return retval db = openDataBase() if not ('mgmtContract' in db): printError('Database was not found or it is in incorrect format', _ret[1]) else: mgmtContractAddress = db['mgmtContract'] mgmtContract = ManagementContract(w3, mgmtContractAddress) try: batContractAddress = mgmtContract.functions.batteryManagement( ).call() except ValueError as error: printError("Cannot call batteryManagement()", [error]) return retval batContract = BatteryContract(w3, batContractAddress) try: erc20ContractAddress = batContract.functions.erc20().call() except ValueError as error: printError("Cannot call erc20()", [error]) return retval try: walletContractAddress = mgmtContract.functions.walletContract( ).call() except ValueError as error: printError("Cannot call erc20()", [error]) return retval forma = 'Management contract: {}\nWallet contract: {}\nCurrency contract: {}' forma = forma.format(mgmtContractAddress, walletContractAddress, erc20ContractAddress).split('\n') retval = checkOutput(_ret[1], forma) return retval
def testVendorNewAccount(): prev_acc_list = w3.eth.accounts cmd = [VendorExe, "--new", "'New_password'"] ret = runCmd(cmd) retval = False if not ret[0]: print("The command executed too long") return retval new_acc_list = w3.eth.accounts diff = set(prev_acc_list) ^ set(new_acc_list) if len(diff) == 0: printError("New account not found on the node", ret[1]) else: account = list(diff)[0] retval = checkOutput(ret[1], [account]) return retval
def visitDefault(self, ctx: EasyParser.DefaultContext): """ Function, which generate variable declaration code or just return a constant :param ctx: :return: """ # accesing a variable or statement true or False if ctx.NAME() is not None: name = str(ctx.NAME()) if name == "True": return ir.Constant(self.int1, 1) if name == "False": return ir.Constant(self.int1, 0) tmp = self.funcs_symtab.get(ctx, name) return self.builder.load(tmp) # Generating code for number elif ctx.NUMBER() is not None: return ir.Constant(self.int32, int(str(ctx.NUMBER()))) #generating code for char elif ctx.CHAR() is not None: ch = str(ctx.CHAR())[1:][:-1] return ir.Constant(self.int8, ord(ch)) # Creating a global string variable and return pointer # to that string elif ctx.STRING() is not None: string = str(ctx.STRING()) string = string.replace('\\n', '\n') string = string.replace('\\r', '\r') string = string[1:][:-1].encode() + b'\x00' new_name = self.module.get_unique_name() my_type = ir.ArrayType(self.int8, len(string)) glo = ir.GlobalVariable(self.module, my_type, new_name) glo.initializer = ir.Constant(my_type, bytearray(string)) return glo.gep([self.int32(0), self.int32(0)]) else: utils.printError(ctx, "Parsing basic type") sys.exit(0)
def ScenterNewAccount(): prev_acc_list = w3.eth.accounts cmd = [ScenterExe, "--new", "'New_password'"] _ret = runCmd(cmd) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval new_acc_list = w3.eth.accounts diff = set(prev_acc_list) ^ set(new_acc_list) if len(diff) == 0: printError("New account not found on the node", _ret[1]) else: account = list(diff)[0] retval = checkOutput(_ret[1], [account]) return retval
def updateSentimento(self): try: table = 'tweetcandidato' select = self.select('*', table, "Sentimento_idSentimento = 3") table = 'tweet' linguaKit = Linguakit() for x in select: select2 = self.select( '*', table, "idTweet = {}".format(x['Tweet_idTweet'])) sentimento = linguaKit.sent_analyze(select2[0]['Texto'])[2] if sentimento == 'NEGATIVE': sentimento = 1 elif sentimento == 'NONE': sentimento = 2 else: sentimento = 3 print(x['Tweet_idTweet']) query = "UPDATE tweetcandidato SET Sentimento_idSentimento = {} WHERE Tweet_idTweet = {}".format( sentimento, x['Tweet_idTweet']) print(query) self.cursor.execute(query) self.dbHelper.conn.commit() except: printError()
def VendorRegisterNewVendorSuccess(_actor, _name, _value): walletContractAddress = mgmtContract.functions.walletContract().call() prev_balance = w3.eth.getBalance(walletContractAddress) cmd = [VendorExe, '--reg', _name, str(_value)] _ret = runCmdWithActor(cmd, _actor) retval = False if not _ret[0]: print("The command executed too long") return retval cur_balance = w3.eth.getBalance(walletContractAddress) wei_value = w3.toWei(_value, 'ether') if not (cur_balance - prev_balance == wei_value): printError("Wallet balance was not changed", _ret[1]) return retval try: deposit = mgmtContract.functions.vendorDeposit( _actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval if deposit != wei_value: printError("Deposit differs", _ret[1]) return retval try: vendId = mgmtContract.functions.vendorId(_actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval forma = 'Success.\nVendor ID: {}'.format(str(w3.toHex(vendId))[2:]) forma = forma.split('\n') retval = checkOutput(_ret[1], forma) return retval
def VendorOwnerOneBattery(_actor, _failed=False): global exist_batId, batContract _newOwner = _actor['account'] _batId = exist_batId cmd = [VendorExe, '--owner', delHexPrefix(w3.toHex(_batId)), _newOwner] _ret = runCmdWithActor(cmd, ownerVendor) retval = False if not _ret[0]: print(_ret[1]) print("The command executed too long or there is nothing on output") return retval try: vendAddr = batContract.functions.vendorOf(_batId).call() except ValueError as error: printError("Cannot call vendorOf()", [error]) return retval try: ownerAddr = batContract.functions.ownerOf(_batId).call() except ValueError as error: printError("Cannot call ownerOf()", [error]) return retval forma = [] if not _failed: forma = ['Success'] if (vendAddr == '0x' + '0' * 40) or (_newOwner != ownerAddr): printError("Incorrect info in Battery management contract", _ret[1]) return retval else: forma = ['Failed. Not allowed to change ownership.'] if (vendAddr == '0x' + '0' * 40) or (_newOwner == ownerAddr): printError("Incorrect info in Battery management contract", _ret[1]) return retval return checkOutput(_ret[1], forma)
def VendorRegOneBatteryWithChangedFee(_setfeeactor, _actor, _newfee): _cmd = [SetupExe, '--setfee', str(_newfee)] _ret = runCmdWithActor(_cmd, _setfeeactor) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval try: prev_deposit = mgmtContract.functions.vendorDeposit( _actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval cmd = [VendorExe, '--bat', '1'] _ret = runCmdWithActor(cmd, _actor, True) retval = False if not _ret[0]: print("The command executed too long or there is nothing on output") return retval try: cur_deposit = mgmtContract.functions.vendorDeposit( _actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval retval = prev_deposit - cur_deposit == w3.toWei(currentBatFee, 'ether') if not retval: printError("Deposit differs unexpectedly", _ret[1]) return retval return retval
def SetupSetFeeTwoOptions(_actor, _fee, _failed=False): global currentBatFee, currentRegFee _cmd = [SetupExe, '--setfee', str(_fee)] _ret = runCmdWithActor(_cmd, _actor) retval = False if not _ret[0]: print("The command executed too long") return retval if (len(_ret[1]) == 0): printError("No output") return retval else: newBatFee = w3.toWei(_fee, 'ether') try: currentBatFeeWei = mgmtContract.functions.batteryFee().call() except ValueError as error: printError("Cannot call batteryFee()", [error]) return retval currentBatFee = w3.fromWei(currentBatFeeWei, 'ether') currentRegFee = Decimal.normalize(1000 * currentBatFee) if newBatFee != currentBatFeeWei: printError("Fee was not set", _ret[1]) return retval if not _failed: forma = ['Updated successfully'] else: forma = ['No permissions to change the service fee'] return checkOutput(_ret[1], forma)
def VendorRegisterInsufficientFundsFail(_name, _value): walletContractAddress = mgmtContract.functions.walletContract().call() prev_balance = w3.eth.getBalance(walletContractAddress) password = "******" actor = {"account": w3.personal.newAccount(password), "password": password} cmd = [VendorExe, '--reg', _name, str(_value)] _ret = runCmdWithActor(cmd, actor) retval = False if not _ret[0]: print("The command executed too long") return retval cur_balance = w3.eth.getBalance(walletContractAddress) if not (cur_balance - prev_balance == 0): printError("Wallet balance was changed", _ret[1]) return retval try: deposit = mgmtContract.functions.vendorDeposit(actor['account']).call() except ValueError as error: printError("Cannot call vendorDeposit()", [error]) return retval if deposit != 0: print(deposit) printError("Vendor was registered. Deposit is not equal to zero", _ret[1]) return retval retval = checkOutput(_ret[1], ['Failed. No enough funds to deposit.']) return retval