bitcoinjs-lib/src/message.js

59 lines
1.5 KiB
JavaScript
Raw Normal View History

/// Implements Bitcoin's feature for signing arbitrary messages.
var Address = require('./address')
2014-05-04 08:37:18 +02:00
var BufferExt = require('./buffer')
var crypto = require('./crypto')
var ecdsa = require('./ecdsa')
2014-03-29 07:44:03 +01:00
var ECPubKey = require('./eckey').ECPubKey
2014-05-04 08:37:18 +02:00
// FIXME: incompatible with other networks (Litecoin etc)
2014-05-04 23:44:51 +02:00
var MAGIC_PREFIX = new Buffer('\x18Bitcoin Signed Message:\n')
function magicHash(message) {
2014-05-04 23:44:51 +02:00
var messageBuffer = new Buffer(message)
var lengthBuffer = new Buffer(BufferExt.varIntSize(messageBuffer.length))
BufferExt.writeVarInt(lengthBuffer, messageBuffer.length, 0)
2014-05-04 23:44:51 +02:00
var buffer = Buffer.concat([
MAGIC_PREFIX, lengthBuffer, messageBuffer
])
return crypto.hash256(buffer)
2014-03-27 02:00:08 +01:00
}
// TODO: parameterize compression instead of using ECKey.compressed
function sign(key, message) {
var hash = magicHash(message)
2014-04-23 23:22:10 +02:00
var sig = ecdsa.parseSig(key.sign(hash))
var i = ecdsa.calcPubKeyRecoveryParam(key.pub.Q, sig.r, sig.s, hash)
2014-03-27 02:00:08 +01:00
i += 27
2014-04-17 11:08:16 +02:00
if (key.pub.compressed) {
2014-03-27 02:00:08 +01:00
i += 4
}
var rB = sig.r.toBuffer(32)
var sB = sig.s.toBuffer(32)
2014-04-23 23:22:10 +02:00
return Buffer.concat([new Buffer([i]), rB, sB], 65)
2014-03-27 02:00:08 +01:00
}
// FIXME: stricter API?
function verify(address, sig, message) {
if (typeof address === 'string') {
address = Address.fromBase58Check(address)
}
sig = ecdsa.parseSigCompact(sig)
var pubKey = new ECPubKey(ecdsa.recoverPubKey(sig.r, sig.s, magicHash(message), sig.i))
2014-04-17 11:08:16 +02:00
pubKey.compressed = !!(sig.i & 4)
return pubKey.getAddress(address.version).toString() === address.toString()
2014-03-27 02:00:08 +01:00
}
module.exports = {
magicHash: magicHash,
sign: sign,
verify: verify
}