def main(): while True: try: bh = pw.height() r = req.get(url="https://api.binance.com/api/v3/avgPrice", params={'symbol': 'WAVESUSDT'}) if r.status_code == 200: refPrice = float(jsn.loads(r.text)['price']) scPrice = float( (oraclePrice.getData(regex='price')[0])['value']) / 100 diff = 100 * ((refPrice - scPrice) / refPrice) is_blocked_status = (oracle.getData( regex='is_blocked')[0])['value'] if not is_blocked_status and (diff >= 7 or diff <= -10): tx = address.invokeScript( oraclesSC, 'callEmergencyShutdown', [{ "type": "string", "value": "more_7-10prc_price_deviation_from_ref" }], []) print("Status- ES: price-ref: " + str(refPrice) + "; price-sc: " + str(scPrice) + "; diff (%): " + str(diff)) elif is_blocked_status: print("Status- SHUTDOWN: price-ref: " + str(refPrice) + "; price-sc: " + str(scPrice) + "; diff (%): " + str(diff)) else: print("Status- OK: price-ref: " + str(refPrice) + "; price-sc: " + str(scPrice) + "; diff (%): " + str(diff)) except Exception as inst: print(inst) sleep(11)
async def saveTestsToPickle(): CURRENT_HEIGHT = int(pw.height()) for testId in list(testResults): if int(testId) <= CURRENT_HEIGHT - 20: pickle.dump(testResults[testId], open("results/" + testId + ".pickle", "wb")) del testResults[testId] pickle.dump(testResults, open("testResults.pickle", "wb"))
def getHeight(): x = 0 global numNodes for attempt in range(attempts): try: pw.setNode(node=nodes[numNodes]) height_1 = pw.height() pw.setNode(node=nodes[numNodes + 1]) height_2 = pw.height() return max(height_1, height_2) except Exception as e: logger.error(e) logger.warning("Problem with %s, going to try next one node", nodes[numNodes]) numNodes = (numNodes + 1) % (len(nodes) - 1) continue else: break else: raise Exception("All attempts failed")
def sendTokens(): currentHeight = py.height() global height global value #change in height present if currentHeight > height: numNewBlocks = currentHeight - height height = currentHeight #print("----------------------") #print(height) valueToSend = value * numNewBlocks for i in range(0, 10): walletAddress = wallets[i] myAddress.sendAsset(recipient=walletAddress, asset=token, amount=valueToSend)
py.setNode('https://sg.katalystcoin.com') DB_HOST = os.getenv('DB_HOST') DB_USER = os.getenv('DB_USER') DB_PASSWORD = os.getenv('DB_PASSWORD') DB_DATABASE = os.getenv('DB_DATABASE') connection = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, database=DB_DATABASE, connect_timeout=3600) cursor = connection.cursor() current_height = py.height() - 1 current_block = py.block(current_height) transactions_in_block = current_block['transactions'] hashes_to_process = [] print('reading current height: ', current_height) for i in range(len(transactions_in_block)): get_transactions_attachment = str(transactions_in_block[i]['attachment']) decoded_attachment = base58.b58decode(get_transactions_attachment) hashes_to_process.append(str(decoded_attachment.decode('utf-8'))) hash_tuple = tuple(hashes_to_process) print('hashes to process', hash_tuple) logging.info('Read height: {}'.format(str(current_height)))
'fresh return verb source radio response broom space appear way energy owner polar electric lock' )) #initialisation py.setNode('https://sg.katalystcoin.com') scheduler = BlockingScheduler() token = py.Asset('GQsFCrD43pHkhdvt5PnZ4W9Qgg8X9LjCSWAUG6mLoFMg') #dioncoin myAddress = py.Address( privateKey='6QsHMXahBHQmaYjA2PMDR3BFXRyWWHCAJfVMn7dWXPrk') #myAddress.sendAsset(recipient = py.Address(privateKey='7VkCrrhhueZTRiwwdBZ8R4DS82M3qTFGXVb8JxXhtRCg'), asset = token, amount = 100) initialiseWallets() height = py.height() value = 25 * math.pow(10, 7) def sendTokens(): currentHeight = py.height() global height global value #change in height present if currentHeight > height: numNewBlocks = currentHeight - height height = currentHeight #print("----------------------") #print(height)
async def register_ip(): async with ClientSession() as session: #first we check wich gateways to connect to print('--------------------------------------') print('Checking which gateways to connect to.') checkBurnUrl = DATA_API_URL + 'transactions/burn?sort=desc&limit=100&assetId=' + RFBT_ADDRESS try: async with session.get(checkBurnUrl) as response: httpStatus = response.status checkBurnResponseData = await response.json() burnTransactions = [] burnSenders = [] rfbGateways.clear() for i in range(0, len(checkBurnResponseData['data'])): burnTransactions.append({ 'sender': checkBurnResponseData['data'][i]['data']['sender'], 'amount': checkBurnResponseData['data'][i]['data']['amount'], 'id': checkBurnResponseData['data'][i]['data']['id'] }) burnSenders.append( checkBurnResponseData['data'][i]['data']['sender']) for sender in set(burnSenders): myAddress = pw.Address(sender) if myAddress.balance(RFBT_ADDRESS) > 100000000: checkDataUrl = DATA_API_URL + 'transactions/data?sender=' + sender + '&key=RFBGateway_address&sort=desc&limit=100' try: async with session.get(checkDataUrl) as response: httpStatus = response.status checkDataResponseData = await response.json() #rfbGatewaysAll = [] #for z in range(0, len(checkDataResponseData['data'])): # rfbGatewaysAll.append(checkDataResponseData['data'][z]['data']['data'][0]['value']) rfbGateways.append( checkDataResponseData['data'][0]['data'] ['data'][0]['value']) except Exception as e: print(e) except Exception as e: print(e) rfbNodes_temp2 = [] rfbNodes_temp = [] print('list of allowed gateways:') print(rfbGateways) print('Registering at gateways.') for gateway in set(rfbGateways): print('Gateway ' + gateway + ' response:') gatewayUrl = 'http://' + str(gateway) + '/checkAPI' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'nodeWallet': ACCOUNT_ADDRESS } try: async with session.post(gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() #print(responseData) responseStatus = responseData['status'] responseMessage = responseData['message'] if responseStatus == "success": rfbNodes_temp.append(responseData['rfbNodes']) NEW_NODE_ADDRESS = get('https://api.ipify.org').text if NEW_NODE_ADDRESS != NODE_ADDRESS[ 0] or responseStatus != "success": NODE_ADDRESS[0] = NEW_NODE_ADDRESS gatewayUrl = 'http://' + str(gateway) + '/registerAPI' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'nodeWallet': ACCOUNT_ADDRESS } async with session.post(gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() responseStatus = responseData['status'] responseMessage = responseData['message'] rfbNodes_temp.append(responseData['rfbNodes']) print(responseMessage) except Exception as e: print(e) #print('***') #print(rfbNodes_temp) if rfbNodes_temp: for node in rfbNodes_temp[0]: rfbNodes_temp2.append(node) rfbNodes = set(rfbNodes_temp2) if len(rfbNodes) >= 2: rfbNodes.remove(NODE_ADDRESS[0] + ':' + str(HOST_PORT)) fileName = "10k.txt" for rfbNode in rfbNodes: CURRENT_HEIGHT = str(pw.height()) if int(CURRENT_HEIGHT[-1:]) >= 5: LAST_DIGIT = "5" else: LAST_DIGIT = "0" testId = CURRENT_HEIGHT[:-1] + LAST_DIGIT asyncio.ensure_future(cleanTestResults(testId)) fileUrl = 'http://' + rfbNode + '/downloadFile/' + fileName + '/' + testId + '/' + str( HOST_PORT) async with ClientSession() as session: try: fileSize = 0 timestampStart = datetime.utcnow() async with session.get(fileUrl) as response: async for data in response.content.iter_chunked( 1024): fileSize += len(data) timestampEnd = datetime.utcnow() taskDuration = str(timestampEnd - timestampStart) if fileSize > 0: testResults.setdefault( testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'success', 'message': 'File downloaded', 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': taskDuration, 'fileName': fileName, 'sourceFileName': '10k.txt', 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd) } else: testResults.setdefault( testId, {} ).setdefault(rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'failed', 'message': 'Empty file downloaded', 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': taskDuration, 'fileName': fileName, 'sourceFileName': '10k.txt', 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd) } except Exception as e: timestampEnd = datetime.utcnow() taskDuration = str(timestampEnd - timestampStart) testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'failed', 'message': str(e), 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': taskDuration, 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': 0, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd) } print(str(e)) fileUrl = 'http://' + rfbNode + '/uploadFile/' + fileName + '/' + testId + '/' + str( HOST_PORT) async with ClientSession() as session: try: timestampStart = datetime.utcnow() async with ClientSession() as session: async with session.post( fileUrl, data={ 'testId': testId, 'fileName': fileName, 'file': download_files[fileName] }) as response: data = await response.json() fileSize = len(download_files[fileName]) timestampEnd = datetime.utcnow() taskDuration = str(timestampEnd - timestampStart) if data: testResults.setdefault( testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['uploadFile'] = { 'status': 'success', 'message': 'File uploaded', 'testId': testId, 'usedHandler': 'uploadFile', 'taskDuration': taskDuration, 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd) } except Exception as e: timestampEnd = datetime.utcnow() taskDuration = str(timestampEnd - timestampStart) testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['uploadFile'] = { 'status': 'failed', 'message': str(e), 'testId': testId, 'usedHandler': 'uploadFile', 'taskDuration': taskDuration, 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': 0, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd) } print(str(e)) async with ClientSession() as session: for gateway in set(rfbGateways): gatewayUrl = 'http://' + str(gateway) + '/shareResults' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'testResults': json.dumps(testResults), 'testConfirmations': json.dumps(testConfirmations) } try: async with session.post( gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() responseStatus = responseData['status'] responseMessage = responseData['message'] except Exception as e: print(str(e))
async def ShareResultsAPIHandler(request): """ POST handler ... """ try: data = await request.post() peername = request.transport.get_extra_info('peername') if peername is not None: host, port = peername testNode = data['nodeAddress'] nodePort = data['nodePort'] nodeToken = data['nodeToken'] testConfirmationsNew = json.loads(data['testConfirmations']) testResultsNew = json.loads(data['testResults']) CURRENT_HEIGHT = int(pw.height()) print(host) print(testNode) print(nodeToken) print(rfbNodes.get(testNode + ':' + nodePort)['nodeToken']) print(testConfirmationsNew) print(testResultsNew) print('---') if host == testNode and nodeToken == rfbNodes.get( testNode + ':' + nodePort)['nodeToken']: for test in testResultsNew: if int(test) >= CURRENT_HEIGHT - 10: #print(test) for node in testResultsNew[test]: #print(node) for nodeA in testResultsNew[test][node]: #print(nodeA) for usedHandler in testResultsNew[test][node][ nodeA]: if nodeA == testNode + ':' + nodePort: #print('setting test results') testResults.setdefault( test, {}).setdefault(node, {}).setdefault( nodeA, {})[usedHandler] = testResultsNew[ test][node][nodeA][usedHandler] pickle.dump( testResults, open("testResults.pickle", "wb")) #print(testResults) else: print( 'He shall not try to load some of these tests results: ' + testResultsNew[test]) for test in testConfirmationsNew: if int(test) >= CURRENT_HEIGHT - 10: #print(test) for node in testConfirmationsNew[test]: #print(node) for nodeA in testConfirmationsNew[test][node]: #print(nodeA) for usedHandler in testConfirmationsNew[test][ node][nodeA]: if node == testNode + ':' + nodePort: testResults.setdefault( test, {}).setdefault(node, {}).setdefault( nodeA, {} )[usedHandler] = testConfirmationsNew[ test][node][nodeA][usedHandler] pickle.dump( testResults, open("testResults.pickle", "wb")) #print(testResults) else: print( 'He shall not try to confirm some of these tests results: ' + testConfirmationsNew[test]) #print(testResults) print('---') response_obj = {'status': 'success', 'message': 'Thanks for sharing'} return web.json_response(response_obj) except Exception as e: response_obj = {'status': 'failed', 'message': str(e)} return web.json_response(response_obj)
async def register_ip(): """ This function: - checks which RFBGateways to connect to: 1) checks list of burn transactions. 2) checks currennt balance for accounts that did those burns. 3) checks (for acounts with minimum balance) for data transactions with key:value where key: RFBGateway_address and value: hostname:port. 4) creates rfbGateways python list - connects to each gateway and fetches the list of RFBNodes - runs tests to all RFBNodes (one by one) - shares test results with gateways from rfbGateways list """ async with ClientSession() as session: checkBurnUrl = DATA_API_URL + 'transactions/burn?sort=desc&limit=100&assetId=' + RFBT_ADDRESS try: async with session.get(checkBurnUrl) as response: httpStatus = response.status checkBurnResponseData = await response.json() burnTransactions = [] burnSenders = [] rfbGateways.clear() for i in range(0, len(checkBurnResponseData['data'])): burnTransactions.append({ 'sender': checkBurnResponseData['data'][i]['data']['sender'], 'amount': checkBurnResponseData['data'][i]['data']['amount'], 'id': checkBurnResponseData['data'][i]['data']['id'] }) burnSenders.append( checkBurnResponseData['data'][i]['data']['sender']) for sender in set(burnSenders): myAddress = pw.Address(sender) if myAddress.balance(RFBT_ADDRESS) > 100000000: checkDataUrl = DATA_API_URL + 'transactions/data?sender=' + sender + '&key=RFBGateway_address&sort=desc&limit=100' try: async with session.get(checkDataUrl) as response: httpStatus = response.status checkDataResponseData = await response.json() rfbGateways.append( checkDataResponseData['data'][0]['data'] ['data'][0]['value']) except Exception as e: print(e) except Exception as e: print(e) rfbNodes_temp2 = [] rfbNodes_temp = [] for gateway in set(rfbGateways): gatewayUrl = 'https://' + str(gateway) + '/checkAPI' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'nodeWallet': ACCOUNT_ADDRESS } try: async with session.post(gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() responseStatus = responseData['status'] responseMessage = responseData['message'] if responseStatus == "success": rfbNodes_temp.append(responseData['rfbNodes']) NEW_NODE_ADDRESS = get('https://api.ipify.org').text if NEW_NODE_ADDRESS != NODE_ADDRESS[ 0] or responseStatus != "success": NODE_ADDRESS[0] = NEW_NODE_ADDRESS gatewayUrl = 'https://' + str(gateway) + '/registerAPI' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'nodeWallet': ACCOUNT_ADDRESS } async with session.post(gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() responseStatus = responseData['status'] responseMessage = responseData['message'] rfbNodes_temp.append(responseData['rfbNodes']) print(responseMessage) except Exception as e: print(e) if rfbNodes_temp: for node in rfbNodes_temp[0]: rfbNodes_temp2.append(node) rfbNodes = set(rfbNodes_temp2) if len(rfbNodes) >= 2: rfbNodes.remove(NODE_ADDRESS[0] + ':' + str(HOST_PORT)) fileName = "100k.txt" for rfbNode in rfbNodes: CURRENT_HEIGHT = str(pw.height()) testId = CURRENT_HEIGHT asyncio.ensure_future(cleanTestResults(testId)) fileUrl = 'http://' + rfbNode + '/downloadFile/' + fileName + '/' + testId + '/' + str( HOST_PORT) async with ClientSession() as session: try: fileSize = 0 timestampStart = datetime.utcnow() async with session.get(fileUrl) as response: async for data in response.content.iter_chunked( 1024): fileSize += len(data) timestampEnd = datetime.utcnow() taskDuration = timestampEnd - timestampStart if fileSize > 0: testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'success', 'message': 'File downloaded', 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': str(taskDuration), 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd), 'speed': str(fileSize / taskDuration.total_seconds()) } else: testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'failed', 'message': 'Empty file downloaded', 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': str(taskDuration), 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd), 'speed': '0' } except Exception as e: timestampEnd = datetime.utcnow() taskDuration = timestampEnd - timestampStart testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['downloadFile'] = { 'status': 'failed', 'message': str(e), 'testId': testId, 'usedHandler': 'downloadFile', 'taskDuration': str(taskDuration), 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': 0, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd), 'speed': '0' } #print(str(e)) fileUrl = 'http://' + rfbNode + '/uploadFile/' + fileName + '/' + testId + '/' + str( HOST_PORT) async with ClientSession() as session: try: timestampStart = datetime.utcnow() async with ClientSession() as session: async with session.post( fileUrl, data={ 'testId': testId, 'fileName': fileName, 'file': download_files[fileName] }) as response: data = await response.json() fileSize = len(download_files[fileName]) timestampEnd = datetime.utcnow() taskDuration = timestampEnd - timestampStart if data: testResults.setdefault( testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['uploadFile'] = { 'status': 'success', 'message': 'File uploaded', 'testId': testId, 'usedHandler': 'uploadFile', 'taskDuration': str(taskDuration), 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': fileSize, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd), 'speed': str(fileSize / taskDuration. total_seconds()) } except Exception as e: timestampEnd = datetime.utcnow() taskDuration = timestampEnd - timestampStart testResults.setdefault(testId, {}).setdefault( rfbNode, {}).setdefault( NODE_ADDRESS[0] + ':' + str(HOST_PORT), {})['uploadFile'] = { 'status': 'failed', 'message': str(e), 'testId': testId, 'usedHandler': 'uploadFile', 'taskDuration': str(taskDuration), 'fileName': fileName, 'sourceFileName': fileName, 'fileSize': 0, 'timestampStart': str(timestampStart), 'timestampEnd': str(timestampEnd), 'speed': '0' } #print(str(e)) async with ClientSession() as session: for gateway in set(rfbGateways): gatewayUrl = 'https://' + str( gateway) + '/shareResults' parameters = { 'nodeAddress': NODE_ADDRESS[0], 'nodePort': str(HOST_PORT), 'nodeToken': nodeToken, 'testResults': json.dumps(testResults), 'testConfirmations': json.dumps(testConfirmations) } try: async with session.post( gatewayUrl, data=parameters) as response: httpStatus = response.status responseData = await response.json() responseStatus = responseData['status'] responseMessage = responseData['message'] except Exception as e: print(str(e))
py.Address( seed= 'bean tool all make clap disagree food buyer forward toy find miracle sick sauce slide' )) wallets.append( py.Address( seed= 'fresh return verb source radio response broom space appear way energy owner polar electric lock' )) initialiseWallets() #print(wallets) height = py.height() value = 25 * math.pow(10, 8) myAddress.sendAsset(recipient=wallets[0], asset=token, amount=value) while True: currentHeight = py.height() if (currentHeight == (height + 1)): height += 1 print("----------------------") print(height) for i in range(0, 10): walletAddress = wallets[i] myAddress.sendAsset(recipient=walletAddress,