美文网首页前端&优化
以太坊钱包的开发3 -- 编写API

以太坊钱包的开发3 -- 编写API

作者: iRonCheng | 来源:发表于2018-07-04 17:59 被阅读252次

以太坊钱包的开发1以太坊钱包的开发2 中,我们用NodeJs搭了个以太坊钱包的后台,实现了查询余额、转账、查看交易等的功能,现在介绍用NodeJs写接口给移动端或者前端使用。

前面搭建本地或者远程服务器的区块链节点后,我们还安装了NodeJs环境。

  // 创建wallet文件夹,进入
  cd  wallet

  //初始化node模块, 并填写相关信息
  npm  init     
  
  //  安装eth包  
  npm install ethereumjs-tx --save

  //  安装express模块 
  npm install express --save

express 是基于NodeJs的一种简单使用的Web框架


代码如下:

var express = require('express');
//实例化express类
var app = express();
var bodyParser = require('body-parser');

var Web3 = require('web3');
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    console.log('~defined~:'+web3);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    var version = web3.version.api;
    console.log(version);
}


/* Post方法
 *         url:  yourHost/transaction   
 *       param:  
 *             to             目标地址
 *             value          转账的数额
 *             privateKey     自己的私钥,可与客户端规定好,使用一些加密方法
 */
app.post("/transaction", function (req, res) {
    if (req.body.to && req.body.value && req.body.privateKey) {
        /* 获取公钥 */
        var publicKey = catchPublicFromPrivate(req.body.privateKey);
        var nonceNumber = web3.eth.getTransactionCount(publicKey);
        // nonceNumber++;
        console.log('nonceNumber:'+nonceNumber);
        try {
            sendMyTransaction(req.body.to, req.body.privateKey, req.body.value, nonceNumber, function (error, hash) {
                if (!error) {
                    res.status(200);
                    res.json({status:1 ,msg:'请求成功' , result:{hash:hash}});
                }
                else {
                    res.status(500);
                    res.json({status:0 ,msg:'请求失败:'+error , result:''});
                }
            });
        } catch (e) {
            console.log('yichang');
            res.status(500);
            res.json({status:0 ,msg:'请求失败:' + e , result:''});
        }
    } else {
        res.status(202);
        res.json({status:0 ,msg:'参数错误', result:''});
        return;
    }
});

/* 
 * 开启监听3000端口 ,这样你的接口才有效
 */
app.listen(3000, function(){
    console.log("App started on port 3000");
});

tips: 编写NodeJs的get方法与此类似:app.get("/abc/aaa",function( request, response){ // to do });

内部封装的方法实现:

/*
 *              ---- ---- ---- Common Method ---- ---- ----
 * */

/*
 *  从私钥获取公钥(解密的过程)  具体实现从官网获得
 *  */
function catchPublicFromPrivate (privateKey) {
    var secp256k1 = require('secp256k1') ;
    var SHA3 = require('keccakjs');
    var privateKeyBuffer = new Buffer(privateKey, 'hex');
    var publicKey = secp256k1.publicKeyCreate(privateKeyBuffer, false).slice(1);
    var h = new SHA3(256);
    h.update(publicKey);
    var hh = h.digest('hex').slice(-40);
    return '0x'+hh;
}


/*
 *   封装的交易方法
 * */
function sendMyTransaction (to, privateKey, value, nonce, callback) {
    var Tx = require('ethereumjs-tx');
    var privateKey = new Buffer(privateKey, 'hex');

    var rawTx = {
        nonce: nonce,
        gasPrice: '0x3b9aca00',
        gasLimit: '0x493e0',
        to: to,
        value: value,
        data: ''
    };
    var tx = new Tx(rawTx);
    tx.sign(privateKey);

    var serializedTx = tx.serialize();
    web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
        console.log('交易结果:'+hash);
        if (callback && typeof(callback) === "function") {
            if (!err)
                callback(null, hash);
            else
                callback(err, null);
        }
    });
}


至此,在客户端就可以用接口实现转账的功能了。

相关文章

网友评论

    本文标题:以太坊钱包的开发3 -- 编写API

    本文链接:https://www.haomeiwen.com/subject/ymqyuftx.html