c++以太坊访问:eth api接口调用(一)

最近接触到以太坊智能合约,在私有链上部署合约后,通过代码去调用合约方法,没有在网上找到c++对以太坊的调用库,发现java有以太坊相关的模块库web3j

(web3j是一个轻量级、高度模块化、反应式、类型安全的Java和Android库,用于处理智能合约和与以太坊网络上的客户端(节点)集成)。

自己尝试进行对web3j进行类似的封装,初步对eth的 json rpc api接口进行访问;

Infura开发手册 :http://cw.hubwiz.com/card/c/infura-api/1/2/3/  

现阶段目前使用c++  lincurl库对其进行部分接口访问,代码如下:

string Web3j::eth_getBalance(string fromAddr)
{
	string retstr ="";
	//封装发送的数据
	Json::Value object;
	Json::Value arr;
	arr.append(fromAddr);
	arr.append("latest");
	object["jsonrpc"] = "2.0";
	object["method"] = "eth_getBalance";
	object["params"] = arr;
	object["id"] = 1;
	string strpost = object.toStyledString();

	CURLcode res;
	//初始化一个CURL的指针
	CURL *hnd = curl_easy_init();
	if (!hnd)
		return "curl init failed!";
	//自定义请求
	curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");

	struct MemoryStruct chunk;
	chunk.memory = (char*)malloc(1);
	chunk.size = 0;

	//请求头设置
	struct curl_slist *header = NULL;
	header = curl_slist_append(header, "Content-Type: application/json");
	curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, header);
	//设置访问URl
	curl_easy_setopt(hnd, CURLOPT_URL, m_sUrl.c_str());
	//设置发送超时时间
	curl_easy_setopt(hnd, CURLOPT_CONNECTTIMEOUT, 30);
	curl_easy_setopt(hnd, CURLOPT_TIMEOUT, 60);
	curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, OnWriteData);
	curl_easy_setopt(hnd, CURLOPT_WRITEDATA, (void *)&chunk);
	//请求参数
	curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, strpost.c_str());
	curl_easy_setopt(hnd, CURLOPT_POST, 1);
	curl_easy_setopt(hnd, CURLOPT_READFUNCTION, NULL);
	//打印调试信息
	curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1);

	res = curl_easy_perform(hnd);
	long info = 0;
	curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &info);
	if (res != CURLE_OK || info != 200)
	{
		cout << "curl failed to perform " << res << " " << info;
	}
	else
	{
		//json字符串转为json对象解析
		Json::CharReaderBuilder b;
		Json::CharReader* reader(b.newCharReader());
		Json::Value value;
		JSONCPP_STRING err;
		bool ok = reader->parse(chunk.memory, chunk.memory + chunk.size, &value, &err);
		if (ok && err.size() == 0)
		{
			retstr = value["result"].asString();
		}
		else
			cout << "eth_getBalance return value parse failed!" << endl;
		delete reader;
	}
	//释放
	curl_slist_free_all(header);
    curl_easy_cleanup(hnd);
	return retstr;
}

初步实现对账户余额(eth_getBalance)接口的访问,来源分析根据下图:

其他接口类似的用法,主要通过libcurl库对http的访问,以及json库对数据的封装。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值