Sending bitcoins using bitcoinjs-lib - node.js

I'm following tutorial for bitcoinjs at https://medium.com/#orweinberger/how-to-create-a-raw-transaction-using-bitcoinjs-lib-1347a502a3a#.wkf9g2lk0
I receive undefined error for
var key = bitcoin.ECKey.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
Reading https://github.com/bitcoinjs/bitcoinjs-lib/issues/487 I use instead
var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
For line : console.log(key.pub.getAddress().toString()); (from tutorial)
I receive similar exception :
TypeError: Cannot read property 'getAddress' of undefined
at repl:1:20
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
'getAddress' method is also deprecated, what to use instead ?
Any other tutorials for sending bitcoins ? They seem difficult to find ?

This should work
var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
var address = key.getAddress().toString()
console.log(address) // 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4

Better still using newer version of bitcoin.js library do
const bitcoin = require('bitcoinjs-lib');
let keyPair = bitcoin.ECPair.makeRandom();
let publicKey = keyPair.publicKey
const { address } = bitcoin.payments.p2pkh({ pubkey: publicKey });
const privateKey = keyPair.toWIF();
console.log(address)
console.log(privateKey)

Related

Issue with connecting to rethinkdb from Windows 11 via thinky (nodejs)

I'm trying to onboard a new developer, that is using Windows 11 as the only one on our small team. I've guided him through installing WSL2 and Ubuntu 20.04.3 LTS (linux kernel: 5.10.93.2-microsoft-standard-WSL2).
We are 3 other developers who are using native Ubuntu, WSL2 Ubuntu 21.04 and macOS, respectively.
We are all on nodejs 16.14 with the exact same package-lock.json file.
He is the only one getting an Error [ERR_STREAM_WRITE_AFTER_END]: write after end.
tldr;
Both errors are about writing to a Buffer.
Is anyone aware of any related issues to nodejs's Buffer implementation on Windows 11?
We are using thinky as outlined below:
'use strict';
const createThinky = require('thinky');
const { rethinkdbConfig } = require ('./utils/config.js');
const thinky = createThinky (rethinkdbConfig);
// Thinky is our ORM
var type = thinky.type;
// Creates the thinky DB model for payments - we save the amount and the stripe customerID for each transaction
// You can execute any rethinkdb query language on the model, eg Payment.count().execute()
var Payment = thinky.createModel("payments", {
id: type.string(),
amount: type.number(),
customerID: type.string(),
project: type.string(),
projectName: type.string(),
projectPercentage: type.number(),
firefundPercentage: type.number(),
type: type.string(),
processor: type.string(),
email: type.string(),
charged: type.boolean(),
recharged: type.boolean()
});
module.exports = {
model: Payment,
};
Now, it doesn't matter if he connects to a local instance of rethinkdb (2.4.1~0focal), our staging or production rethinkdb (2.3.5~0trusty) on AWS.
I got him to try Netcat with nc -zv [url] 28015 to see if he could connect at all and he got connectıon successful. So I do not think it is a firewall issue.
Error stack trace
node ./bin/www
firefund:www Listening on port 3000 +0ms
node:events:498
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:319:11)
at Socket.Writable.write (node:internal/streams/writable:334:10)
at Connection._sendProof (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:294:19)
at /home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:248:12
at Object.tryCatch (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/helper.js:170:3)
at Connection._computeSaltedPassword (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:247:12)
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:184:18)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
Emitted 'error' event on Connection instance at:
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:129:12)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
The stack trace indicates that it is a connection error in node_modules/rethinkdbdash/lib/connection.js.
connection.js
connection.js: line 294 is this.connection.write(Buffer.concat([new Buffer(message.toString()), NULL_BUFFER])) at the bottom.
Connection.prototype._sendProof = function(authentication, randomNonce, saltedPassword) {
var clientFinalMessageWithoutProof = "c=biws,r=" + randomNonce;
var clientKey = crypto.createHmac("sha256", saltedPassword).update("Client Key").digest()
var storedKey = crypto.createHash("sha256").update(clientKey).digest()
var authMessage =
"n=" + this.user + ",r=" + this.randomString + "," +
authentication + "," +
clientFinalMessageWithoutProof
var clientSignature = crypto.createHmac("sha256", storedKey).update(authMessage).digest()
var clientProof = helper.xorBuffer(clientKey, clientSignature)
var serverKey = crypto.createHmac("sha256", saltedPassword).update("Server Key").digest()
this.serverSignature = crypto.createHmac("sha256", serverKey).update(authMessage).digest()
this.state = 2
var message = JSON.stringify({
authentication: clientFinalMessageWithoutProof + ",p=" + clientProof.toString("base64")
})
this.connection.write(Buffer.concat([new Buffer(message.toString()), NULL_BUFFER]))
}
Variant Error
He has also reported a variant of the same error as posted below:
node ./bin/www
firefund:www Listening on port 3000 +0ms
node:events:498
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:319:11)
at Socket.Writable.write (node:internal/streams/writable:334:10)
at /home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:143:23
at Object.tryCatch (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/helper.js:170:3)
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:142:12)
at Socket.emit (node:events:523:35)
at Socket.emit (node:domain:475:12)
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1143:10)
Emitted 'error' event on Connection instance at:
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:129:12)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
This variant suggest that the error is at line 143 in connection.js:
self.connection.write(Buffer.concat([versionBuffer, authBuffer, NULL_BUFFER]));
self.connection.on('connect', function() {
self.connection.removeAllListeners('error');
self.connection.on('error', function(error) {
self.emit('error', error);
});
var versionBuffer = new Buffer(4)
versionBuffer.writeUInt32LE(protodef.VersionDummy.Version.V1_0, 0)
self.randomString = new Buffer(crypto.randomBytes(18)).toString('base64')
var authBuffer = new Buffer(JSON.stringify({
protocol_version: PROTOCOL_VERSION,
authentication_method: AUTHENTIFICATION_METHOD,
authentication: "n,,n=" + self.user + ",r=" + self.randomString
}));
helper.tryCatch(function() {
self.connection.write(Buffer.concat([versionBuffer, authBuffer, NULL_BUFFER]));
}, function(err) {
// The TCP connection is open, but the ReQL connection wasn't established.
// We can just abort the whole thing
self.open = false;
reject(new Err.ReqlDriverError('Failed to perform handshake with '+self.host+':'+self.port).setOperational());
});
});
If you read this far - THANK YOU!
Both errors are about writing to a Buffer.
Is anyone aware of any related issues to nodejs's Buffer implementation on Windows 11?
Definitely not sure if this is THE answer, just spit-balling here that maybe you could make a custom Buffer.concat function to work in case it really is the nodejs Buffer.concat being the cause of the problem here ;-; hope it works I'm on windows 10 however
function BufferConcat(buffers){ //buffers is the array of buffers
var bytes=Buffer.byteLength, i=0
var length=buffers.reduce((b1,b2)=>bytes(b1)+bytes(b2))
const BufferToReturn=Buffer.alloc(length)
for(let buffer in buffers){
let values=Object.values(buffer)
for(let item of buffer){BufferToReturn[i++]=item}
}
return BufferToReturn
}

