bitcoinjs-lib/src/message.js

58 lines
1.8 KiB
JavaScript
Raw Normal View History

/// Implements Bitcoin's feature for signing arbitrary messages.
var Address = require('./address')
2014-05-10 22:30:29 +10:00
var BigInteger = require('bigi')
2014-05-13 16:38:13 +10:00
var bufferutils = require('./bufferutils')
var crypto = require('./crypto')
var ecdsa = require('./ecdsa')
2014-05-16 15:39:17 +10:00
var networks = require('./networks')
2014-05-16 15:39:17 +10:00
var Address = require('./address')
var ECPubKey = require('./ecpubkey')
var ECSignature = require('./ecsignature')
2014-06-07 16:24:27 +10:00
var ecurve = require('ecurve')
var ecparams = ecurve.getCurveByName('secp256k1')
2014-05-17 15:06:52 +10:00
2014-05-16 15:39:17 +10:00
function magicHash(message, network) {
2014-06-17 21:05:18 +10:00
var magicPrefix = new Buffer(network.magicPrefix)
2014-05-05 07:44:51 +10:00
var messageBuffer = new Buffer(message)
2014-05-13 16:38:13 +10:00
var lengthBuffer = new Buffer(bufferutils.varIntSize(messageBuffer.length))
bufferutils.writeVarInt(lengthBuffer, messageBuffer.length, 0)
var buffer = Buffer.concat([magicPrefix, lengthBuffer, messageBuffer])
return crypto.hash256(buffer)
2014-03-26 21:00:08 -04:00
}
function sign(privKey, message, network) {
2014-05-16 15:39:17 +10:00
network = network || networks.bitcoin
var hash = magicHash(message, network)
var signature = privKey.sign(hash)
2014-05-10 22:30:29 +10:00
var e = BigInteger.fromBuffer(hash)
var i = ecdsa.calcPubKeyRecoveryParam(ecparams, e, signature, privKey.pub.Q)
return signature.toCompact(i, privKey.pub.compressed)
2014-03-26 21:00:08 -04:00
}
2014-05-16 15:39:17 +10:00
// TODO: network could be implied from address
function verify(address, signatureBuffer, message, network) {
if (address instanceof Address) {
address = address.toString()
}
2014-05-16 15:39:17 +10:00
network = network || networks.bitcoin
2014-05-16 15:39:17 +10:00
var hash = magicHash(message, network)
var parsed = ECSignature.parseCompact(signatureBuffer)
2014-05-10 22:30:29 +10:00
var e = BigInteger.fromBuffer(hash)
2014-05-24 16:25:38 +10:00
var Q = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i)
2014-05-24 16:25:38 +10:00
var pubKey = new ECPubKey(Q, parsed.compressed)
return pubKey.getAddress(network).toString() === address
2014-03-26 21:00:08 -04:00
}
module.exports = {
magicHash: magicHash,
sign: sign,
verify: verify
}