web3.js: Error: el método shh_newSymKey no existe/no está disponible en Web3.js

Mi objetivo principal es llamar a web3.shhfunciones usando RPC API, Web3.pyo Web3.js. Puedo llamar web3.shhfunciones cuando uso geth attach; que es mi última opción para hacer.

Estoy siguiendo esta respuesta .

  • versión geth:1.8.0-unstable
  • Estoy corriendo gethcon --shhbandera y--rpcapi "admin,eth,net,web3,debug,shh"

  • console.log(web3.version);devuelve: api: '0.20.5'.

Cuando ejecuto el siguiente script:

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

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

var kId = web3.shh.newSymKey(); //Error occurs. 

var kId = web3.shh.newSymKey();da el siguiente error con web3@'0.20.5':

Error: The method shh_newSymKey does not exist/is not available
    at Object.InvalidResponse (/home/alper/eBlocBroker/node_modules/web3/lib/web3/errors.js:38:16)
    at RequestManager.send (/home/alper/eBlocBroker/node_modules/web3/lib/web3/requestmanager.js:61:22)
    at Shh.send [as newSymKey] (/home/alper/eBlocBroker/node_modules/web3/lib/web3/method.js:145:58)
    at Object.<anonymous> (/home/alper/eBlocBroker/dd.js:9:20)
    at Module._compile (module.js:649:30)
    at Object.Module._extensions..js (module.js:660:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Function.Module.runMain (module.js:690:10)

Tenga en cuenta que lo he intentado con web3@1.0.0-beta.34eso también da este error que parece el mismo error:

Promise { <pending> }
true
(node:16162) UnhandledPromiseRejectionWarning: Error: Returned error: The method shh_newSymKey does not exist/is not available
    at Object.ErrorResponse (/home/alper/eBlocBroker/node_modules/web3-shh/node_modules/web3-core-helpers/src/errors.js:29:16)
    at /home/alper/eBlocBroker/node_modules/web3-shh/node_modules/web3-core-requestmanager/src/index.js:140:36
    at XMLHttpRequest.request.onreadystatechange (/home/alper/eBlocBroker/node_modules/web3/node_modules/web3-providers-http/src/index.js:77:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/alper/eBlocBroker/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/home/alper/eBlocBroker/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/home/alper/eBlocBroker/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/home/alper/eBlocBroker/node_modules/xhr2/lib/xhr2.js:469:24)
    at IncomingMessage.emit (events.js:185:15)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:114:19)
(node:16162) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16162) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

[P] ¿Cómo podría solucionar este error? ¿Qué hago mal?

Tenga en cuenta que las shhfunciones disponibles se pueden ver aquí ; salida de console.log(web3.shh).

¿Cuál es su versión web3?
Me refiero a su versión web3, es web3 1.0 o 0.x porque este último no tiene el método newSymKey() a partir de estos documentos: github.com/ethereum/wiki/wiki/JavaScript-API#web3shh
Ah, lo siento, olvidé agregarlo. Lo hice console.log(web3.version)y vuelve: api: '0.20.5'@KakiMasterOfTime
como hice en su lado del cliente js, está usando la versión web3 0.x para que ese método no salga. debe usar la versión más nueva de web3 1.0, ya es estable.
Pero web3.shhdevuelve el método, pero cuando lo llamo da el error. @KakiMasterOfTime
Por favor, vea mi respuesta actualizada con try on 1.0.0-beta.34. @KakiMasterOfTime
Intenté ejecutar geth con --shh y luego usar web3 y funcionó perfectamente, pero estoy ejecutando la versión sable de geth 1.8.7 y la última web3 1.0. ¿Puedes usar web3.shh desde la consola javascript geth ( geth attach)? si no, pruébalo y mira si shhestá correctamente activado.
de geth attach; web3.shh.newSymKey()¡obras! Pero, ¿por qué no funciona a través del script (que muestro en mi pregunta)? @KakiMasterOfTime
Desde aquí ( github.com/ethereum/go-ethereum/wiki/Whisper-v5-RPC-API ); Intenté usar as curl -X POST --data ...pero también dice curl: no URL specified!. No puedo averiguar cómo podría usarlo a través curlde @KakiMasterOfTime

Respuestas (1)

La newSymKey();función devuelve una promesa, que debe resolverse, para obtener el valor devuelto.

Es por eso que el error en la versión web3@1.0.0-beta.34le da un promise pendingmensaje con UnhandledPromiseRejectionWarning, y en la web3@0.20.5versión, el error indica shh_newSymKey does not exist/is not available. [todavía]

así que intentavar kId = web3.shh.newSymKey().then(console.log);

ovar kId = web3.shh.newSymKey().then(function(result) { console.log(result) //will log results. })

Prefiero usar la nueva función async/await en lugar de las promesas (se lee más fácilmente):

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.newSymKey(); //note await
    console.log(kId);

}

connect();
Porque shh.getPrivateKey(kId).then(console.log)me devuelve: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Returned error: invalid argument 0: json: cannot unmarshal object into Go value of type string¿Cómo podría arreglar también este error? @Heraldo
Supongo que publicó estas preguntas de seguimiento aquí: ethereum.stackexchange.com/questions/52112/…
Es causado por el mismo problema que tuvo antes, la línea se ejecuta antes de que se haya resuelto la promesa de las líneas anteriores. Entonces kId está vacío cuando llamas a getPrivateKey. Debe usar awaitcomo se muestra arriba o llamar a shh.getPrivateKey(kId); en una función de devolución de llamada en lugar de que la consola registre el kId, las definiciones de función según los documentos son: web3.shh.newSymKey([devolución de llamada]) web3.shh.getPrivateKey(id, [devolución de llamada])
En lugar de dar kId , lo proporcioné como una cadena que aún enfrenta el mismo error.
Podemos continuar desde la pregunta de seguimiento.