New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@secux/app-btc

Package Overview
Dependencies
Maintainers
2
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@secux/app-btc - npm Package Compare versions

Comparing version 3.1.0 to 3.1.1

7

lib/app-btc.d.ts

@@ -145,2 +145,9 @@ /// <reference types="node" />

static deriveAddress(xpub: string, change: number, addressIndex: number, option?: AddressOption): string;
/**
* Estimate virtual size of transaction.
* @param {Array<ScriptType>} inputs
* @param {Array<ScriptType>} outputs
* @returns {number} virtual size
*/
static getVirtualSize(inputs: Array<ScriptType>, outputs: Array<ScriptType>): number;
}

2

lib/app-btc.js

@@ -1,1 +0,1 @@

"use strict";var e,t=this&&this.__decorate||function(e,t,r,i){var o,u=arguments.length,n=u<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(n=(u<3?o(n):u>3?o(t,r,n):o(t,r))||n);return u>3&&n&&Object.defineProperty(t,r,n),n},r=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(o,u){function n(e){try{p(i.next(e))}catch(e){u(e)}}function c(e){try{p(i.throw(e))}catch(e){u(e)}}function p(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,c)}p((i=i.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecuxBTC=exports.ScriptType=exports.CoinType=void 0;const i=require("secp256k1/elliptic"),o=require("@secux/utility"),u=require("@secux/utility/lib/xpub"),n=require("ow"),c=require("@secux/protocol-transaction"),p=require("@secux/utility/lib/communication"),s=require("@secux/protocol-transaction/lib/interface"),a=require("./interface");Object.defineProperty(exports,"CoinType",{enumerable:!0,get:function(){return a.CoinType}}),Object.defineProperty(exports,"ScriptType",{enumerable:!0,get:function(){return a.ScriptType}});const l=require("./psbt"),d=require("./utils"),f=require("@secux/transport");let y=e=class{static addressConvert(e,t){const r=(0,d.getPublickey)(e);(0,n.default)(t,n.default.any(a.ow_path,a.ow_PathObject));const o=Buffer.from(i.publicKeyConvert(r,!0)),u="string"==typeof t?(0,d.getCoinType)(t):t.coin,c="string"==typeof t?(0,d.getDefaultScript)(t):t.script,p=(0,d.getPayment)(u);switch(c){case a.ScriptType.P2SH_P2WPKH:const e=p.p2wpkh(u,{publickey:o});return p.p2sh(u,e.redeemHash).address;case a.ScriptType.P2SH_P2PKH:const t=p.p2pkh(u,{publickey:o});return p.p2sh(u,t.redeemHash).address;case a.ScriptType.P2PKH:return p.p2pkh(u,{publickey:o}).address;case a.ScriptType.P2WPKH:return p.p2wpkh(u,{publickey:o}).address;case a.ScriptType.P2TR:return p.p2tr(u,{publickey:o}).address;default:throw Error(`Invalid or unsupported ScriptType, got ${c} of ${u}`)}}static resolveAddress(t,r){const i=e.resolvePublickey(t);return e.addressConvert(i,r)}static preparePublickey(e,t){var r;(0,n.default)(e,a.ow_path),t&&(0,n.default)(t,a.ow_AddressOption);const i=null!==(r=null==t?void 0:t.coin)&&void 0!==r?r:(0,d.getCoinType)(e),u=a.coinmap[i].coinType,p=void 0===(null==t?void 0:t.script)?void 0:(0,d.getPurpose)(null==t?void 0:t.script);return(0,n.default)(e,o.ow_strictPath(u,p)),c.SecuxTransactionTool.getPublickey(e,s.EllipticCurve.SECP256K1)}static resolvePublickey(e){const t=c.SecuxTransactionTool.resolvePublickey(e,s.EllipticCurve.SECP256K1,!0);return Buffer.from(t,"base64").toString("hex")}static prepareXPublickey(e){return(0,n.default)(e,a.ow_accountPath),c.SecuxTransactionTool.getXPublickey(e)}static resolveXPublickey(e,t){return(0,n.default)(t,a.ow_accountPath),c.SecuxTransactionTool.resolveXPublickey(e,t)}static prepareSign(e,t,r){var i;(0,n.default)(e,n.default.array.ofType(a.ow_txInput).minLength(1)),(0,n.default)(r,n.default.any(n.default.undefined,a.ow_SignOption));const u=null!==(i=null==r?void 0:r.coin)&&void 0!==i?i:(0,d.getCoinType)(e[0].path);(0,n.default)(t,a.ow_txOutput),e.map((e=>{const t=e.script?(0,d.getPurpose)(e.script):a.btcPurposes;(0,n.default)(e.path,o.ow_strictPath(a.coinmap[u].coinType,t))}));let c=(0,a.isOutuptScriptExtended)(t.to);if(c){const e=c.script?(0,d.getPurpose)(c.script):a.btcPurposes;(0,n.default)(c.path,o.ow_strictPath(a.coinmap[u].coinType,e))}if(t.utxo){const e=t.utxo.script?(0,d.getPurpose)(t.utxo.script):a.btcPurposes;(0,n.default)(t.utxo.path,o.ow_strictPath(a.coinmap[u].coinType,e))}const p=new l.SecuxPsbt(u);return p.AddInputs(e),p.AddOutputs(t.utxo?[t.to,t.utxo]:[t.to]),p.PrepareSign(null==r?void 0:r.feeRate)}static resolveSignatureList(e){return c.SecuxTransactionTool.resolveSignatureList(e).map((e=>Buffer.from(e,"base64"))).map((e=>o.Signature.fromSignature(e))).map((e=>Buffer.concat([e.r,e.s]).toString("hex")))}static resolveTransaction(t,r,i,u=a.CoinType.BITCOIN){(0,n.default)(t,p.ow_communicationData),(0,n.default)(r,o.ow_hexString),(0,n.default)(i,n.default.array.ofType(n.default.any(o.ow_hexString,n.default.buffer))),(0,n.default)(u,n.default.number.inRange(0,a.CoinType.__LENGTH-1));const c=e.resolveSignatureList(t).map((e=>Buffer.from(e,"hex"))),s=i.map((e=>(0,d.getPublickey)(e)));return l.SecuxPsbt.FromBuffer(Buffer.from(r,"hex"),u).appendSignature(c,s).finalizeAllInputs().extractTransaction().toHex()}static getAddress(t,i){var o,u;return r(this,void 0,void 0,(function*(){const r=e.prepareAddress(t,i),n=yield this.Exchange((0,p.getBuffer)(r));return e.resolveAddress(n,{coin:null!==(o=null==i?void 0:i.coin)&&void 0!==o?o:(0,d.getCoinType)(t),script:null!==(u=null==i?void 0:i.script)&&void 0!==u?u:(0,d.getDefaultScript)(t)})}))}static getPublickey(t,i){return r(this,void 0,void 0,(function*(){const r=e.preparePublickey(t,i),o=yield this.Exchange((0,p.getBuffer)(r));return e.resolvePublickey(o)}))}static getXPublickey(t){return r(this,void 0,void 0,(function*(){const r=e.prepareXPublickey(t),i=yield this.Exchange((0,p.getBuffer)(r));return e.resolveXPublickey(i,t)}))}static sign(t,i,o){var u,n;return r(this,void 0,void 0,(function*(){const c={},s=t=>r(this,void 0,void 0,(function*(){if(void 0!==c[t])return c[t];const r=yield e.getPublickey.call(this,t,{coin:a}),i=Buffer.from(r,"hex");return c[t]=i,i})),a=null!==(u=null==o?void 0:o.coin)&&void 0!==u?u:(0,d.getCoinType)(t[0].path);for(const e of t)void 0===e.publickey&&(e.publickey=yield s(e.path));i.to.path&&void 0===i.to.publickey&&(i.to.publickey=yield s(i.to.path)),(null===(n=i.utxo)||void 0===n?void 0:n.path)&&void 0===i.utxo.publickey&&(i.utxo.publickey=yield s(i.utxo.path));const{commandData:l,rawTx:f}=e.prepareSign(t,i,{coin:a,feeRate:null==o?void 0:o.feeRate}),y=yield this.Exchange((0,p.getBuffer)(l));return{raw_tx:e.resolveTransaction(y,f,t.map((e=>e.publickey)),a)}}))}static deriveAddress(t,r,i,o){var c,p;(0,n.default)(r,n.default.number.uint8),(0,n.default)(i,n.default.number.uint8),(0,n.default)(o,n.default.any(n.default.undefined,a.ow_AddressOption));const s=(0,u.decodeXPUB)(t);if(3!==s.depth)throw Error(`ArgumentError: expect depth from xpub is 3, but got ${s.depth}`);if(null==o?void 0:o.script)if(o.script in[a.ScriptType.P2PKH,a.ScriptType.P2SH_P2PKH,a.ScriptType.P2SH_P2WPKH,a.ScriptType.P2WPKH]){const e=(0,d.getPurpose)(null==o?void 0:o.script);if(s.purpose!==e)throw Error(`ArgumentError: expect purpose from xpub is ${e}, but got ${s.purpose}`)}else{if(44!==s.purpose)throw Error(`ArgumentError: expect purpose from xpub is 44, but got ${s.purpose}`);s.purpose,(0,d.getPurpose)(null==o?void 0:o.script)}const{publickey:l}=(0,u.deriveKey)(s.publickey,s.chaincode,[r,i]),f=null!==(c=null==o?void 0:o.coin)&&void 0!==c?c:a.CoinType.BITCOIN,y=null!==(p=null==o?void 0:o.script)&&void 0!==p?p:(0,d.getDefaultScript)(`m/${s.purpose}'`);return e.addressConvert(l,{coin:f,script:y})}};y.prepareAddress=e.preparePublickey,y=e=t([(0,f.staticImplements)()],y),exports.SecuxBTC=y,(0,f.loadPlugin)(y,"SecuxBTC");
"use strict";var e,t=this&&this.__decorate||function(e,t,r,i){var o,u=arguments.length,n=u<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(n=(u<3?o(n):u>3?o(t,r,n):o(t,r))||n);return u>3&&n&&Object.defineProperty(t,r,n),n},r=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(o,u){function n(e){try{s(i.next(e))}catch(e){u(e)}}function c(e){try{s(i.throw(e))}catch(e){u(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,c)}s((i=i.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecuxBTC=exports.ScriptType=exports.CoinType=void 0;const i=require("secp256k1/elliptic"),o=require("varuint-bitcoin"),u=require("@secux/utility"),n=require("@secux/utility/lib/xpub"),c=require("ow"),s=require("@secux/protocol-transaction"),p=require("@secux/utility/lib/communication"),a=require("@secux/protocol-transaction/lib/interface"),l=require("./interface");Object.defineProperty(exports,"CoinType",{enumerable:!0,get:function(){return l.CoinType}}),Object.defineProperty(exports,"ScriptType",{enumerable:!0,get:function(){return l.ScriptType}});const d=require("./psbt"),f=require("./utils"),y=require("@secux/transport");let v=e=class{static addressConvert(e,t){const r=(0,f.getPublickey)(e);(0,c.default)(t,c.default.any(l.ow_path,l.ow_PathObject));const o=Buffer.from(i.publicKeyConvert(r,!0)),u="string"==typeof t?(0,f.getCoinType)(t):t.coin,n="string"==typeof t?(0,f.getDefaultScript)(t):t.script,s=(0,f.getPayment)(u);switch(n){case l.ScriptType.P2SH_P2WPKH:const e=s.p2wpkh(u,{publickey:o});return s.p2sh(u,e.redeemHash).address;case l.ScriptType.P2SH_P2PKH:const t=s.p2pkh(u,{publickey:o});return s.p2sh(u,t.redeemHash).address;case l.ScriptType.P2PKH:return s.p2pkh(u,{publickey:o}).address;case l.ScriptType.P2WPKH:return s.p2wpkh(u,{publickey:o}).address;case l.ScriptType.P2TR:return s.p2tr(u,{publickey:o}).address;default:throw Error(`Invalid or unsupported ScriptType, got ${n} of ${u}`)}}static resolveAddress(t,r){const i=e.resolvePublickey(t);return e.addressConvert(i,r)}static preparePublickey(e,t){var r;(0,c.default)(e,l.ow_path),t&&(0,c.default)(t,l.ow_AddressOption);const i=null!==(r=null==t?void 0:t.coin)&&void 0!==r?r:(0,f.getCoinType)(e),o=l.coinmap[i].coinType,n=void 0===(null==t?void 0:t.script)?void 0:(0,f.getPurpose)(null==t?void 0:t.script);return(0,c.default)(e,u.ow_strictPath(o,n)),s.SecuxTransactionTool.getPublickey(e,a.EllipticCurve.SECP256K1)}static resolvePublickey(e){const t=s.SecuxTransactionTool.resolvePublickey(e,a.EllipticCurve.SECP256K1,!0);return Buffer.from(t,"base64").toString("hex")}static prepareXPublickey(e){return(0,c.default)(e,l.ow_accountPath),s.SecuxTransactionTool.getXPublickey(e)}static resolveXPublickey(e,t){return(0,c.default)(t,l.ow_accountPath),s.SecuxTransactionTool.resolveXPublickey(e,t)}static prepareSign(e,t,r){var i;(0,c.default)(e,c.default.array.ofType(l.ow_txInput).minLength(1)),(0,c.default)(r,c.default.any(c.default.undefined,l.ow_SignOption));const o=null!==(i=null==r?void 0:r.coin)&&void 0!==i?i:(0,f.getCoinType)(e[0].path);(0,c.default)(t,l.ow_txOutput),e.map((e=>{const t=e.script?(0,f.getPurpose)(e.script):l.btcPurposes;(0,c.default)(e.path,u.ow_strictPath(l.coinmap[o].coinType,t))}));let n=(0,l.isOutuptScriptExtended)(t.to);if(n){const e=n.script?(0,f.getPurpose)(n.script):l.btcPurposes;(0,c.default)(n.path,u.ow_strictPath(l.coinmap[o].coinType,e))}if(t.utxo){const e=t.utxo.script?(0,f.getPurpose)(t.utxo.script):l.btcPurposes;(0,c.default)(t.utxo.path,u.ow_strictPath(l.coinmap[o].coinType,e))}const s=new d.SecuxPsbt(o);return s.AddInputs(e),s.AddOutputs(t.utxo?[t.to,t.utxo]:[t.to]),s.PrepareSign(null==r?void 0:r.feeRate)}static resolveSignatureList(e){return s.SecuxTransactionTool.resolveSignatureList(e).map((e=>Buffer.from(e,"base64"))).map((e=>u.Signature.fromSignature(e))).map((e=>Buffer.concat([e.r,e.s]).toString("hex")))}static resolveTransaction(t,r,i,o=l.CoinType.BITCOIN){(0,c.default)(t,p.ow_communicationData),(0,c.default)(r,u.ow_hexString),(0,c.default)(i,c.default.array.ofType(c.default.any(u.ow_hexString,c.default.buffer))),(0,c.default)(o,c.default.number.inRange(0,l.CoinType.__LENGTH-1));const n=e.resolveSignatureList(t).map((e=>Buffer.from(e,"hex"))),s=i.map((e=>(0,f.getPublickey)(e)));return d.SecuxPsbt.FromBuffer(Buffer.from(r,"hex"),o).appendSignature(n,s).finalizeAllInputs().extractTransaction().toHex()}static getAddress(t,i){var o,u;return r(this,void 0,void 0,(function*(){const r=e.prepareAddress(t,i),n=yield this.Exchange((0,p.getBuffer)(r));return e.resolveAddress(n,{coin:null!==(o=null==i?void 0:i.coin)&&void 0!==o?o:(0,f.getCoinType)(t),script:null!==(u=null==i?void 0:i.script)&&void 0!==u?u:(0,f.getDefaultScript)(t)})}))}static getPublickey(t,i){return r(this,void 0,void 0,(function*(){const r=e.preparePublickey(t,i),o=yield this.Exchange((0,p.getBuffer)(r));return e.resolvePublickey(o)}))}static getXPublickey(t){return r(this,void 0,void 0,(function*(){const r=e.prepareXPublickey(t),i=yield this.Exchange((0,p.getBuffer)(r));return e.resolveXPublickey(i,t)}))}static sign(t,i,o){var u,n;return r(this,void 0,void 0,(function*(){const c={},s=t=>r(this,void 0,void 0,(function*(){if(void 0!==c[t])return c[t];const r=yield e.getPublickey.call(this,t,{coin:a}),i=Buffer.from(r,"hex");return c[t]=i,i})),a=null!==(u=null==o?void 0:o.coin)&&void 0!==u?u:(0,f.getCoinType)(t[0].path);for(const e of t)void 0===e.publickey&&(e.publickey=yield s(e.path));i.to.path&&void 0===i.to.publickey&&(i.to.publickey=yield s(i.to.path)),(null===(n=i.utxo)||void 0===n?void 0:n.path)&&void 0===i.utxo.publickey&&(i.utxo.publickey=yield s(i.utxo.path));const{commandData:l,rawTx:d}=e.prepareSign(t,i,{coin:a,feeRate:null==o?void 0:o.feeRate}),y=yield this.Exchange((0,p.getBuffer)(l));return{raw_tx:e.resolveTransaction(y,d,t.map((e=>e.publickey)),a)}}))}static deriveAddress(t,r,i,o){var u,s;(0,c.default)(r,c.default.number.uint8),(0,c.default)(i,c.default.number.uint8),(0,c.default)(o,c.default.any(c.default.undefined,l.ow_AddressOption));const p=(0,n.decodeXPUB)(t);if(3!==p.depth)throw Error(`ArgumentError: expect depth from xpub is 3, but got ${p.depth}`);if(null==o?void 0:o.script)if(o.script in[l.ScriptType.P2PKH,l.ScriptType.P2SH_P2PKH,l.ScriptType.P2SH_P2WPKH,l.ScriptType.P2WPKH]){const e=(0,f.getPurpose)(null==o?void 0:o.script);if(p.purpose!==e)throw Error(`ArgumentError: expect purpose from xpub is ${e}, but got ${p.purpose}`)}else{if(44!==p.purpose)throw Error(`ArgumentError: expect purpose from xpub is 44, but got ${p.purpose}`);p.purpose,(0,f.getPurpose)(null==o?void 0:o.script)}const{publickey:a}=(0,n.deriveKey)(p.publickey,p.chaincode,[r,i]),d=null!==(u=null==o?void 0:o.coin)&&void 0!==u?u:l.CoinType.BITCOIN,y=null!==(s=null==o?void 0:o.script)&&void 0!==s?s:(0,f.getDefaultScript)(`m/${p.purpose}'`);return e.addressConvert(a,{coin:d,script:y})}static getVirtualSize(e,t){const r=8+o.encodingLength(e.length)+o.encodingLength(t.length)+e.reduce(((e,t)=>e+40+(0,f.sliceSize)((0,f.getInScriptSize)(t))),0)+t.reduce(((e,t)=>e+8+(0,f.sliceSize)((0,f.getOutScriptSize)(t))),0),i=e.map((e=>(0,f.getWitnessSize)(e)));return(4*r+(i.some((e=>0!==e.length))?2+i.reduce(((e,t)=>e+(0,f.vectorSize)(t)),0):0))/4}};v.prepareAddress=e.preparePublickey,v=e=t([(0,y.staticImplements)()],v),exports.SecuxBTC=v,(0,y.loadPlugin)(v,"SecuxBTC");

@@ -1,1 +0,1 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BufferWriter=exports.BufferReader=void 0;const t=require("varuint-bitcoin");exports.BufferWriter=class{constructor(t,e=0){this.buffer=t,this.offset=e}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){var r,f,s;this.offset=(r=this.buffer,f=t,s=this.offset,e(f,9007199254740991),r.writeInt32LE(-1&f,s),r.writeUInt32LE(Math.floor(f/4294967296),s+4),s+8)}writeVarInt(e){t.encode(e,this.buffer,this.offset),this.offset+=t.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach((t=>this.writeVarSlice(t)))}};function e(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}exports.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=function(t,r){const f=t.readUInt32LE(r);let s=t.readUInt32LE(r+4);return s*=4294967296,e(s+f,9007199254740991),s+f}(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const e=t.decode(this.buffer,this.offset);return this.offset+=t.decode.bytes,e}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const e=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,e}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),e=[];for(let r=0;r<t;r++)e.push(this.readVarSlice());return e}};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BufferWriter=exports.BufferReader=void 0;const t=require("varuint-bitcoin");exports.BufferWriter=class{constructor(t,e=0){this.buffer=t,this.offset=e}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){var r,s,f;this.offset=(r=this.buffer,s=t,f=this.offset,e(s,9007199254740991),r.writeInt32LE(-1&s,f),r.writeUInt32LE(Math.floor(s/4294967296),f+4),f+8)}writeVarInt(e){t.encode(e,this.buffer,this.offset),this.offset+=t.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach((t=>this.writeVarSlice(t)))}};function e(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}exports.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=function(t,r){const s=t.readUInt32LE(r);let f=t.readUInt32LE(r+4);return f*=4294967296,e(f+s,9007199254740991),f+s}(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const e=t.decode(this.buffer,this.offset);return this.offset+=t.decode.bytes,e}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const e=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,e}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),e=[];for(let r=0;r<t;r++)e.push(this.readVarSlice());return e}};

