Querying Blockchain Data
Desliza para mostrar el menú
g with blockchains, applications often need to query data about blocks, transactions, and account balances. This information is essential for analytics dashboards, monitoring blockchain activity, and decentralized applications.
Using Python, you can connect to a blockchain node through RPC endpoints and request this data. The node returns JSON responses containing details such as block information, transaction data, and account balances.
import requests
# Replace with your node's RPC URL
rpc_url = "http://localhost:8545"
payload = {
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["latest", True],
"id": 1
}
response = requests.post(rpc_url, json=payload)
latest_block = response.json()["result"]
print("Block Number:", latest_block["number"])
print("Block Hash:", latest_block["hash"])
print("Timestamp:", latest_block["timestamp"])
print("Number of Transactions:", len(latest_block["transactions"]))
When you query blockchain nodes, they typically respond with data in JSON format. JSON responses are structured as nested dictionaries and lists in Python, making it straightforward to access specific fields. For example, a block's JSON object contains keys such as "number", "hash", "timestamp", and "transactions". Each transaction within the block is itself a JSON object with its own set of fields. By navigating these structures in Python, you can extract exactly the information you need for further processing or display.
# Assume latest_block is already obtained
print("Transaction Hashes in the Latest Block:")
for tx in latest_block["transactions"]:
print(tx["hash"])
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla