Added last scanned block detail to getSystemData API endpoint

This commit is contained in:
Vivek Teega 2020-09-08 03:14:36 +00:00
parent e160134adc
commit 5b6b93ab76

View File

@ -56,6 +56,39 @@ def multiRequest(apicall, net):
return retryRequest(testserverlist, apicall) return retryRequest(testserverlist, apicall)
def blockdetailhelper(blockdetail):
if blockdetail.isdigit():
blockHash = None
blockHeight = int(blockdetail)
else:
blockHash = str(blockdetail)
blockHeight = None
# open the latest block database
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
if blockHash:
c.execute(
f"select jsonData from latestBlocks where blockHash='{blockHash}'")
elif blockHeight:
c.execute(
f"select jsonData from latestBlocks where blockNumber='{blockHeight}'")
blockJson = c.fetchall()
return blockJson
def transactiondetailhelper(transactionHash):
# open the latest block database
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
c.execute(
f"select jsonData,parsedFloData from latestTransactions where transactionHash='{transactionHash}'")
transactionJsonData = c.fetchall()
return transactionJsonData
# FLO TOKEN APIs # FLO TOKEN APIs
@app.route('/api/v1.0/getTokenList', methods=['GET']) @app.route('/api/v1.0/getTokenList', methods=['GET'])
@ -104,7 +137,7 @@ async def getTokenInfo():
associatedContractList.append(tempdict) associatedContractList.append(tempdict)
return jsonify(result='ok', token=token, incorporationAddress=incorporationRow[1], tokenSupply=incorporationRow[3], return jsonify(result='ok', token=token, incorporationAddress=incorporationRow[1], tokenSupply=incorporationRow[3],
transactionHash=incorporationRow[6], blockchainReference=incorporationRow[7], time=incorporationRow[6], blockchainReference=incorporationRow[7],
activeAddress_no=numberOf_distinctAddresses, totalTransactions=numberOf_transactions, associatedSmartContracts=associatedContractList) activeAddress_no=numberOf_distinctAddresses, totalTransactions=numberOf_transactions, associatedSmartContracts=associatedContractList)
@ -800,25 +833,7 @@ async def getsmartcontracttransactions():
@app.route('/api/v1.0/getBlockDetails/<blockdetail>', methods=['GET']) @app.route('/api/v1.0/getBlockDetails/<blockdetail>', methods=['GET'])
async def getblockdetails(blockdetail): async def getblockdetails(blockdetail):
if blockdetail.isdigit(): blockJson = blockdetailhelper(blockdetail)
blockHash = None
blockHeight = int(blockdetail)
else:
blockHash = str(blockdetail)
blockHeight = None
# open the latest block database
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
if blockHash:
c.execute(
f"select jsonData from latestBlocks where blockHash='{blockHash}'")
elif blockHeight:
c.execute(
f"select jsonData from latestBlocks where blockNumber='{blockHeight}'")
blockJson = c.fetchall()
if len(blockJson) != 0: if len(blockJson) != 0:
blockJson = json.loads(blockJson[0][0]) blockJson = json.loads(blockJson[0][0])
return jsonify(result='ok', blockDetails=blockJson) return jsonify(result='ok', blockDetails=blockJson)
@ -829,13 +844,7 @@ async def getblockdetails(blockdetail):
@app.route('/api/v1.0/getTransactionDetails/<transactionHash>', methods=['GET']) @app.route('/api/v1.0/getTransactionDetails/<transactionHash>', methods=['GET'])
async def gettransactiondetails(transactionHash): async def gettransactiondetails(transactionHash):
# open the latest block database transactionJsonData = transactiondetailhelper(transactionHash)
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
c.execute(
f"select jsonData,parsedFloData from latestTransactions where transactionHash='{transactionHash}'")
transactionJsonData = c.fetchall()
if len(transactionJsonData) != 0: if len(transactionJsonData) != 0:
transactionJson = json.loads(transactionJsonData[0][0]) transactionJson = json.loads(transactionJsonData[0][0])
@ -916,6 +925,26 @@ async def getLatestBlockDetails():
return jsonify(result='ok', latestBlocks=tempdict) return jsonify(result='ok', latestBlocks=tempdict)
@app.route('/api/v1.0/getBlockTransactions/<blockdetail>', methods=['GET'])
async def getblocktransactions(blockdetail):
blockJson = blockdetailhelper(blockdetail)
if len(blockJson) != 0:
blockJson = json.loads(blockJson[0][0])
blocktxlist = blockJson['tx']
blocktxs = {}
for i in range(len(blocktxlist)):
temptx = transactiondetailhelper(blocktxlist[i])
transactionJson = json.loads(temptx[0][0])
parseResult = json.loads(temptx[0][1])
blocktxs[blocktxlist[i]] = {
"parsedFloData" : parseResult,
"transactionDetails" : transactionJson
}
return jsonify(result='ok', transactions=blocktxs, blockKeyword=blockdetail)
else:
return jsonify(result='error', description='Block doesn\'t exist in database')
@app.route('/api/v1.0/categoriseString/<urlstring>') @app.route('/api/v1.0/categoriseString/<urlstring>')
async def categoriseString(urlstring): async def categoriseString(urlstring):
@ -998,6 +1027,7 @@ async def systemData():
'select count(distinct token) from tokenAddressMapping').fetchall()[0][0] 'select count(distinct token) from tokenAddressMapping').fetchall()[0][0]
contractCount = c.execute( contractCount = c.execute(
'select count(distinct contractName) from contractAddressMapping').fetchall()[0][0] 'select count(distinct contractName) from contractAddressMapping').fetchall()[0][0]
lastscannedblock = int(c.execute("select value from systemData where attribute=='lastblockscanned'").fetchall()[0][0])
conn.close() conn.close()
# query for total number of validated blocks # query for total number of validated blocks
@ -1009,7 +1039,7 @@ async def systemData():
'select count(distinct transactionHash) from latestTransactions').fetchall()[0][0] 'select count(distinct transactionHash) from latestTransactions').fetchall()[0][0]
conn.close() conn.close()
return jsonify(systemAddressCount=tokenAddressCount, systemBlockCount=validatedBlockCount, systemTransactionCount=validatedTransactionCount, systemSmartContractCount=contractCount, systemTokenCount=tokenCount, result='ok') return jsonify(systemAddressCount=tokenAddressCount, systemBlockCount=validatedBlockCount, systemTransactionCount=validatedTransactionCount, systemSmartContractCount=contractCount, systemTokenCount=tokenCount, lastscannedblock=lastscannedblock, result='ok')
@app.route('/test') @app.route('/test')
@ -1100,8 +1130,9 @@ async def getPriceData():
return jsonify(prices=prices, result='ok') return jsonify(prices=prices, result='ok')
''' Stuff required for getPrices endpoint ''' ''' Stuff required for getPrices endpoint '''
def updatePrices(): def updatePrices():
prices = {} prices = {}
@ -1127,7 +1158,6 @@ def updatePrices():
# todo : add logger to the application # todo : add logger to the application
print('USD to Fiat APIs arent responding') print('USD to Fiat APIs arent responding')
# Blockchain stuff : BTC,FLO -> USD,INR # Blockchain stuff : BTC,FLO -> USD,INR
response = requests.get( response = requests.get(
f"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,flo&vs_currencies=usd,inr") f"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,flo&vs_currencies=usd,inr")
@ -1158,14 +1188,15 @@ def updatePrices():
price1 = response1.json() price1 = response1.json()
price2 = response2.json() price2 = response2.json()
prices['BTCUSD'] = price1['quotes']['usd']['price'] prices['BTCUSD'] = price1['quotes']['usd']['price']
prices['BTCINR'] = price1['quotes']['usd']['price'] * prices['USDINR'] prices['BTCINR'] = price1['quotes']['usd']['price'] * \
prices['USDINR']
prices['FLOUSD'] = price2['quotes']['usd']['price'] prices['FLOUSD'] = price2['quotes']['usd']['price']
prices['FLOINR'] = price2['quotes']['usd']['price'] * prices['USDINR'] prices['FLOINR'] = price2['quotes']['usd']['price'] * \
prices['USDINR']
except ValueError: except ValueError:
# todo : add logger to the application # todo : add logger to the application
print('Blockchain to Fiat APIs arent responding') print('Blockchain to Fiat APIs arent responding')
# 3. update latest price data # 3. update latest price data
print('Prices updated at time: %s' % datetime.now()) print('Prices updated at time: %s' % datetime.now())
print(prices) print(prices)
@ -1174,9 +1205,11 @@ def updatePrices():
c = conn.cursor() c = conn.cursor()
for pair in list(prices.items()): for pair in list(prices.items()):
pair = list(pair) pair = list(pair)
c.execute(f"UPDATE ratepairs SET price={pair[1]} WHERE ratepair='{pair[0]}'") c.execute(
f"UPDATE ratepairs SET price={pair[1]} WHERE ratepair='{pair[0]}'")
conn.commit() conn.commit()
# if system.db isn't present, initialize it # if system.db isn't present, initialize it
if not os.path.isfile(f"system.db"): if not os.path.isfile(f"system.db"):
# create an empty db # create an empty db