@@ -1,1 +0,1 @@

"use strict";var t,i,e,s,r,n,p,a,o,c,u,h,f=this&&this.__classPrivateFieldSet||function(t,i,e,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof i?t!==i||!r:!i.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(t,e):r?r.value=e:i.set(t,e),e},l=this&&this.__classPrivateFieldGet||function(t,i,e,s){if("a"===e&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof i?t!==i||!s:!i.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===e?s:"a"===e?s.call(t):s?s.value:i.get(t)};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecuxPsbt=void 0;const d=require("./parser"),S=require("bip174/src/lib/utils"),y=require("secp256k1/elliptic"),g=require("hash.js"),P=require("./script"),T=require("@secux/utility"),w=require("./interface"),b=require("./utils"),m=require("./payment"),k=require("./transaction"),v=require("./coindef"),H=require("../../protocol-transaction/lib/protocol-transaction"),E=require("./bip340"),x=null===T.Logger||void 0===T.Logger?void 0:T.Logger.child({id:"psbt"});class W{constructor(a,o=new d.Psbtv2(new $)){t.add(this),i.set(this,void 0),e.set(this,void 0),s.set(this,void 0),r.set(this,[]),n.set(this,void 0),p.set(this,{}),f(this,i,o,"f"),f(this,e,a,"f"),f(this,s,(0,b.getPayment)(l(this,e,"f")),"f"),f(this,n,l(this,i,"f").globalMap.unsignedTx.tx,"f"),a===w.CoinType.BITCOINCASH&&(l(this,n,"f").version=1)}static FromBuffer(t,i){const e=d.Psbtv2.fromBuffer(t,(t=>new $(t)));return new W(i,e)}AddInput(t){var n;if(!(0,T.isSupportedCoin)(t.path))throw Error(`ArgumentError: unsupport bip32 path, got "${t.path}"`);const p={},a={},o=(0,b.getPublickey)(t.publickey),c=null!==(n=t.script)&&void 0!==n?n:(0,b.getDefaultScript)(t.path);switch(c){case w.ScriptType.P2PKH:p.witnessUtxo={script:l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:o}).scriptPublickey,value:t.satoshis};break;case w.ScriptType.P2SH_P2PKH:const r=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:o});a.redeemScript=r.scriptPublickey,p.witnessUtxo={script:l(this,s,"f").p2sh(l(this,e,"f"),r.redeemHash).scriptPublickey,value:t.satoshis};break;case w.ScriptType.P2SH_P2WPKH:const n=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:o});a.redeemScript=n.scriptPublickey,p.witnessUtxo={script:l(this,s,"f").p2sh(l(this,e,"f"),n.redeemHash).scriptPublickey,value:t.satoshis};break;case w.ScriptType.P2WPKH:p.witnessUtxo={script:l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:o}).scriptPublickey,value:t.satoshis};break;case w.ScriptType.P2TR:p.witnessUtxo={script:l(this,s,"f").p2tr(l(this,e,"f"),{publickey:o}).scriptPublickey,value:t.satoshis};break;default:throw Error(`ArgumentError: Invalid ScriptType of input#${l(this,i,"f").inputs.length}, got "${w.ScriptType[c]}"`)}if(t.txHex){const s=k.Transaction.fromBuffer(Buffer.from(t.txHex,"hex"));if((0,b.getSerializer)(l(this,e,"f")).getId(s)!==t.hash)throw Error(`UTXO hash for input #${l(this,i,"f").inputs.length} doesn't match the hash specified in the prevout`);const r=s.outs[t.vout];if(r.value!==t.satoshis)throw Error(`UTXO value for input #${l(this,i,"f").inputs.length} doesn't match the value specified in the prevout`);r.script.equals(p.witnessUtxo.script)||null==x||x.warn(`Input script generation error: ${r.script.toString("hex")}, got "${p.witnessUtxo.script}"`)}const u=Object.assign(Object.assign({hash:t.hash,index:t.vout},p),a);return l(this,i,"f").addInput(u),l(this,r,"f").push(t.path),this}AddInputs(t){for(const i of t)this.AddInput(i);return this}AddOutput(t){var r;let n,p,a,o=t.satoshis;if(n=(0,w.isOutuptScriptExtended)(t)){const t=(0,b.getPublickey)(n.publickey);a=n.path;const o=null!==(r=n.script)&&void 0!==r?r:(0,b.getDefaultScript)(a);let c,u;switch(o){case w.ScriptType.P2SH_P2WPKH:if(!n.path.startsWith("m/49'/"))throw Error("P2SH(...) should use m/49' path");c=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:t}).redeemHash,u=l(this,s,"f").p2sh(l(this,e,"f"),c),p=u.scriptPublickey;break;case w.ScriptType.P2SH_P2PKH:if(!n.path.startsWith("m/49'/"))throw Error("P2SH(...) should use m/49' path");c=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:t}).redeemHash,u=l(this,s,"f").p2sh(l(this,e,"f"),c),p=u.scriptPublickey;break;case w.ScriptType.P2PKH:if(!n.path.startsWith("m/44'/"))throw Error("P2PKH should use m/44' path");p=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:t}).scriptPublickey;break;case w.ScriptType.P2WPKH:if(!n.path.startsWith("m/84'/"))throw Error("P2WPKH should use m/84' path");p=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:t}).scriptPublickey;break;case w.ScriptType.P2TR:if(!n.path.startsWith("m/86'/"))throw Error("P2TR should use m/86' path");p=l(this,s,"f").p2tr(l(this,e,"f"),{publickey:t}).scriptPublickey;break;default:throw Error(`ArgumentError: Invalid ScriptType of output#${l(this,i,"f").outputs.length}, got "${w.ScriptType[o]}"`)}}else if(n=(0,w.isOutputAddress)(t))p=l(this,s,"f").decode(l(this,e,"f"),n.address);else{if(!(n=(0,w.isOutuptScript)(t)))throw Error("Invalid parameter of output");p=Buffer.from(n.scriptHex,"hex")}return l(this,i,"f").addOutput({script:p,value:o,path:a}),this}AddOutputs(t){for(const i of t)this.AddOutput(i);return this}PrepareSign(s){if(s){const e=l(this,t,"m",u).call(this),r=Math.round(e*s);null==x||x.info(`Estimated fee is ${r}, with ${s} fee rates.`);const p=l(this,i,"f").inputs.reduce(((t,i)=>t+i.witnessUtxo.value),0),a=l(this,n,"f").outs[0].value,o=1===l(this,i,"f").outputs.length?0:l(this,n,"f").outs[1].value,c=p-a-o;if(c<r&&(null==x||x.warn(`Estimated fee is ${r}, but got ${c}.`)),c>r||c<e)if(0!==o){const t=p-a-r;if(t<0)throw Error(`Insufficient amount, expect ${a+r}, but got ${p}.`);l(this,n,"f").outs[1].value=t,null==x||x.info(`Modify change amount from ${o} to ${t}.`)}else{const t=p-r;if(t<0)throw Error(`Insufficient amount, expect at least ${r}, but got ${p}.`);l(this,n,"f").outs[0].value=t,null==x||x.info(`Modify spend amount from ${a} to ${t}.`)}}const{type:p}=l(this,t,"m",a).call(this,0),c=l(this,e,"f")!==w.CoinType.BITCOINCASH&&p===w.ScriptType.P2PKH?Buffer.alloc(0):Buffer.from([l(this,i,"f").outputs.length,...(0,T.BigIntToBuffer)(l(this,n,"f").outs[0].value,8),l(this,n,"f").outs[0].script.length,...l(this,n,"f").outs[0].script,...l(this,n,"f").outs.slice(1).reduce(((t,i)=>[...t,...(0,T.BigIntToBuffer)(i.value,8),...(0,T.buildPathBuffer)(i.path).pathBuffer]),[])]),h=l(this,i,"f").inputs.map(((i,e)=>{const s=l(this,t,"m",o).call(this,e);return null==x||x.debug(`tx data [${e}]: ${s.toString("hex")}`),s}));null==x||x.debug(`confirm data: ${c.toString("hex")}`);return{commandData:H.SecuxTransactionTool.signRawTransactionList(l(this,r,"f"),h,c),rawTx:l(this,i,"f").toHex()}}appendSignature(s,r){var n,p;if(s.length!==r.length)throw Error(`ArgumentError: each signature is correspond to one publickey, got ${s.length} signatures and ${r.length} publickeys`);for(let c=0;c<l(this,i,"f").inputs.length;c++){const u=l(this,t,"m",o).call(this,c);if(l(this,t,"m",a).call(this,c).type!==w.ScriptType.P2TR){const t=l(this,e,"f")===w.CoinType.GROESTL?Buffer.from((0,g.sha256)().update(u).digest()):Buffer.from((0,g.sha256)().update((0,g.sha256)().update(u).digest()).digest()),p=r[c];if(!y.ecdsaVerify(s[c],t,p))throw Error(`Signature Error #${c}`);let a=null!==(n=l(this,i,"f").inputs[c].sighashType)&&void 0!==n?n:k.Transaction.SIGHASH_ALL;l(this,e,"f")===w.CoinType.BITCOINCASH&&(a|=64);const o=[{pubkey:p,signature:P.encode(s[c],a)}];l(this,i,"f").updateInput(c,{partialSig:o})}else{const t=(0,b.taggedHash)("TapSighash",u),e=(0,b.toTweakedPublickey)(r[c]),n=s[c].slice(0,64);if(!(0,E.taprootVerify)(n,t,e))throw Error(`Signature Error #${c}`);const a=null!==(p=l(this,i,"f").inputs[c].sighashType)&&void 0!==p?p:k.Transaction.SIGHASH_DEFAULT;l(this,i,"f").inputs[c].partialSig=[{pubkey:e,signature:a===k.Transaction.SIGHASH_DEFAULT?n:Buffer.from([a,...n])}]}}return this}finalizeAllInputs(){if(l(this,i,"f").inputs.length<1)throw Error("utxo input cannot be empty");return l(this,i,"f").inputs.forEach(((t,s)=>{(0,S.checkForInput)(l(this,i,"f").inputs,s);const{script:r,scriptType:n}=I(t,l(this,e,"f"));if(!r)throw new Error(`No script found for input #${s}`);if(t.sighashType&&t.partialSig){const{partialSig:i,sighashType:e}=t;for(const t of i){const{hashType:i}=P.decode(t.signature);if(i!==e)throw new Error("Signature sighash does not match input sighash type")}}const{finalScriptSig:p,finalScriptWitness:a}=function(t,i){let e,s;const{signature:r,pubkey:n}=i[0];switch(t){case w.ScriptType.P2PKH:e=P.compile([r,n]);break;case w.ScriptType.P2SH_P2PKH:e=(()=>{const t=P.compile([r,n]),i=P.decompile(t),e={output:i[i.length-1],input:P.compile(i.slice(0,-1))};return P.compile([].concat(P.decompile(e.input),e.output))})();break;case w.ScriptType.P2SH_P2WPKH:s=(0,b.witnessStackToScriptWitness)([r,n]),e=(()=>{const t=Buffer.alloc(0),i=(0,m.Hash160)(n),e=P.compile([v.OPCODES.OP_0,i]);return P.compile([].concat(P.decompile(t),e))})();break;case w.ScriptType.P2WPKH:s=(0,b.witnessStackToScriptWitness)([r,n]);break;case w.ScriptType.P2TR:s=r}return{finalScriptSig:e,finalScriptWitness:s}}(n,t.partialSig);if(p&&l(this,i,"f").updateInput(s,{finalScriptSig:p}),a&&l(this,i,"f").updateInput(s,{finalScriptWitness:a}),!p&&!a)throw new Error(`Unknown error finalizing input #${s}`)})),this}extractTransaction(){const e=l(this,n,"f").clone();l(this,i,"f").inputs.forEach(((i,s)=>l(this,t,"m",c).call(this,e,s,i)));const s=l(this,i,"f").inputs.reduce(((t,i)=>t+i.witnessUtxo.value),0)-e.outs.reduce(((t,i)=>t+i.value),0),r=e.virtualSize();if(s<r)throw Error(`Transaction fee must >= ${r}, but got ${s}.`);return e}}function I(t,i){let e,s;const r=(0,b.getPayment)(i);if(t.witnessScript)e=t.witnessScript;else if(t.redeemScript)switch(e=t.redeemScript,s=r.classify(e),s){case w.ScriptType.P2PKH:s=w.ScriptType.P2SH_P2PKH;break;case w.ScriptType.P2WPKH:s=w.ScriptType.P2SH_P2WPKH}else e=t.witnessUtxo.script,s=r.classify(e);return{script:e,scriptType:s}}exports.SecuxPsbt=W,i=new WeakMap,e=new WeakMap,s=new WeakMap,r=new WeakMap,n=new WeakMap,p=new WeakMap,t=new WeakSet,a=function(t){if(l(this,p,"f")[t])return l(this,p,"f")[t];const s=l(this,i,"f").inputs[t],r=s.witnessUtxo,n=I(s,l(this,e,"f")).scriptType,a=function(t,i,e,s){let r;switch(i){case w.ScriptType.P2SH_P2PKH:case w.ScriptType.P2SH_P2WPKH:if(!e)throw Error("scriptPubkey is P2SH but redeemScript missing");r=e;break;default:r=t}if(!r)throw Error("cannot extract script");return r}(r.script,n,s.redeemScript,s.witnessScript);null==x||x.debug(`input #${t} script type: ${w.ScriptType[n]}`),null==x||x.debug(`script: ${a.toString("hex")}`);const o={type:n,scriptPubkey:a};return l(this,p,"f")[t]=o,o},o=function(s){var r,p;const o=l(this,i,"f").inputs[s],c=l(this,n,"f");let u=null!==(r=o.sighashType)&&void 0!==r?r:k.Transaction.SIGHASH_ALL;const h=(0,b.getSerializer)(l(this,e,"f"));void 0===o.witnessUtxo&&Error("Need a Utxo input item for signing");const f=o.witnessUtxo,{type:d,scriptPubkey:S}=l(this,t,"m",a).call(this,s);let y;switch(d){case w.ScriptType.P2WPKH:case w.ScriptType.P2SH_P2WPKH:case w.ScriptType.P2SH_P2PKH:null==x||x.debug(w.ScriptType[d]);const r=(0,b.getPayment)(l(this,e,"f")).p2pkh(l(this,e,"f"),{hash:S.slice(2)}).scriptPublickey;y=h.dataForWitnessV0(c,s,r,f.value,u);break;case w.ScriptType.P2TR:null==x||x.debug("p2tr"),u=null!==(p=o.sighashType)&&void 0!==p?p:k.Transaction.SIGHASH_DEFAULT,y=h.dataForWitnessV1(c,s,l(this,i,"f").inputs.map(((i,e)=>l(this,t,"m",a).call(this,e).scriptPubkey)),l(this,i,"f").inputs.map((t=>t.witnessUtxo.value)),u);break;default:l(this,e,"f")===w.CoinType.BITCOINCASH?(null==x||x.debug("bch using bip143"),y=h.dataForWitnessV0(c,s,S,f.value,64|u)):(null==x||x.debug("non-segwit"),y=h.dataForSignature(c,s,S,u))}return y},c=function(i,e,s){if(!s.finalScriptSig&&!s.finalScriptWitness)throw Error(`input#${e} not finalized.`);s.finalScriptSig&&(i.ins[e].script=s.finalScriptSig),s.finalScriptWitness&&(l(this,t,"m",a).call(this,e).type!==w.ScriptType.P2TR?i.ins[e].witness=(0,b.scriptWitnessToWitnessStack)(s.finalScriptWitness):i.ins[e].witness=[s.finalScriptWitness])},u=function(){const e=l(this,n,"f").clone();let s=0,r=2;return l(this,i,"f").inputs.forEach(((i,e)=>{var n;const{type:p}=l(this,t,"m",a).call(this,e);switch(p){case w.ScriptType.P2PKH:s+=107;break;case w.ScriptType.P2SH_P2PKH:break;case w.ScriptType.P2SH_P2WPKH:s+=23,r+=105,r+=2,r+=1;break;case w.ScriptType.P2WPKH:r+=105,r+=2,r+=1;break;case w.ScriptType.P2TR:const t=null!==(n=i.sighashType)&&void 0!==n?n:k.Transaction.SIGHASH_DEFAULT;r+=t===k.Transaction.SIGHASH_DEFAULT?64:65,r+=1,r+=1}})),e.virtualSize()+s+r/4};class ${constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){h.set(this,void 0),f(this,h,k.Transaction.fromBuffer(t),"f")}getInputOutputCounts(){return{inputCount:l(this,h,"f").ins.length,outputCount:l(this,h,"f").outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const i="string"==typeof t.hash?Buffer.from(Buffer.from(t.hash,"hex").reverse()):t.hash;l(this,h,"f").addInput(i,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");l(this,h,"f").addOutput(t.script,t.value,t.path)}toBuffer(){return l(this,h,"f").toBuffer()}get tx(){return l(this,h,"f")}}h=new WeakMap;
"use strict";var t,i,e,s,r,n,o,p,a,u,c,h,f=this&&this.__classPrivateFieldSet||function(t,i,e,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof i?t!==i||!r:!i.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(t,e):r?r.value=e:i.set(t,e),e},l=this&&this.__classPrivateFieldGet||function(t,i,e,s){if("a"===e&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof i?t!==i||!s:!i.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===e?s:"a"===e?s.call(t):s?s.value:i.get(t)};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SecuxPsbt=void 0;const d=require("./parser"),S=require("bip174/src/lib/utils"),g=require("secp256k1/elliptic"),y=require("hash.js"),P=require("./script"),w=require("@secux/utility"),b=require("./interface"),T=require("./utils"),m=require("./payment"),k=require("./transaction"),v=require("./coindef"),H=require("../../protocol-transaction/lib/protocol-transaction"),E=require("./bip340"),x=null===w.Logger||void 0===w.Logger?void 0:w.Logger.child({id:"psbt"});class W{constructor(p,a=new d.Psbtv2(new I)){t.add(this),i.set(this,void 0),e.set(this,void 0),s.set(this,void 0),r.set(this,[]),n.set(this,void 0),o.set(this,{}),f(this,i,a,"f"),f(this,e,p,"f"),f(this,s,(0,T.getPayment)(l(this,e,"f")),"f"),f(this,n,l(this,i,"f").globalMap.unsignedTx.tx,"f"),p===b.CoinType.BITCOINCASH&&(l(this,n,"f").version=1)}static FromBuffer(t,i){const e=d.Psbtv2.fromBuffer(t,(t=>new I(t)));return new W(i,e)}AddInput(t){var n;if(!(0,w.isSupportedCoin)(t.path))throw Error(`ArgumentError: unsupport bip32 path, got "${t.path}"`);const o={},p={},a=(0,T.getPublickey)(t.publickey),u=null!==(n=t.script)&&void 0!==n?n:(0,T.getDefaultScript)(t.path);switch(u){case b.ScriptType.P2PKH:o.witnessUtxo={script:l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:a}).scriptPublickey,value:t.satoshis};break;case b.ScriptType.P2SH_P2PKH:const r=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:a});p.redeemScript=r.scriptPublickey,o.witnessUtxo={script:l(this,s,"f").p2sh(l(this,e,"f"),r.redeemHash).scriptPublickey,value:t.satoshis};break;case b.ScriptType.P2SH_P2WPKH:const n=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:a});p.redeemScript=n.scriptPublickey,o.witnessUtxo={script:l(this,s,"f").p2sh(l(this,e,"f"),n.redeemHash).scriptPublickey,value:t.satoshis};break;case b.ScriptType.P2WPKH:o.witnessUtxo={script:l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:a}).scriptPublickey,value:t.satoshis};break;case b.ScriptType.P2TR:o.witnessUtxo={script:l(this,s,"f").p2tr(l(this,e,"f"),{publickey:a}).scriptPublickey,value:t.satoshis};break;default:throw Error(`ArgumentError: Invalid ScriptType of input#${l(this,i,"f").inputs.length}, got "${b.ScriptType[u]}"`)}if(t.txHex){const s=k.Transaction.fromBuffer(Buffer.from(t.txHex,"hex"));if((0,T.getSerializer)(l(this,e,"f")).getId(s)!==t.hash)throw Error(`UTXO hash for input #${l(this,i,"f").inputs.length} doesn't match the hash specified in the prevout`);const r=s.outs[t.vout];if(r.value!==t.satoshis)throw Error(`UTXO value for input #${l(this,i,"f").inputs.length} doesn't match the value specified in the prevout`);r.script.equals(o.witnessUtxo.script)||null==x||x.warn(`Input script generation error: ${r.script.toString("hex")}, got "${o.witnessUtxo.script}"`)}const c=Object.assign(Object.assign({hash:t.hash,index:t.vout},o),p);return l(this,i,"f").addInput(c),l(this,r,"f").push(t.path),this}AddInputs(t){for(const i of t)this.AddInput(i);return this}AddOutput(t){var r;let n,o,p,a=t.satoshis;if(n=(0,b.isOutuptScriptExtended)(t)){const t=(0,T.getPublickey)(n.publickey);p=n.path;const a=null!==(r=n.script)&&void 0!==r?r:(0,T.getDefaultScript)(p);let u,c;switch(a){case b.ScriptType.P2SH_P2WPKH:if(!n.path.startsWith("m/49'/"))throw Error("P2SH(...) should use m/49' path");u=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:t}).redeemHash,c=l(this,s,"f").p2sh(l(this,e,"f"),u),o=c.scriptPublickey;break;case b.ScriptType.P2SH_P2PKH:if(!n.path.startsWith("m/49'/"))throw Error("P2SH(...) should use m/49' path");u=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:t}).redeemHash,c=l(this,s,"f").p2sh(l(this,e,"f"),u),o=c.scriptPublickey;break;case b.ScriptType.P2PKH:if(!n.path.startsWith("m/44'/"))throw Error("P2PKH should use m/44' path");o=l(this,s,"f").p2pkh(l(this,e,"f"),{publickey:t}).scriptPublickey;break;case b.ScriptType.P2WPKH:if(!n.path.startsWith("m/84'/"))throw Error("P2WPKH should use m/84' path");o=l(this,s,"f").p2wpkh(l(this,e,"f"),{publickey:t}).scriptPublickey;break;case b.ScriptType.P2TR:if(!n.path.startsWith("m/86'/"))throw Error("P2TR should use m/86' path");o=l(this,s,"f").p2tr(l(this,e,"f"),{publickey:t}).scriptPublickey;break;default:throw Error(`ArgumentError: Invalid ScriptType of output#${l(this,i,"f").outputs.length}, got "${b.ScriptType[a]}"`)}}else if(n=(0,b.isOutputAddress)(t))o=l(this,s,"f").decode(l(this,e,"f"),n.address);else{if(!(n=(0,b.isOutuptScript)(t)))throw Error("Invalid parameter of output");o=Buffer.from(n.scriptHex,"hex")}return l(this,i,"f").addOutput({script:o,value:a,path:p}),this}AddOutputs(t){for(const i of t)this.AddOutput(i);return this}PrepareSign(s){if(s){const e=l(this,t,"m",c).call(this),r=Math.round(e*s);null==x||x.info(`Estimated fee is ${r}, with ${s} fee rates.`);const o=l(this,i,"f").inputs.reduce(((t,i)=>t+i.witnessUtxo.value),0),p=l(this,n,"f").outs[0].value,a=1===l(this,i,"f").outputs.length?0:l(this,n,"f").outs[1].value,u=o-p-a;if(u<r&&(null==x||x.warn(`Estimated fee is ${r}, but got ${u}.`)),u>r||u<e)if(0!==a){const t=o-p-r;if(t<0)throw Error(`Insufficient amount, expect ${p+r}, but got ${o}.`);l(this,n,"f").outs[1].value=t,null==x||x.info(`Modify change amount from ${a} to ${t}.`)}else{const t=o-r;if(t<0)throw Error(`Insufficient amount, expect at least ${r}, but got ${o}.`);l(this,n,"f").outs[0].value=t,null==x||x.info(`Modify spend amount from ${p} to ${t}.`)}}const{type:o}=l(this,t,"m",p).call(this,0),u=l(this,e,"f")!==b.CoinType.BITCOINCASH&&o===b.ScriptType.P2PKH?Buffer.alloc(0):Buffer.from([l(this,i,"f").outputs.length,...(0,w.BigIntToBuffer)(l(this,n,"f").outs[0].value,8),l(this,n,"f").outs[0].script.length,...l(this,n,"f").outs[0].script,...l(this,n,"f").outs.slice(1).reduce(((t,i)=>[...t,...(0,w.BigIntToBuffer)(i.value,8),...(0,w.buildPathBuffer)(i.path).pathBuffer]),[])]),h=l(this,i,"f").inputs.map(((i,e)=>{const s=l(this,t,"m",a).call(this,e);return null==x||x.debug(`tx data [${e}]: ${s.toString("hex")}`),s}));null==x||x.debug(`confirm data: ${u.toString("hex")}`);return{commandData:H.SecuxTransactionTool.signRawTransactionList(l(this,r,"f"),h,u),rawTx:l(this,i,"f").toHex()}}appendSignature(s,r){var n,o;if(s.length!==r.length)throw Error(`ArgumentError: each signature is correspond to one publickey, got ${s.length} signatures and ${r.length} publickeys`);for(let u=0;u<l(this,i,"f").inputs.length;u++){const c=l(this,t,"m",a).call(this,u);if(l(this,t,"m",p).call(this,u).type!==b.ScriptType.P2TR){const t=l(this,e,"f")===b.CoinType.GROESTL?Buffer.from((0,y.sha256)().update(c).digest()):Buffer.from((0,y.sha256)().update((0,y.sha256)().update(c).digest()).digest()),o=r[u];if(!g.ecdsaVerify(s[u],t,o))throw Error(`Signature Error #${u}`);let p=null!==(n=l(this,i,"f").inputs[u].sighashType)&&void 0!==n?n:k.Transaction.SIGHASH_ALL;l(this,e,"f")===b.CoinType.BITCOINCASH&&(p|=64);const a=[{pubkey:o,signature:P.encode(s[u],p)}];l(this,i,"f").updateInput(u,{partialSig:a})}else{const t=(0,T.taggedHash)("TapSighash",c),e=(0,T.toTweakedPublickey)(r[u]),n=s[u].slice(0,64);if(!(0,E.taprootVerify)(n,t,e))throw Error(`Signature Error #${u}`);const p=null!==(o=l(this,i,"f").inputs[u].sighashType)&&void 0!==o?o:k.Transaction.SIGHASH_DEFAULT;l(this,i,"f").inputs[u].partialSig=[{pubkey:e,signature:p===k.Transaction.SIGHASH_DEFAULT?n:Buffer.from([p,...n])}]}}return this}finalizeAllInputs(){if(l(this,i,"f").inputs.length<1)throw Error("utxo input cannot be empty");return l(this,i,"f").inputs.forEach(((t,s)=>{(0,S.checkForInput)(l(this,i,"f").inputs,s);const{script:r,scriptType:n}=$(t,l(this,e,"f"));if(!r)throw new Error(`No script found for input #${s}`);if(t.sighashType&&t.partialSig){const{partialSig:i,sighashType:e}=t;for(const t of i){const{hashType:i}=P.decode(t.signature);if(i!==e)throw new Error("Signature sighash does not match input sighash type")}}const{finalScriptSig:o,finalScriptWitness:p}=function(t,i){let e,s;const{signature:r,pubkey:n}=i[0];switch(t){case b.ScriptType.P2PKH:e=P.compile([r,n]);break;case b.ScriptType.P2SH_P2PKH:e=(()=>{const t=P.compile([r,n]),i=P.decompile(t),e={output:i[i.length-1],input:P.compile(i.slice(0,-1))};return P.compile([].concat(P.decompile(e.input),e.output))})();break;case b.ScriptType.P2SH_P2WPKH:s=(0,T.witnessStackToScriptWitness)([r,n]),e=(()=>{const t=Buffer.alloc(0),i=(0,m.Hash160)(n),e=P.compile([v.OPCODES.OP_0,i]);return P.compile([].concat(P.decompile(t),e))})();break;case b.ScriptType.P2WPKH:s=(0,T.witnessStackToScriptWitness)([r,n]);break;case b.ScriptType.P2TR:s=r}return{finalScriptSig:e,finalScriptWitness:s}}(n,t.partialSig);if(o&&l(this,i,"f").updateInput(s,{finalScriptSig:o}),p&&l(this,i,"f").updateInput(s,{finalScriptWitness:p}),!o&&!p)throw new Error(`Unknown error finalizing input #${s}`)})),this}extractTransaction(){const e=l(this,n,"f").clone();l(this,i,"f").inputs.forEach(((i,s)=>l(this,t,"m",u).call(this,e,s,i)));const s=l(this,i,"f").inputs.reduce(((t,i)=>t+i.witnessUtxo.value),0)-e.outs.reduce(((t,i)=>t+i.value),0),r=e.virtualSize();if(s<r)throw Error(`Transaction fee must >= ${r}, but got ${s}.`);return e}}function $(t,i){let e,s;const r=(0,T.getPayment)(i);if(t.witnessScript)e=t.witnessScript;else if(t.redeemScript)switch(e=t.redeemScript,s=r.classify(e),s){case b.ScriptType.P2PKH:s=b.ScriptType.P2SH_P2PKH;break;case b.ScriptType.P2WPKH:s=b.ScriptType.P2SH_P2WPKH}else e=t.witnessUtxo.script,s=r.classify(e);return{script:e,scriptType:s}}exports.SecuxPsbt=W,i=new WeakMap,e=new WeakMap,s=new WeakMap,r=new WeakMap,n=new WeakMap,o=new WeakMap,t=new WeakSet,p=function(t){if(l(this,o,"f")[t])return l(this,o,"f")[t];const s=l(this,i,"f").inputs[t],r=s.witnessUtxo,n=$(s,l(this,e,"f")).scriptType,p=function(t,i,e,s){let r;switch(i){case b.ScriptType.P2SH_P2PKH:case b.ScriptType.P2SH_P2WPKH:if(!e)throw Error("scriptPubkey is P2SH but redeemScript missing");r=e;break;default:r=t}if(!r)throw Error("cannot extract script");return r}(r.script,n,s.redeemScript,s.witnessScript);null==x||x.debug(`input #${t} script type: ${b.ScriptType[n]}`),null==x||x.debug(`script: ${p.toString("hex")}`);const a={type:n,scriptPubkey:p};return l(this,o,"f")[t]=a,a},a=function(s){var r,o;const a=l(this,i,"f").inputs[s],u=l(this,n,"f");let c=null!==(r=a.sighashType)&&void 0!==r?r:k.Transaction.SIGHASH_ALL;const h=(0,T.getSerializer)(l(this,e,"f"));void 0===a.witnessUtxo&&Error("Need a Utxo input item for signing");const f=a.witnessUtxo,{type:d,scriptPubkey:S}=l(this,t,"m",p).call(this,s);let g;switch(d){case b.ScriptType.P2WPKH:case b.ScriptType.P2SH_P2WPKH:case b.ScriptType.P2SH_P2PKH:null==x||x.debug(b.ScriptType[d]);const r=(0,T.getPayment)(l(this,e,"f")).p2pkh(l(this,e,"f"),{hash:S.slice(2)}).scriptPublickey;g=h.dataForWitnessV0(u,s,r,f.value,c);break;case b.ScriptType.P2TR:null==x||x.debug("p2tr"),c=null!==(o=a.sighashType)&&void 0!==o?o:k.Transaction.SIGHASH_DEFAULT,g=h.dataForWitnessV1(u,s,l(this,i,"f").inputs.map(((i,e)=>l(this,t,"m",p).call(this,e).scriptPubkey)),l(this,i,"f").inputs.map((t=>t.witnessUtxo.value)),c);break;default:l(this,e,"f")===b.CoinType.BITCOINCASH?(null==x||x.debug("bch using bip143"),g=h.dataForWitnessV0(u,s,S,f.value,64|c)):(null==x||x.debug("non-segwit"),g=h.dataForSignature(u,s,S,c))}return g},u=function(i,e,s){if(!s.finalScriptSig&&!s.finalScriptWitness)throw Error(`input#${e} not finalized.`);s.finalScriptSig&&(i.ins[e].script=s.finalScriptSig),s.finalScriptWitness&&(l(this,t,"m",p).call(this,e).type!==b.ScriptType.P2TR?i.ins[e].witness=(0,T.scriptWitnessToWitnessStack)(s.finalScriptWitness):i.ins[e].witness=[s.finalScriptWitness])},c=function(){const e=l(this,n,"f").clone();let s=0,r=2;return l(this,i,"f").inputs.forEach(((i,e)=>{const{type:n}=l(this,t,"m",p).call(this,e);s+=(0,T.getInScriptSize)(n);const o=(0,T.getWitnessSize)(n,i.sighashType);r+=(0,T.vectorSize)(o)})),e.virtualSize()+s+r/4};class I{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){h.set(this,void 0),f(this,h,k.Transaction.fromBuffer(t),"f")}getInputOutputCounts(){return{inputCount:l(this,h,"f").ins.length,outputCount:l(this,h,"f").outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const i="string"==typeof t.hash?Buffer.from(Buffer.from(t.hash,"hex").reverse()):t.hash;l(this,h,"f").addInput(i,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");l(this,h,"f").addOutput(t.script,t.value,t.path)}toBuffer(){return l(this,h,"f").toBuffer()}get tx(){return l(this,h,"f")}}h=new WeakMap;

@@ -10,2 +10,7 @@ /// <reference types="node" />

export declare function getSerializer(coin: CoinType): typeof Transaction;
export declare function getInScriptSize(type: ScriptType): number;
export declare function getWitnessSize(type: ScriptType, sighashType?: number): Array<number>;
export declare function getOutScriptSize(type: ScriptType): number;
export declare function sliceSize(size: number): number;
export declare function vectorSize(sizes: Array<number>): number;
export declare function witnessStackToScriptWitness(witness: Buffer[]): Buffer;

@@ -12,0 +17,0 @@ export declare function scriptWitnessToWitnessStack(buffer: Buffer): Buffer[];

@@ -1,1 +0,1 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedHash=exports.toTweakedPublickey=exports.getPublickey=exports.scriptWitnessToWitnessStack=exports.witnessStackToScriptWitness=exports.getSerializer=exports.getDefaultScript=exports.getPurpose=exports.getCoinType=exports.getPayment=void 0;const e=require("secp256k1/elliptic"),t=require("varuint-bitcoin"),r=require("./interface"),n=require("./payment"),o=require("./payment_bch"),c=require("./payment_grs"),i=require("./transaction"),s=require("./transaction_grs"),p=require("ow"),u=require("@secux/utility"),a=require("hash.js"),f=require("./bip340");function g(e){const t=e.match(/\d+/g),n=parseInt(t[1],10);for(let e=0;e<r.coinmap.length;e++)if(n===r.coinmap[e].coinType)return e;throw Error(`ArgumentError: unsupport cointype of BIP32 path, got ${e}`)}function y(t){(0,p.default)(t,p.default.any(u.ow_hexString,p.default.buffer));const r="string"==typeof t?Buffer.from(t,"hex"):t;if((0,p.default)(r,p.default.buffer.is((e=>33===e.length||65===e.length))),!e.publicKeyVerify(r))throw Error(`ArgumentError: invalid secp256k1 publickey, got "${r.toString("hex")}"`);return r}exports.getPayment=function(e){switch(e){case r.CoinType.BITCOINCASH:return o.PaymentBCH;case r.CoinType.GROESTL:return c.PaymentGRS;default:return n.PaymentBTC}},exports.getCoinType=g,exports.getPurpose=function(e){switch(e){case r.ScriptType.P2PKH:return 44;case r.ScriptType.P2SH_P2PKH:case r.ScriptType.P2SH_P2WPKH:return 49;case r.ScriptType.P2WPKH:return 84;case r.ScriptType.P2TR:return 86}throw Error(`ArgumentError: unsupport ScriptType, got ${e}`)},exports.getDefaultScript=function(e){const t=e.match(/\d+/g),n=parseInt(t[0],10),o=t[1]?g(e):r.CoinType.BITCOIN;switch(n){case 44:return r.ScriptType.P2PKH;case 49:return o!==r.CoinType.BITCOINCASH?r.ScriptType.P2SH_P2WPKH:r.ScriptType.P2SH_P2PKH;case 84:return r.ScriptType.P2WPKH;case 86:return r.ScriptType.P2TR}throw Error(`ArgumentError: unsupport purpose of path, got "${n}" from ${e}`)},exports.getSerializer=function(e){return e===r.CoinType.GROESTL?s.TransactionGRS:i.Transaction},exports.witnessStackToScriptWitness=function(e){let r=Buffer.allocUnsafe(0);const n=e=>{const n=r.length,o=t.encodingLength(e);r=Buffer.concat([r,Buffer.allocUnsafe(o)]),t.encode(e,r,n)};n(e.length);for(const t of e)n(t.length),r=Buffer.concat([r,Buffer.from(t)]);return r},exports.scriptWitnessToWitnessStack=function(e){let r=0;const n=()=>{const n=t.decode(e,r);return r+=t.decode.bytes,n},o=()=>{const t=n();return r+=t,e.slice(r-t,r)},c=n(),i=[];for(let e=0;e<c;e++)i.push(o());return i},exports.getPublickey=y,exports.toTweakedPublickey=function(e){const t=y(e).slice(1,33),r=l("TapTweak",t);return(0,f.taprootConvert)(t,r)};const T=Object.fromEntries(["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"].map((e=>{const t=function(e){return Buffer.from((0,a.sha256)().update(e).digest())}(e);return[e,Buffer.concat([t,t])]})));function l(e,t){const r=Buffer.concat([T[e],t]);return Buffer.from((0,a.sha256)().update(r).digest())}exports.taggedHash=l;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedHash=exports.toTweakedPublickey=exports.getPublickey=exports.scriptWitnessToWitnessStack=exports.witnessStackToScriptWitness=exports.vectorSize=exports.sliceSize=exports.getOutScriptSize=exports.getWitnessSize=exports.getInScriptSize=exports.getSerializer=exports.getDefaultScript=exports.getPurpose=exports.getCoinType=exports.getPayment=void 0;const e=require("secp256k1/elliptic"),t=require("varuint-bitcoin"),r=require("./interface"),n=require("./payment"),c=require("./payment_bch"),i=require("./payment_grs"),o=require("./transaction"),s=require("./transaction_grs"),p=require("ow"),u=require("@secux/utility"),a=require("hash.js"),f=require("./bip340");function S(e){const t=e.match(/\d+/g),n=parseInt(t[1],10);for(let e=0;e<r.coinmap.length;e++)if(n===r.coinmap[e].coinType)return e;throw Error(`ArgumentError: unsupport cointype of BIP32 path, got ${e}`)}function P(e){return t.encodingLength(e)+e}function T(t){(0,p.default)(t,p.default.any(u.ow_hexString,p.default.buffer));const r="string"==typeof t?Buffer.from(t,"hex"):t;if((0,p.default)(r,p.default.buffer.is((e=>33===e.length||65===e.length))),!e.publicKeyVerify(r))throw Error(`ArgumentError: invalid secp256k1 publickey, got "${r.toString("hex")}"`);return r}exports.getPayment=function(e){switch(e){case r.CoinType.BITCOINCASH:return c.PaymentBCH;case r.CoinType.GROESTL:return i.PaymentGRS;default:return n.PaymentBTC}},exports.getCoinType=S,exports.getPurpose=function(e){switch(e){case r.ScriptType.P2PKH:return 44;case r.ScriptType.P2SH_P2PKH:case r.ScriptType.P2SH_P2WPKH:return 49;case r.ScriptType.P2WPKH:return 84;case r.ScriptType.P2TR:return 86}throw Error(`ArgumentError: unsupport ScriptType, got ${e}`)},exports.getDefaultScript=function(e){const t=e.match(/\d+/g),n=parseInt(t[0],10),c=t[1]?S(e):r.CoinType.BITCOIN;switch(n){case 44:return r.ScriptType.P2PKH;case 49:return c!==r.CoinType.BITCOINCASH?r.ScriptType.P2SH_P2WPKH:r.ScriptType.P2SH_P2PKH;case 84:return r.ScriptType.P2WPKH;case 86:return r.ScriptType.P2TR}throw Error(`ArgumentError: unsupport purpose of path, got "${n}" from ${e}`)},exports.getSerializer=function(e){return e===r.CoinType.GROESTL?s.TransactionGRS:o.Transaction},exports.getInScriptSize=function(e){switch(e){case r.ScriptType.P2PKH:case r.ScriptType.P2SH_P2PKH:return 107;case r.ScriptType.P2SH_P2WPKH:return 23}return 0},exports.getWitnessSize=function(e,t=o.Transaction.SIGHASH_DEFAULT){switch(e){case r.ScriptType.P2SH_P2WPKH:case r.ScriptType.P2WPKH:return[72,33];case r.ScriptType.P2TR:return t===o.Transaction.SIGHASH_DEFAULT?[64]:[65]}return[]},exports.getOutScriptSize=function(e){switch(e){case r.ScriptType.P2PKH:return 25;case r.ScriptType.P2SH_P2PKH:case r.ScriptType.P2SH_P2WPKH:return 23;case r.ScriptType.P2WPKH:return 22;case r.ScriptType.P2TR:return 34}return 0},exports.sliceSize=P,exports.vectorSize=function(e){return t.encodingLength(e.length)+e.reduce(((e,t)=>e+P(t)),0)},exports.witnessStackToScriptWitness=function(e){let r=Buffer.allocUnsafe(0);const n=e=>{const n=r.length,c=t.encodingLength(e);r=Buffer.concat([r,Buffer.allocUnsafe(c)]),t.encode(e,r,n)};n(e.length);for(const t of e)n(t.length),r=Buffer.concat([r,Buffer.from(t)]);return r},exports.scriptWitnessToWitnessStack=function(e){let r=0;const n=()=>{const n=t.decode(e,r);return r+=t.decode.bytes,n},c=()=>{const t=n();return r+=t,e.slice(r-t,r)},i=n(),o=[];for(let e=0;e<i;e++)o.push(c());return o},exports.getPublickey=T,exports.toTweakedPublickey=function(e){const t=T(e).slice(1,33),r=y("TapTweak",t);return(0,f.taprootConvert)(t,r)};const g=Object.fromEntries(["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"].map((e=>{const t=function(e){return Buffer.from((0,a.sha256)().update(e).digest())}(e);return[e,Buffer.concat([t,t])]})));function y(e,t){const r=Buffer.concat([g[e],t]);return Buffer.from((0,a.sha256)().update(r).digest())}exports.taggedHash=y;
{
"name": "@secux/app-btc",
"version": "3.1.0",
"version": "3.1.1",
"description": "SecuX Hardware Wallet BTC API",

@@ -29,3 +29,2 @@ "keywords": [

"docs": "npx tsc && jsdoc2md --template ./README.hbs ./lib/app-btc.js > README.md",
"api-docs": "npx tsc && jsdoc2md --template ./api-docs.hbs ./lib/app-btc.js > app-btc.md",
"test:webusb": "webpack serve --progress --config ../../webpack.config.js --output-path ./__tests__ --entry ./__tests__/usb.js",

@@ -32,0 +31,0 @@ "test:webble": "webpack serve --progress --config ../../webpack.config.js --output-path ./__tests__ --entry ./__tests__/ble.js",

@@ -12,3 +12,3 @@ [![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lerna.js.org/)

```ts
import { SecuxBTC } from "@secux/app-btc";
import { SecuxBTC, ScriptType } from "@secux/app-btc";
```

@@ -171,2 +171,24 @@

5. Estimate transaction size
```ts
const size = SecuxBTC.getVirtualSize(
// your inputs
[
ScriptType.P2PKH,
ScriptType.P2SH_P2WPKH,
ScriptType.P2SH_P2WPKH,
ScriptType.P2WPKH,
...
],
// your outputs
[
ScriptType.P2PKH,
ScriptType.P2PKH,
ScriptType.P2WPKH,
...
]
);
```
# API Reference

@@ -189,2 +211,3 @@ BTC package for SecuX device

* [.deriveAddress(xpub, change, addressIndex, [option])](#SecuxBTC.deriveAddress) ⇒ <code>string</code>
* [.getVirtualSize(inputs, outputs)](#SecuxBTC.getVirtualSize) ⇒ <code>number</code>

@@ -336,4 +359,17 @@ <br/>

<br/>
<a name="SecuxBTC.getVirtualSize"></a>
### **SecuxBTC.getVirtualSize(inputs, outputs) ⇒ <code>number</code>**
*Estimate virtual size of transaction.*
**Returns**: <code>number</code> - virtual size
| Param | Type |
| --- | --- |
| inputs | <code>Array.&lt;ScriptType&gt;</code> |
| outputs | <code>Array.&lt;ScriptType&gt;</code> |
<br/>
<br/>
<a name="txInput"></a>

@@ -340,0 +376,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc