|
|
@ -1,9 +1,10 @@ |
|
|
|
var $ = require('preconditions').singleton(); |
|
|
|
var _ = require('lodash'); |
|
|
|
|
|
|
|
var Bitcore = require('bitcore-lib'); |
|
|
|
var crypto = Bitcore.crypto; |
|
|
|
var encoding = Bitcore.encoding; |
|
|
|
var bitcore = require('bitcore-lib'); |
|
|
|
var crypto = bitcore.crypto; |
|
|
|
var encoding = bitcore.encoding; |
|
|
|
var secp256k1 = require('secp256k1'); |
|
|
|
|
|
|
|
var Utils = {}; |
|
|
|
|
|
|
@ -28,28 +29,62 @@ Utils.strip = function(number) { |
|
|
|
|
|
|
|
/* TODO: It would be nice to be compatible with bitcoind signmessage. How |
|
|
|
* the hash is calculated there? */ |
|
|
|
Utils.hashMessage = function(text) { |
|
|
|
Utils.hashMessage = function(text, noReverse) { |
|
|
|
$.checkArgument(text); |
|
|
|
var buf = new Buffer(text); |
|
|
|
var ret = crypto.Hash.sha256sha256(buf); |
|
|
|
ret = new Bitcore.encoding.BufferReader(ret).readReverse(); |
|
|
|
if (!noReverse) { |
|
|
|
ret = new bitcore.encoding.BufferReader(ret).readReverse(); |
|
|
|
} |
|
|
|
return ret; |
|
|
|
}; |
|
|
|
|
|
|
|
Utils.verifyMessage = function(text, signature, pubKey) { |
|
|
|
Utils.verifyMessage = function(text, signature, publicKey) { |
|
|
|
$.checkArgument(text); |
|
|
|
$.checkArgument(pubKey); |
|
|
|
|
|
|
|
if (!signature) |
|
|
|
var hash = Utils.hashMessage(text, true); |
|
|
|
|
|
|
|
var sig = this._tryImportSignature(signature); |
|
|
|
if (!sig) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
|
|
|
|
var publicKeyBuffer = this._tryImportPublicKey(publicKey); |
|
|
|
if (!publicKeyBuffer) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
|
|
|
|
return this._tryVerifyMessage(hash, sig, publicKeyBuffer); |
|
|
|
}; |
|
|
|
|
|
|
|
var pub = new Bitcore.PublicKey(pubKey); |
|
|
|
var hash = Utils.hashMessage(text); |
|
|
|
Utils._tryImportPublicKey = function(publicKey) { |
|
|
|
var publicKeyBuffer = publicKey; |
|
|
|
try { |
|
|
|
if (!Buffer.isBuffer(publicKey)) { |
|
|
|
publicKeyBuffer = new Buffer(publicKey, 'hex'); |
|
|
|
} |
|
|
|
return publicKeyBuffer; |
|
|
|
} catch(e) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
Utils._tryImportSignature = function(signature) { |
|
|
|
try { |
|
|
|
var signatureBuffer = signature; |
|
|
|
if (!Buffer.isBuffer(signature)) { |
|
|
|
signatureBuffer = new Buffer(signature, 'hex'); |
|
|
|
} |
|
|
|
return secp256k1.signatureImport(signatureBuffer); |
|
|
|
} catch(e) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
Utils._tryVerifyMessage = function(hash, sig, publicKeyBuffer) { |
|
|
|
try { |
|
|
|
var sig = new crypto.Signature.fromString(signature); |
|
|
|
return crypto.ECDSA.verify(hash, sig, pub, 'little'); |
|
|
|
} catch (e) { |
|
|
|
return secp256k1.verify(hash, sig, publicKeyBuffer); |
|
|
|
} catch(e) { |
|
|
|
return false; |
|
|
|
} |
|
|
|
}; |
|
|
|