Skip to content

Instantly share code, notes, and snippets.

@knockshore
Last active October 24, 2022 17:57
Show Gist options
  • Save knockshore/06d3cbbbaca44aefeec66ddcac6a9209 to your computer and use it in GitHub Desktop.
Save knockshore/06d3cbbbaca44aefeec66ddcac6a9209 to your computer and use it in GitHub Desktop.
Ethereum Mining Client
class EthClient {
constructor(host, port, user, password, worker) {
this.host = host
this.port = port
this.user = user
this.password = password
this.worker = worker
this.connected = false;
this.queueHead = 0;
this.init();
this.recv_queue = []
this.pctr = 0
this.handle_connect.bind(this)
this.handle_data.bind(this)
this.handle_end.bind(this)
this.recvTImer;
}
init() {
// create secure socket
}
async connect() {
return new Promise((resolve, reject) => {
this.socket = net.createConnection({
host: this.host,
port: this.port,
})
this.socket.setKeepAlive(true)
this.socket.setNoDelay()
this.socket.setTimeout(3000)
this.socket.on('connect', () => {
resolve(null);
this.handle_connect();
})
this.socket.on('data', (data) => this.handle_data(data))
this.socket.on('end', () => this.handle_end())
});
}
handle_connect() {
this.connected = true;
console.log("Connected to:",
this.socket.remoteAddress,
this.socket.remotePort)
console.log("socket status:", this.socket.readyState)
}
async handle_data(data) {
let pl = data.toString('utf8')
console.log("Got data:", this.pctr++, pl, data)
if (this.queueHead >= 10) {
this.recv_queue = []
this.queueHead = 0
}
let pls = pl.split("\r\n")
pls.forEach(i => this.recv_queue.push(i))
}
handle_end() {
console.log("Connection closed:", this.host, this.port)
}
async next() {
return new Promise((resolve, reject) => {
this.recvTimer = setInterval(() => {
if (this.recv_queue.length > 0) {
let res = this.recv_queue[this.queueHead]
if (res) {
this.queueHead++
clearInterval(this.recvTimer)
resolve(res)
}
}
}, 100)
})
}
async send(pl) {
this.socket.write(JSON.stringify(pl) + "\r\n")
}
async subscribe() {
var pl = {
id: 1,
method: "mining.subscribe",
params: [],
//params: [
// "etcool 0.1.0+1",
// "EthereumStratum/1.0.0",
//],
jsonrpc: "2.0",
}
this.send(pl)
}
async authorize() {
let pl = {
id: 3,
jsonrpc: "2.0",
method: "mining.authorize",
params: [
`${this.user}.${this.worker}`,
this.password,
]
}
this.send(pl)
}
sendNoop() {
var pl = {
id: 7,
method: "mining.noop"
}
this.send(pl)
}
close() {
this.socket.end();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment