Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe to `newBlockHeaders` on local RSK node over websockets?

I'm connecting to RSKj using the following endpoint:

ws://localhost:4444/

... However, I am unable to connect.

Note that the equivalent HTTP endpoint http://localhost:4444/ work for me, so I know that my RSKj node is running properly.

I need to listen for newBlockHeaders, so I prefer to use WebSockets (instead of HTTP).

How can I do this?

like image 843
Jesse Clark Avatar asked May 17 '21 10:05

Jesse Clark


People also ask

What are WebSockets in Node JS?

WebSockets in Node.js Jun 10, 2019 WebSockets are a tool for bidirectional communication between a browser client and a server. In particular, WebSockets enable the server to push data to the client.

Can the HTTP headers be specified in the JavaScript WebSockets API?

Short answer: No, only the path and protocol field can be specified. There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.

How is the Sec-WebSocket-protocol header generated?

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor: var ws = new WebSocket ("ws://example.com/path", "protocol"); var ws = new WebSocket ("ws://example.com/path", ["protocol1", "protocol2"]);

How to spin off the HTTP Server and the WebSocket server?

We can make use of a single port to spin off the HTTP server and the WebSocket server. The gist below shows the creation of a simple HTTP server. Once it is created, we tie the WebSocket server to the HTTP port:


1 Answers

RSKj by default uses 4444 as the port for the HTTP transport; and 4445 as the port for the Websockets transport. Also note that the websockets endpoint is not at /, but rather at websocket. Therefore use ws://localhost:4445/websocket as your endpoint.

If you're using web3.js, you can create a web3 instance that connects over Websockets using the following:

const Web3 = require('web3');
const wsEndpoint = 'ws://localhost:4445/websocket';
const wsProvider =
  new Web3.providers.WebsocketProvider(wsEndpoint);
const web3 = new Web3(wsProvider);

The second part of your question can be done using eth_subscribe on newBlockHeaders. Using the web3 instance from above like so:

// eth_subscribe newBlockHeaders
web3.eth.subscribe('newBlockHeaders', function(error, blockHeader) {
  if (!error) {
    // TODO something with blockHeader
  } else {
    // TODO something with error
  }
});

like image 188
bguiz Avatar answered Oct 16 '22 16:10

bguiz