bitcoinjs-lib/src/message.js

55 lines
1.6 KiB
JavaScript
Raw Normal View History

/// Implements Bitcoin's feature for signing arbitrary messages.
var Address = require('./address')
2014-05-13 08:38:13 +02:00
var bufferutils = require('./bufferutils')
var crypto = require('./crypto')
var ecdsa = require('./ecdsa')
2014-05-16 07:39:17 +02:00
var networks = require('./networks')
2014-05-16 07:39:17 +02:00
var Address = require('./address')
var ECPubKey = require('./ecpubkey')
2014-05-16 07:39:17 +02:00
function magicHash(message, network) {
var magicPrefix = new Buffer(network.magicPrefix)
2014-05-04 23:44:51 +02:00
var messageBuffer = new Buffer(message)
2014-05-13 08:38:13 +02:00
var lengthBuffer = new Buffer(bufferutils.varIntSize(messageBuffer.length))
bufferutils.writeVarInt(lengthBuffer, messageBuffer.length, 0)
2014-05-04 23:44:51 +02:00
var buffer = Buffer.concat([
2014-05-16 07:39:17 +02:00
magicPrefix, lengthBuffer, messageBuffer
2014-05-04 23:44:51 +02:00
])
return crypto.hash256(buffer)
2014-03-27 02:00:08 +01:00
}
2014-05-16 07:39:17 +02:00
function sign(key, message, network) {
network = network || networks.bitcoin
var hash = magicHash(message, network)
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-05-16 16:27:54 +02:00
return ecdsa.serializeSigCompact(sig.r, sig.s, i, key.pub.compressed)
2014-03-27 02:00:08 +01:00
}
2014-05-16 07:39:17 +02:00
// TODO: network could be implied from address
function verify(address, compactSig, message, network) {
if (typeof address === 'string') {
address = Address.fromBase58Check(address)
}
2014-05-16 07:39:17 +02:00
network = network || networks.bitcoin
2014-05-16 07:39:17 +02:00
var hash = magicHash(message, network)
var sig = ecdsa.parseSigCompact(compactSig)
var Q = ecdsa.recoverPubKey(sig.r, sig.s, hash, sig.i)
var compressed = !!(sig.i & 4)
2014-05-16 07:39:17 +02:00
var pubKey = new ECPubKey(Q, compressed)
return pubKey.getAddress(address.version).toString() === address.toString()
2014-03-27 02:00:08 +01:00
}
module.exports = {
magicHash: magicHash,
sign: sign,
verify: verify
}