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 [email protected]
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 [email protected]
//if(!await web3.eth.net.isListening()){ //await [email protected]
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 [email protected]
//if(!await web3.eth.net.isListening()){ //await [email protected]
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 });
});
有问题欢迎留言讨论