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 });
});
有問題歡迎留言討論