Skip to content

Instantly share code, notes, and snippets.

@SahidMiller
Last active July 7, 2021 15:23
Show Gist options
  • Save SahidMiller/3519769580f46e6e43fd4f37651576a0 to your computer and use it in GitHub Desktop.
Save SahidMiller/3519769580f46e6e43fd4f37651576a0 to your computer and use it in GitHub Desktop.
Websocket via Libp2p (electrum-cash)
//Usage
const client = websocketOverLibp2p("/ip4/xxx.xx/tcp/xxx/ws", "/x/electrum")
const getBlocks = () => {
client.send(
JSON.stringify({
method: "blockchain.scripthash.listunspent",
params: [
"60e518016f265ca054e7044b818b3438d2886138c15cc7563f24bbe29e0cca91",
],
id: 1,
})
);
};
//getBlocks()
/**
* Tunnel websocket over libp2p in nodejs
*
* Expected to be used with https://github.com/ipfs/go-ipfs/blob/master/docs/experimental-features.md#ipfs-p2p
* ex: (go-ipfs) ipfs p2p listen /x/electrum /dns4/bch.imaginary.cash/tcp/50003
*
* @param {*} multiaddr multiaddress of libp2p proxy
* @param {*} proto p2p protocol name
* @returns ws instance streamed over libp2p
*/
async websocketOverLibp2p(multiaddr, proto) {
const { libp2p } = await ipfs.createPeer();
let { stream } = await libp2p.dialProtocol(multiaddr, proto);
const socket = toStream.duplex({
source: buffer(stream.source),
sink: stream.sink,
});
socket.setTimeout = () => {};
socket.setNoDelay = () => {};
var agent = new Agent();
agent.createConnection = (options, fn) => {
return socket;
};
var client = new WS(url, { agent });
try {
await new Promise((resolve, reject) => {
client.on("upgrade", function () {
console.log("WebSocket Client Connected");
resolve();
});
client.on("error", function (error) {
console.log("Connection Error: " + error.toString());
reject(error);
});
});
} catch (error) {
console.log("Error connecting to remote websocket");
throw error;
}
client.on("close", function () {
console.log("echo-protocol Connection Closed");
});
client.on("message", function (message) {
console.log("Received: '" + message + "'");
});
//patchEmitter(client);
return client;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment