Created
August 18, 2017 07:11
-
-
Save nii236/ce2b413c0b57c14160500da6d0637fc5 to your computer and use it in GitHub Desktop.
Verification of a Bitcoin signature from https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/src/ecdsa.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function verify (hash, signature, Q) { | |
typeforce(types.tuple( | |
types.Hash256bit, | |
types.ECSignature, | |
types.ECPoint | |
), arguments) | |
var n = secp256k1.n | |
var G = secp256k1.G | |
var r = signature.r | |
var s = signature.s | |
// 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] | |
if (r.signum() <= 0 || r.compareTo(n) >= 0) return false | |
if (s.signum() <= 0 || s.compareTo(n) >= 0) return false | |
// 1.4.2 H = Hash(M), already done by the user | |
// 1.4.3 e = H | |
var e = BigInteger.fromBuffer(hash) | |
// Compute s^-1 | |
var sInv = s.modInverse(n) | |
// 1.4.4 Compute u1 = es^−1 mod n | |
// u2 = rs^−1 mod n | |
var u1 = e.multiply(sInv).mod(n) | |
var u2 = r.multiply(sInv).mod(n) | |
// 1.4.5 Compute R = (xR, yR) | |
// R = u1G + u2Q | |
var R = G.multiplyTwo(u1, Q, u2) | |
// 1.4.5 (cont.) Enforce R is not at infinity | |
if (secp256k1.isInfinity(R)) return false | |
// 1.4.6 Convert the field element R.x to an integer | |
var xR = R.affineX | |
// 1.4.7 Set v = xR mod n | |
var v = xR.mod(n) | |
// 1.4.8 If v = r, output "valid", and if v != r, output "invalid" | |
return v.equals(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment