web3的shh使用

web3-shh包用来使用whisper协议进行广播发送。

我在node-js开发中想调用ssh生成一对公钥和私钥,但是报了以下错误:

web3.js: Error: The method shh_newSymKey does not exist/is not available on Web3.js

不管怎么调,方法总是调用不了,百度以后发现没有解答,然后果断Google,终于找到答案,在这里总结。

1.升级web3版本,我之前用的是Web3.js 0.20.x,现在已经到了1.2.7,在0.20.x版本虽然有shh接口,但是没有关于公钥和私钥的接口,要想使用需要升级到1.0以上版本,我采用了1.0.0-beta.34,进入工程目录,使用以下命令安装:

npm install web3@1.0.0-beta.34

2、启动私链节点时要添加 --shh 和 --rpcapi "eth,net,web3,personal,shh"

geth --rpc --rpcport 8545 --rpcaddr="0.0.0.0" --rpccorsdomain="*" --nodiscover --maxpeers '15' --networkid '11' --datadir './chain' --rpcapi "eth,net,web3,personal,shh" --shh

3、web3 1.0中一些接口发生了变化,比如

if(!await web3.isConnected()){ //await web3@0.20.5
//if(!await web3.eth.net.isListening()){ //await web3@1.0.0-beta.34
    console.log("notconnected");
    process.exit();
}

报错完美解决!

但是又出了第二个报错

Error: invalid argument 0: json: cannot unmarshal object into Go value of type string

这是因为web3 1.0以后接口都需要回调函数,异步执行,所以需要改成:

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));     

async function connect() { //note async function declaration
    if(!await web3.isConnected()){ //await web3@0.20.5
    //if(!await web3.eth.net.isListening()){ //await web3@1.0.0-beta.34
        console.log("notconnected");
        process.exit();
    }

    var kId = await web3.shh.newKeyPair(); 
    var privateKey = await web3.shh.getPrivateKey(kId); //the await keyword resolves the promise
    console.log(privateKey);
}
connect();

如果在node-js中使用express,express本身支持异步,因此可以这么写:

router.get('/', async function(req, res, next) {
  var kId = await web3.shh.newKeyPair(); 
  res.render('index', { title: kId });
});

有问题欢迎留言讨论

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值