UNPKG

@secux/app-btc

Version:
18 lines (15 loc) 2.87 kB
"use strict"; /*! 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.CoinType=exports.PaymentBCH=void 0;const cashaddr=require("cashaddrjs"),payment_1=require("./payment");Object.defineProperty(exports,"CoinType",{enumerable:!0,get:function(){return payment_1.CoinType}});const interface_1=require("./interface");class PaymentBCH extends payment_1.PaymentBTC{static CoinSupported(coin){if(coin!==payment_1.CoinType.BITCOINCASH)throw Error("Not supported cointype")}static p2pkh(coin,opt){if(this.CoinSupported(coin),!opt.publickey&&!opt.hash)throw Error("Invalid Parameters");if(opt.publickey&&opt.hash)throw Error("Invalid Parameters");const pkHash=opt.hash?opt.hash:(0,payment_1.Hash160)(opt.publickey);null===payment_1.logger||void 0===payment_1.logger||payment_1.logger.info(`publickey hash: ${pkHash.toString("hex")}`);let address=cashaddr.encode("bitcoincash","P2PKH",pkHash);address=address.split(":")[1];const op=Buffer.from([interface_1.OPCODES.OP_DUP,interface_1.OPCODES.OP_HASH160,20]),check=Buffer.from([interface_1.OPCODES.OP_EQUALVERIFY,interface_1.OPCODES.OP_CHECKSIG]);return{address,scriptPublickey:Buffer.concat([op,pkHash,check])}}static p2sh(coin,opt){if(this.CoinSupported(coin),!opt.redeemScript&&!opt.hash)throw Error("Invalid Parameters");const redeemHash=opt.hash?opt.hash:(0,payment_1.Hash160)(opt.redeemScript);null===payment_1.logger||void 0===payment_1.logger||payment_1.logger.info(`redeem hash: ${redeemHash.toString("hex")}`);let address=cashaddr.encode("bitcoincash","P2SH",redeemHash);address=address.split(":")[1];const op=Buffer.from([interface_1.OPCODES.OP_HASH160,20]),check=Buffer.from([interface_1.OPCODES.OP_EQUAL]);return{address,scriptPublickey:Buffer.concat([op,redeemHash,check])}}static decode(coin,address){if(address.startsWith("1")){const hash160=this.bs58check.decode(address),hash=Buffer.from(hash160.slice(1));return PaymentBCH.p2pkh(coin,{hash}).scriptPublickey}{address=function(address){return/^(?:bitcoincash|bchtest):q.+/.test(address)}(address)?address:`bitcoincash:${address}`;const{hash,type}=cashaddr.decode(address);return"P2SH"===type?PaymentBCH.p2sh(coin,{hash:Buffer.from(hash)}).scriptPublickey:PaymentBCH.p2pkh(coin,{hash:Buffer.from(hash)}).scriptPublickey}}}exports.PaymentBCH=PaymentBCH;