Я создаю минимальное приложение nodeJS, которое должно подключаться через web3.js к моему узлу geth. Я следую официальной документации web3.js1.0 и использую web3 1.0.0-beta.29.
Мне удается подключиться через IPC, но и HTTP, и веб-сокеты терпят неудачу - в обоих случаях я получаю один и тот же вывод из своего JS-скрипта, как если бы geth вообще не работал. Любая помощь будет оценена по достоинству.
1) HTTP (не работает)
гет:
geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"
index.js:
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545'); // same output as with option below
// var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts(console.log);
console.log("Hello World");
вывод:
$ node index.js
Hello World
Error: Invalid JSON RPC response: ""
2) веб-сокеты (не работают)
гет:
geth syncmode="fast" --cache=4096 --ws --wsport 8546 --wsorigins "*" console
index.js:
var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8546"); // same output as with option below
// var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
web3.eth.getAccounts(console.log);
console.log("Hello World");
вывод:
$ node index.js
Hello World
connection not open on send()
Error: connection not open
3) МПК (работает)
geth: (то же самое начало, что и для HTTP)
geth syncmode="fast" --cache=4096 --rpc --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,web3,personal"
index.js:
var net = require('net');
var Web3 = require('web3');
var web3 = new Web3('/Users/sebastian/Library/Ethereum/geth.ipc', net); // same output as with option below
// var web3 = new Web3(new Web3.providers.IpcProvider('/Users/sebastian/Library/Ethereum/geth.ipc', net));
web3.eth.getAccounts(console.log);
console.log("Hello World");
вывод:
$ node index.js
Hello World
null [ '0x045a6A820FD596a4c1a49732af01E3EF1D6aEb8B' ]
В командной строке geth есть опечатка: вы пропустили двойное тире перед syncmode. Не знаю почему, но, похоже, он не позволяет geth запускать прослушиватель HTTP RPC.
По сути, требуется объявить опцию --wsorigins "*"
в geth
команде, чтобы подключаться к узлам через websocket provider
или http provider
.
В вашем случае вам не хватает двойного тире перед syncmode
, добавление двойного тире или удаление syncmode
решает проблему.
Дополнительно, согласно статье https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options ,
--wsorigins значение: источники, из которых можно принимать запросы веб-сокетов.
Надеюсь, это поможет.
--ws.origin "*"
--ws.origins "*"
!!!Если кто-то использует Geth 1.10.17-stable-25c9b49f
, параметры командной строки немного изменились.
Чтобы включить HTTP
сервер, мы теперь используем --http
флаг. И использование следующего кода приведет к тому же результату:geth --http --http.corsdomain "*" --http.api personal,eth,web3
// Node.js app
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
web3.eth.getAccounts(console.log);
абб