很多时候需要实现地址监控,例如钱包充值后需要及时通知用户,那怎么来实现呢?
因为对一块没具体了解过,初步想有两种方法:
ethereum有rpc函数eth_getBlockByNumber,是不是这个能达到要求呢?
大概思路:
监控服务第一次启动,从以太坊上取最新块数据
解析新块上是否有监控地址的交易,有则通知,处理完成保存块号到本地
继续取下一块数据,并执行2,只到最新块取完,进行延时
取最新块号,不等于保存的最新块号则取新块数据,执行2
用python简单写个http调用试试,返回错误
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 415: Unsupported Media Type
不支持类型,官方有个说明没注意看
The curl options below might return a response where the node complains about the content type, this is because the --data option sets the content type to application/x-www-form-urlencoded .
If your node does complain, manually set the header by placing -H "Content-Type: application/json" at the start of the call.
在HTTP头里加上
{"Content-type":"application/json"}
再次调用,正确返回数据了!
POST:http://localhost:8545,data:{"jsonrpc":"2.0","method":"eth_mining","params":[],"id":71}
{"jsonrpc":"2.0","id":71,"result":false}
主要就是通过eth_getBlockByNumber和eth_blockNumber这两个接口循环监控是否有新块,有新块再解析新块数据了!
def run(self):
while True:
r = self.eth_blockNumber()
d = json.loads(r)
if d.has_key("result"):
lastBlockNo = d["result"]
if lastBlockNo != self.lastBlockNo:
print("New block no: " + lastBlockNo)
r = self.eth_getBlockByNumber(lastBlockNo)
d = json.loads(r)
print(d)
self.lastBlockNo = lastBlockNo
else:
print("eth_blockNumber fail!")
time.sleep(1)
可能还能用eth_newBlockFilter之类方法直接监控到新块,但是这些方法都需要以太坊节点打开RPC功能,web3接口同样需要,而打开RPC又可能引起安全问题,如果用这种方法,除了限制IP和端口外,这个节点的机器就千万不要用钱包了!
是不是可以用以太坊钱包的方式去取节点数据呢?
用这个应该更简单,不用自己HTTP调用了
https://github.com/ethereum/wiki/wiki/JavaScript-API
>最后更新日期2016年,算了
https://pypi.python.org/pypi/web3/3.2.0
以太坊官网上有一个web3py库,http://web3py.readthedocs.io/
parity有个tarce_filter方法,可以指定区块范围查找地址
https://github.com/paritytech/parity/wiki/JSONRPC-trace-module#trace_filter
https://github.com/paritytech/parity/wiki/JSONRPC-Parity-Pub-Sub-module
Ethereum Frontier Guide
https://ethereum.gitbooks.io/frontier-guide/content/rpc.html
RPC安全
https://isc.sans.edu/forums/diary/Internet+Wide+Ethereum+JSONRPC+Scans/23061/
https://daowiki.atlassian.net/wiki/spaces/DAO/pages/4489244/Ethereum+wallet+getting+hacked
https://ethereum.stackexchange.com/questions/3887/how-to-reduce-the-chances-of-your-ethereum-wallet-getting-hacked
感谢您阅读 @chaimyu 的帖子,期待您能留言交流!