@secux/app-btc
Version:
SecuX Hardware Wallet BTC API
18 lines (15 loc) • 2.21 kB
JavaScript
;
/*!
Copyright 2022 SecuX Technology Inc
Copyright Chen Wei-En
Copyright Wu Tsung-Yu
Licensed under the Apache License, Version 2.0 (the License);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an AS IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/Object.defineProperty(exports,"__esModule",{value:!0}),exports.taprootVerify=exports.taprootConvert=void 0;const utils_1=require("./utils"),BigInteger=require("bigi"),ecurve=require("ecurve"),curve=ecurve.getCurveByName("secp256k1"),G=curve.G,p=curve.p,n=curve.n,zero=BigInteger.ZERO,one=BigInteger.ONE,two=BigInteger.valueOf(2),three=BigInteger.valueOf(3),four=BigInteger.valueOf(4),seven=BigInteger.valueOf(7);function liftX(XOnlyPubkey){const x=BigInteger.fromBuffer(XOnlyPubkey),c=x.pow(three).add(seven).mod(p),y=c.modPow(p.add(one).divide(four),p);if(0!==c.compareTo(y.modPow(two,p)))throw new Error("c is not equal to y^2");let P=ecurve.Point.fromAffine(curve,x,y);return isEven(P)||(P=ecurve.Point.fromAffine(curve,x,p.subtract(y))),P}function isEven(point){return point.affineY.mod(two).equals(zero)}exports.taprootConvert=function(XOnlyPubkey,commitHash){const P=liftX(XOnlyPubkey),tweak=BigInteger.fromBuffer(commitHash);return P.add(G.multiply(tweak)).affineX.toBuffer(32)},exports.taprootVerify=function(signature,message,XOnlyPubkey){const P=liftX(XOnlyPubkey),Px=P.affineX.toBuffer(32),r=BigInteger.fromBuffer(signature.slice(0,32)),s=BigInteger.fromBuffer(signature.slice(32,64));if(r.compareTo(p)>=0)return!1;if(s.compareTo(n)>=0)return!1;const e=function(Rx,Px,m){const hash=(0,utils_1.taggedHash)("BIP0340/challenge",Buffer.concat([Rx,Px,m]));return BigInteger.fromBuffer(hash).mod(n)}(r.toBuffer(32),Px,message),R=function(s,e,P){const sG=G.multiply(s),eP=P.multiply(e);return sG.add(eP.negate())}(s,e,P);return!(R.curve.isInfinity(R)||!isEven(R)||!R.affineX.equals(r))};