57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
var bufferutils = require('./bufferutils')
|
|
var crypto = require('./crypto')
|
|
var ecdsa = require('./ecdsa')
|
|
var networks = require('./networks')
|
|
|
|
var BigInteger = require('bigi')
|
|
var ECPair = require('./ecpair')
|
|
var ECSignature = require('./ecsignature')
|
|
|
|
var ecurve = require('ecurve')
|
|
var ecparams = ecurve.getCurveByName('secp256k1')
|
|
|
|
function magicHash (message, network) {
|
|
var messagePrefix = new Buffer(network.messagePrefix)
|
|
var messageBuffer = new Buffer(message)
|
|
var lengthBuffer = bufferutils.varIntBuffer(messageBuffer.length)
|
|
|
|
var buffer = Buffer.concat([messagePrefix, lengthBuffer, messageBuffer])
|
|
return crypto.hash256(buffer)
|
|
}
|
|
|
|
function sign (keyPair, message, network) {
|
|
network = network || networks.bitcoin
|
|
|
|
var hash = magicHash(message, network)
|
|
var signature = keyPair.sign(hash)
|
|
var e = BigInteger.fromBuffer(hash)
|
|
var i = ecdsa.calcPubKeyRecoveryParam(ecparams, e, signature, keyPair.Q)
|
|
|
|
return signature.toCompact(i, keyPair.compressed)
|
|
}
|
|
|
|
// TODO: network could be implied from address
|
|
function verify (address, signature, message, network) {
|
|
if (!Buffer.isBuffer(signature)) {
|
|
signature = new Buffer(signature, 'base64')
|
|
}
|
|
|
|
network = network || networks.bitcoin
|
|
|
|
var hash = magicHash(message, network)
|
|
var parsed = ECSignature.parseCompact(signature)
|
|
var e = BigInteger.fromBuffer(hash)
|
|
var Q = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i)
|
|
var keyPair = new ECPair(null, Q, {
|
|
compressed: parsed.compressed,
|
|
network: network
|
|
})
|
|
|
|
return keyPair.getAddress().toString() === address.toString()
|
|
}
|
|
|
|
module.exports = {
|
|
magicHash: magicHash,
|
|
sign: sign,
|
|
verify: verify
|
|
}
|