-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncParser.py
More file actions
79 lines (65 loc) · 2.03 KB
/
Copy pathasyncParser.py
File metadata and controls
79 lines (65 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import asyncio
from Crypto.Hash import keccak
import time
def getHash(stringToHash):
return keccak.new(
digest_bits=256,
data=stringToHash.encode('utf-8')
).hexdigest()
async def getBlockHeader(blocknumber):
await asyncio.sleep(0.1)
return {
'blocknumber': blocknumber,
'blockhash': getHash(str(blocknumber)),
'transactions': [
getHash(str(blocknumber)+str(num)) for num in range(10)
]
}
async def getTransactionReceipt(txHash):
# Returns fake transaction receipt
await asyncio.sleep(0.1)
return getHash(txHash)
async def parseBlocks(blocksToFetch):
''' Fetches batch of block headers and transaction receipts.
Return data in the following format:
[
[
blockheader,
txReceiptDict: {
txHash: data,
...
}
],
...
]
'''
# Complete this function
blockData = []
txReceiptDict = {}
for blockNumber in blocksToFetch:
blockData.append([])
blockHeader = await getBlockHeader(blockNumber)
blockData[blockNumber].append(blockHeader)
for transaction in blockHeader["transactions"]:
txReceiptDict[transaction] = await getTransactionReceipt(transaction)
blockData[blockNumber].append(txReceiptDict)
print(blockData)
return blockData
def main():
loop = asyncio.get_event_loop()
blocksToFetch = range(5)
# Fetch blocks and transaction receipts
startTime = time.time()
blockData = loop.run_until_complete(parseBlocks(blocksToFetch))
# Test results
assert len(blockData) == 5
for block in blockData:
assert block[0]['blockhash'] == getHash(str(block[0]['blocknumber']))
assert len(block[0]['transactions']) == 10
assert isinstance(block[1], dict)
for txHash in block[1]:
assert block[1][txHash] == getHash(txHash)
print('Passed!')
print(time.time() - startTime)
if __name__ == "__main__":
main()