.addRole and .removeRole are not functions - Discord Bot Mute Case

I have scanned through all the related topics on Stack Overflow and Tried everything, but the codes just won't work :)
So I'm following a YouTube tutorial on how to mute members using a bot on Discord, and here is the error:
TypeError: person.removeRole is not a function
at Client.<anonymous> (C:\Users\hp\Documents\discordBot\Codes\index.js:39:14)
at Client.emit (events.js:311:20)
at MessageCreateAction.handle (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
at Receiver.receiverOnMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\ws\lib\websocket.js:801:20)
Here is my code, other parts are eliminated if it's necessary I can put them here.
case "mute":
let person = m.mentions.members.first() || m.guild.members.fetch(args[1]); //m.guild.member(
//console.log(person);
if (!person) return m.reply("I don't know who this is, bro.");
let mainrole = m.guild.roles.cache.find((role) => role.name === "Main");
let muterole = m.guild.roles.cache.find((role) => role.name === "Mute");
if (!muterole) return m.reply("Sorry they simply don't exsit.");
let time = args[2];
console.log(time);
if (!time) return m.reply("That's not a time. How did you even do it?");
person.removeRole(mainrole.id);
person.addRole(muterole.id);
// person.remove("Main");
// person.add("Mute");
m.channel.send(
`#${person.user.tag} has now been mute for ${ms(ms(time))}`
);
setTimeout(() => {
person.addRole(mainRole.id);
person.removeRole(muterole.id); //switching the order and see how that looks like
m.channel.send(`#${person.user.tag} has been unmuted, good job!`);
}, ms(time));
Makes me wonder if the import of ms module or discord.js has some problems?
Send help please!
Thank you!
Since discord.js v12 you now need to use roles.add() and roles.remove() instead of .addRole() and .removeRole().

