责编 | Carol
出品 | 区块链大本营(ID:blockchain_camp)
前几天,作者碰着了这样一种情形,须要在一个让web3.py险些不可能事情的环境中利用Python与Ethereum网络进行通信。

由于作者仍旧须要与网络通信,以是作者利用了Ethereum供应的JSON-RPC API,所有的web3库都构建在这个API之上。原来,这是非常有趣的一件事,让我们一起来看看吧。
根本设置
首先,让我们声明几个变量,这将有助于往后发送要求:
import requestsimport jsonsession = requests.Sessionurl = \"大众https://ropsten.infura.io/v3/YOUR_INFURA_KEY\"大众headers = {'Content-type': 'application/json'}
为了大略起见,我们利用Infura节点连接到Ethereum Ropsten Testnet。你可以在这里得到一个API 密钥:https://infura.io/。
你的第一个要求
让我们先来理解一下网络当前的gas价格。我们可以大略地做以下操作:
# Prepare the data we will senddata = {\"大众jsonrpc\"大众: \"大众2.0\"大众, \"大众method\公众: \"大众eth_gasPrice\公众, \"大众params\"大众: , \公众id\公众:1}response = session.post(url, json=data, headers=headers)# Check if response is validif response.ok:# Get result of the request and decode it to decimalgasPriceHex = response.json.get(\"大众result\公众)gasPriceDecimal = int(gasPriceHex, 16)else:# Handle Errorprint(\"大众Error occured\"大众)
我们怎么知道利用哪种方法以及发送什么参数呢?所有这些都可以在以太坊官方文档中找到。
获取最新的块
让我们来考试测验一些更有趣的东西——让我们获取最新的块,看看我们可以从那里读取什么?
# Set params and prepare datablockNumber = \"大众latest\"大众# Boolean indicating if we want the full transactions (True) or just their hashes (false)fullTrx = Falseparams = [ blockNumber, fullTrx]data = {\公众jsonrpc\"大众: \"大众2.0\"大众, \"大众method\公众: \"大众eth_getBlockByNumber\"大众,\"大众params\公众: params, \"大众id\"大众: 1}response = session.post(url, json=data, headers=headers)# Check if response is validif response.ok:# Get the blockblock = response.json.get(\"大众result\"大众)# Get the transactions contained in the blocktransactions = block.get(\"大众transactions\公众)else:# Handle Erro
让我们仔细看看个中一笔交易:
params = [transactions[0]]data = {\"大众jsonrpc\"大众: \公众2.0\"大众, \"大众method\公众: \"大众eth_getTransactionByHash\公众,\"大众params\"大众: params, \公众id\公众: 3}response = session.post(url, json=data, headers=headers)if response.ok:transaction = response.json.get(\"大众result\"大众)else:# Handle Errorprint(\公众Error occured
可能你已经开始理解这些调用的事情模式,以是让我们考试测验一些更高等的方法。
发送交易
首先,让我们利用web3.py库创建一个新帐户,并向个中加载一些Ropsten ether。
import web3w3 = web3.Web3account = w3.eth.account.create('put any phrase here')address = account.addresspKey = account.privateKey
要发送创建交易,我们须要随机数。我们也可以利用与上述相同的模式通过RPC JSON API获取信息:
# Get the nonce at the latest blockparams = [address, \"大众latest\公众]data = {\"大众jsonrpc\公众: \"大众2.0\"大众, \"大众method\公众: \"大众eth_getTransactionCount\"大众,\"大众params\"大众: params, \公众id\公众: 3}response = session.post(url, json=data, headers=headers)if response.ok:nonce = response.json.get(\公众result\公众)else:# Handle Errorprint(\公众Error occured\"大众)
接下来,我们将创建并署名交易,然后再次利用 JSON RPC API 将其发送出去:
# Create our transactionsigned_txn = w3.eth.account.signTransaction({# Faucet address'to': '0x687422eEA2cB73B5d3e242bA5456b782919AFc85','nonce': nonce,'gasPrice': gasPriceHex,'gas': 100000,'value': w3.toWei(0.5,'ether'),# 3 Because we are on Ropsten'chainId':3,},pKey)
如果你要在其他以太坊(Test)网络上进行测试,请确保相应地设置链ID。
params = [signed_txn.rawTransaction.hex()]data = {\公众jsonrpc\"大众: \"大众2.0\"大众, \"大众method\"大众: \"大众eth_sendRawTransaction\公众,\"大众params\"大众: params, \"大众id\公众: 4}response = session.post(url, json=data, headers=headers)if response.ok:receipt = response.json.get(\公众result\"大众)else:# Handle Errorprint(\公众Error occured\"大众)
请把稳我们是如何重新利用开始时获取的汽油价格的。
结论
就这样大略,你刚刚利用5分钟学习了利用JSON RPC Ethereum API与天下上最具影响力的区块链进行交互的根本知识!
你可以在这里找到所有代码:https://github.com/nschapeler/ethereum-rpcjson。
原文:https://hackernoon.com/learn-the-basics-of-the-ethereum-json-api-in-5-minutes-7k3x3yn0
☞“谷歌杀手”发明者,科学天才 Wolfram
☞漫画:“哈夫曼编码” 是什么鬼?
☞数据库激荡40年,深入解析PostgreSQL、NewSQL演进进程
☞黑客用上机器学习你慌不慌?这7种盗取数据的新手段快来认识一下!
☞超详细!
一文见告你SparkStreaming如何整合Kafka!
附代码可实践
☞Libra的Move措辞初探,10行代码实现你第一个智能合约