Understanding signing messages with bitcoinjs-lib

3

1

I'm trying to understand what a specific line of code does when signing a message using bitcoinjs-lib. Here's the code:

var bitcoin = require('bitcoinjs-lib')
var bitcoinMessage = require('bitcoinjs-message')

var keyPair = bitcoin.ECPair.makeRandom();
//private key
var privateKey = keyPair.toWIF();
// Address
var address = keyPair.getAddress();

console.log(privateKey);
console.log(address);

privateKey = keyPair.d.toBuffer(32)
var message = 'your message'
var messagePrefix = bitcoin.networks.bitcoin.messagePrefix

var signature = bitcoinMessage.sign(message, messagePrefix, privateKey, keyPair.compressed)
console.log(signature.toString('base64'))

The line I'm curious about is this one:

privateKey = keyPair.d.toBuffer(32)

What exactly is this code doing and why is it necessary?

Thanks,

Connor

user1929274

Posted 2016-11-30T20:25:50.137

Reputation: 63

Answers

2

That particular line of code asserts that the private key fits into a 32 byte-sized byte array properly with the necessary zero paddings. As the private key is simply some random Big Integer between 0 ~ 2^(256-1), javascript may encode that integer into different byte array sizes. For example, if the d value was simply 1, then it could easily fit into a 1 byte-sized byte array and you would not have the leading/trailing zeroes required depending on the endianess of your encoding of choice.

renlord

Posted 2016-11-30T20:25:50.137

Reputation: 2 167

Ah ha! That makes sense. Thank you for the great clarification.user1929274 2016-12-01T14:51:11.627