Json cannot read property of undefined

When I execute a command (the error doesn't occur when I type a normal message) in my discord bot I get an error saying:
Cannot read property 'active' of undefined
And it occurs when I try to console log an object from a json file where I store users data.
Those are the first lines of code of the index.js file of my bot, the line where I try to console log is where the error occurs
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
const prefix = '>';
let xp = require("./storage/dbGeneral.json");
let pr = require("./storage/dbPremium.json");
let lv = require("./storage/levels.json");
client.on('message', message => {
console.log(pr[message.author.id].active);
}
This is the json file where I store the data
{
"397387465024864257": {
"active": false,
"dateStart": "",
"dateEnd": ""
}
}
This is the error:
index.js:14
console.log(pr[message.author.id].active);
^
TypeError: Cannot read property 'active' of undefined
at Client.client.on.message (index.js:14:39)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle (\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (\node_modules\ws\lib\event-target.js:120:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
I really don't know what is the cause of the error, all other json requests work fine with the same method.
The error is caused by trying to access a property of something not defined.
To fix your problem, you must check if the user exists in your database.
let user = pr[message.author.id];
if(user) console.log(user.active)

Custom REPL in nodejs

I'm trying to play with the nodejs built in REPL from the documentation.
http://nodejs.org/api/repl.html
The example of adding an item is as follows:
repl.start().context.m = msg;
I cant seem to find away to add multiple menus. I've tried doing:
menus = {m = 'hello', f = 'foo'}
repl.start().context = menus
But that doesn't work either. I get:
testREPL> m
TypeError: needs a 'context' argument.
at REPLServer.self.eval (repl.js:113:21)
at Interface.<anonymous> (repl.js:250:12)
at Interface.EventEmitter.emit (events.js:88:17)
at Interface._onLine (readline.js:199:10)
at Interface._normalWrite._line_buffer (readline.js:308:12)
at Array.forEach (native)
at Interface._normalWrite (readline.js:307:11)
at Socket.ondata (readline.js:90:10)
at Socket.EventEmitter.emit (events.js:115:20)
at TCP.onread (net.js:395:14)
Does anybody know how to get this working?
You can't assign to the context property, you have to add properties to it. What you are trying is "overwriting" it with your own object. Try to assign each property by itself instead:
var context = repl.start({}).context;
context.m = 'hello';
context.f = 'foo';

custom stream object? (nodejs)

Is it possible to extend / initialize the require('stream').Stream; object ? I would like to be able to create a stream object that i can push data to and have all the listeners notified when new data arrive.
I tried the following:
var stream = require('stream');
var test = new stream.Stream();
test.write(new Buffer('mads'));
But i get the following error:
TypeError: Object [object Object] has no method 'write'
at repl:1:6
at Interface.<anonymous> (repl.js:168:22)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty_posix.js:306:10)
at ReadStream.onData (tty_posix.js:69:12)
at ReadStream.emit (events.js:67:17)
For anyone who stumbles on this question today (node v0.10.x), this can be easily achieved using the PassThrough stream introduced with streams2.
var stream = require('stream');
var test = stream.PassThrough();
test.write('mads');
test.end();
You have to create those methods yourself and also set the writable property to true, and don't forget to emit the events in those methods you override as well so that you can use it as a regular event emitter. Check this question for more information.

Resources