@atomicfinance/utils 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # @atomicfinance/utils
2
+
3
+ ## 3.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - a06082e: Create unified standalone `bitcoin-abstraction-layer` package
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [a06082e]
12
+ - @atomicfinance/types@3.0.0
13
+ - @atomicfinance/crypto@3.0.0
14
+ - @atomicfinance/errors@3.0.0
@@ -0,0 +1,37 @@
1
+ /// <reference types="node" />
2
+ import { Address, bitcoin as bT, Transaction } from '@atomicfinance/types';
3
+ import { BitcoinNetwork } from 'bitcoin-networks';
4
+ declare const AddressTypes: string[];
5
+ declare function calculateFee(numInputs: number, numOutputs: number, feePerByte: number): number;
6
+ /**
7
+ * Get compressed pubKey from pubKey.
8
+ * @param {!string} pubKey - 65 byte string with prefix, x, y.
9
+ * @return {string} Returns the compressed pubKey of uncompressed pubKey.
10
+ */
11
+ declare function compressPubKey(pubKey: string): string;
12
+ /**
13
+ * Get a network object from an address
14
+ * @param {string} address The bitcoin address
15
+ * @return {Network}
16
+ */
17
+ declare function getAddressNetwork(address: string): BitcoinNetwork;
18
+ declare type CoinSelectTarget = {
19
+ value: number;
20
+ script?: Buffer;
21
+ id?: string;
22
+ };
23
+ declare function selectCoins(utxos: bT.UTXO[], targets: CoinSelectTarget[], feePerByte: number, fixedInputs?: bT.UTXO[]): {
24
+ inputs: bT.UTXO[];
25
+ outputs: CoinSelectTarget[];
26
+ fee: number;
27
+ change: any;
28
+ };
29
+ declare function decodeRawTransaction(hex: string, network: BitcoinNetwork): bT.Transaction;
30
+ declare function normalizeTransactionObject(tx: bT.Transaction, fee: number, block?: {
31
+ number: number;
32
+ hash: string;
33
+ }): Transaction<bT.Transaction>;
34
+ declare function witnessStackToScriptWitness(witness: Buffer[]): Buffer;
35
+ declare function getPubKeyHash(address: string, network: BitcoinNetwork): Buffer;
36
+ declare function validateAddress(_address: Address | string, network: BitcoinNetwork): void;
37
+ export { calculateFee, compressPubKey, getAddressNetwork, CoinSelectTarget, selectCoins, decodeRawTransaction, normalizeTransactionObject, witnessStackToScriptWitness, AddressTypes, getPubKeyHash, validateAddress, };
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.validateAddress = exports.getPubKeyHash = exports.AddressTypes = exports.witnessStackToScriptWitness = exports.normalizeTransactionObject = exports.decodeRawTransaction = exports.selectCoins = exports.getAddressNetwork = exports.compressPubKey = exports.calculateFee = void 0;
26
+ const crypto_1 = require("@atomicfinance/crypto");
27
+ const errors_1 = require("@atomicfinance/errors");
28
+ const types_1 = require("@atomicfinance/types");
29
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
30
+ const varuint = __importStar(require("bip174/src/lib/converter/varint"));
31
+ const bitcoin_networks_1 = require("bitcoin-networks");
32
+ const bitcoin = __importStar(require("bitcoinjs-lib"));
33
+ const classify = __importStar(require("bitcoinjs-lib/src/classify"));
34
+ const coinselect_1 = __importDefault(require("coinselect"));
35
+ const accumulative_1 = __importDefault(require("coinselect/accumulative"));
36
+ const lodash_1 = require("lodash");
37
+ const _1 = require("./");
38
+ const AddressTypes = ['legacy', 'p2sh-segwit', 'bech32'];
39
+ exports.AddressTypes = AddressTypes;
40
+ function calculateFee(numInputs, numOutputs, feePerByte) {
41
+ return (numInputs * 148 + numOutputs * 34 + 10) * feePerByte;
42
+ }
43
+ exports.calculateFee = calculateFee;
44
+ /**
45
+ * Get compressed pubKey from pubKey.
46
+ * @param {!string} pubKey - 65 byte string with prefix, x, y.
47
+ * @return {string} Returns the compressed pubKey of uncompressed pubKey.
48
+ */
49
+ function compressPubKey(pubKey) {
50
+ const x = pubKey.substring(2, 66);
51
+ const y = pubKey.substring(66, 130);
52
+ const even = parseInt(y.substring(62, 64), 16) % 2 === 0;
53
+ const prefix = even ? '02' : '03';
54
+ return prefix + x;
55
+ }
56
+ exports.compressPubKey = compressPubKey;
57
+ /**
58
+ * Get a network object from an address
59
+ * @param {string} address The bitcoin address
60
+ * @return {Network}
61
+ */
62
+ function getAddressNetwork(address) {
63
+ // TODO: can this be simplified using just bitcoinjs-lib??
64
+ let networkKey;
65
+ // bech32
66
+ networkKey = lodash_1.findKey(bitcoin_networks_1.BitcoinNetworks, (network) => address.startsWith(network.bech32));
67
+ // base58
68
+ if (!networkKey) {
69
+ const prefix = crypto_1.base58.decode(address).toString('hex').substring(0, 2);
70
+ networkKey = lodash_1.findKey(bitcoin_networks_1.BitcoinNetworks, (network) => {
71
+ const pubKeyHashPrefix = crypto_1.padHexStart(network.pubKeyHash.toString(16), 1);
72
+ const scriptHashPrefix = crypto_1.padHexStart(network.scriptHash.toString(16), 1);
73
+ return [pubKeyHashPrefix, scriptHashPrefix].includes(prefix);
74
+ });
75
+ }
76
+ return bitcoin_networks_1.BitcoinNetworks[networkKey];
77
+ }
78
+ exports.getAddressNetwork = getAddressNetwork;
79
+ function selectCoins(utxos, targets, feePerByte, fixedInputs = []) {
80
+ let selectUtxos = utxos;
81
+ // Default coinselect won't accumulate some inputs
82
+ // TODO: does coinselect need to be modified to ABSOLUTELY not skip an input?
83
+ const coinselectStrat = fixedInputs.length
84
+ ? accumulative_1.default
85
+ : coinselect_1.default;
86
+ if (fixedInputs.length) {
87
+ selectUtxos = [
88
+ // Order fixed inputs to the start of the list so they are used
89
+ ...fixedInputs,
90
+ ...utxos.filter((utxo) => !fixedInputs.find((input) => input.vout === utxo.vout && input.txid === utxo.txid)),
91
+ ];
92
+ }
93
+ const { inputs, outputs, fee } = coinselectStrat(selectUtxos, targets, Math.ceil(feePerByte));
94
+ let change;
95
+ if (inputs && outputs) {
96
+ change = outputs.find((output) => output.id !== 'main');
97
+ }
98
+ return { inputs, outputs, fee, change };
99
+ }
100
+ exports.selectCoins = selectCoins;
101
+ const OUTPUT_TYPES_MAP = {
102
+ [classify.types.P2WPKH]: 'witness_v0_keyhash',
103
+ [classify.types.P2WSH]: 'witness_v0_scripthash',
104
+ };
105
+ function decodeRawTransaction(hex, network) {
106
+ const bjsTx = bitcoin.Transaction.fromHex(hex);
107
+ const vin = bjsTx.ins.map((input) => {
108
+ return {
109
+ txid: Buffer.from(input.hash).reverse().toString('hex'),
110
+ vout: input.index,
111
+ scriptSig: {
112
+ asm: bitcoin.script.toASM(input.script),
113
+ hex: input.script.toString('hex'),
114
+ },
115
+ txinwitness: input.witness.map((w) => w.toString('hex')),
116
+ sequence: input.sequence,
117
+ };
118
+ });
119
+ const vout = bjsTx.outs.map((output, n) => {
120
+ const type = classify.output(output.script);
121
+ const vout = {
122
+ value: output.value / 1e8,
123
+ n,
124
+ scriptPubKey: {
125
+ asm: bitcoin.script.toASM(output.script),
126
+ hex: output.script.toString('hex'),
127
+ reqSigs: 1,
128
+ type: OUTPUT_TYPES_MAP[type] || type,
129
+ addresses: [],
130
+ },
131
+ };
132
+ try {
133
+ const address = bitcoin.address.fromOutputScript(output.script, network);
134
+ vout.scriptPubKey.addresses.push(address);
135
+ }
136
+ catch (e) {
137
+ /** If output script is not parasable, we just skip it */
138
+ }
139
+ return vout;
140
+ });
141
+ return {
142
+ txid: bjsTx.getHash(false).reverse().toString('hex'),
143
+ hash: bjsTx.getHash(true).reverse().toString('hex'),
144
+ version: bjsTx.version,
145
+ locktime: bjsTx.locktime,
146
+ size: bjsTx.byteLength(),
147
+ vsize: bjsTx.virtualSize(),
148
+ weight: bjsTx.weight(),
149
+ vin,
150
+ vout,
151
+ hex,
152
+ };
153
+ }
154
+ exports.decodeRawTransaction = decodeRawTransaction;
155
+ function normalizeTransactionObject(tx, fee, block) {
156
+ const value = tx.vout.reduce((p, n) => p.plus(new bignumber_js_1.default(n.value).times(1e8)), new bignumber_js_1.default(0));
157
+ const result = {
158
+ hash: tx.txid,
159
+ value: value.toNumber(),
160
+ _raw: tx,
161
+ confirmations: 0,
162
+ status: tx.confirmations > 0 ? types_1.TxStatus.Success : types_1.TxStatus.Pending,
163
+ };
164
+ if (fee) {
165
+ const feePrice = Math.round(fee / tx.vsize);
166
+ Object.assign(result, {
167
+ fee,
168
+ feePrice,
169
+ });
170
+ }
171
+ if (block) {
172
+ Object.assign(result, {
173
+ blockHash: block.hash,
174
+ blockNumber: block.number,
175
+ confirmations: tx.confirmations,
176
+ });
177
+ }
178
+ return result;
179
+ }
180
+ exports.normalizeTransactionObject = normalizeTransactionObject;
181
+ // TODO: This is copy pasta because it's not exported from bitcoinjs-lib
182
+ // https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts#L477
183
+ function witnessStackToScriptWitness(witness) {
184
+ let buffer = Buffer.allocUnsafe(0);
185
+ function writeSlice(slice) {
186
+ buffer = Buffer.concat([buffer, Buffer.from(slice)]);
187
+ }
188
+ function writeVarInt(i) {
189
+ const currentLen = buffer.length;
190
+ const varintLen = varuint.encodingLength(i);
191
+ buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
192
+ varuint.encode(i, buffer, currentLen);
193
+ }
194
+ function writeVarSlice(slice) {
195
+ writeVarInt(slice.length);
196
+ writeSlice(slice);
197
+ }
198
+ function writeVector(vector) {
199
+ writeVarInt(vector.length);
200
+ vector.forEach(writeVarSlice);
201
+ }
202
+ writeVector(witness);
203
+ return buffer;
204
+ }
205
+ exports.witnessStackToScriptWitness = witnessStackToScriptWitness;
206
+ function getPubKeyHash(address, network) {
207
+ const outputScript = bitcoin.address.toOutputScript(address, network);
208
+ const type = classify.output(outputScript);
209
+ if (![classify.types.P2PKH, classify.types.P2WPKH].includes(type)) {
210
+ throw new Error(`Bitcoin swap doesn't support the address ${address} type of ${type}. Not possible to derive public key hash.`);
211
+ }
212
+ try {
213
+ const bech32 = bitcoin.address.fromBech32(address);
214
+ return bech32.data;
215
+ }
216
+ catch (e) {
217
+ const base58 = bitcoin.address.fromBase58Check(address);
218
+ return base58.hash;
219
+ }
220
+ }
221
+ exports.getPubKeyHash = getPubKeyHash;
222
+ function validateAddress(_address, network) {
223
+ const address = _1.addressToString(_address);
224
+ if (typeof address !== 'string') {
225
+ throw new errors_1.InvalidAddressError(`Invalid address: ${address}`);
226
+ }
227
+ let pubKeyHash;
228
+ try {
229
+ pubKeyHash = getPubKeyHash(address, network);
230
+ }
231
+ catch (e) {
232
+ throw new errors_1.InvalidAddressError(`Invalid Address. Failed to parse: ${address}`);
233
+ }
234
+ if (!pubKeyHash) {
235
+ throw new errors_1.InvalidAddressError(`Invalid Address: ${address}`);
236
+ }
237
+ }
238
+ exports.validateAddress = validateAddress;
239
+ //# sourceMappingURL=bitcoin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitcoin.js","sourceRoot":"","sources":["../lib/bitcoin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAA4D;AAC5D,kDAA4D;AAC5D,gDAK8B;AAC9B,gEAAqC;AACrC,yEAA2D;AAC3D,uDAAmE;AAC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A4C,OAAO,YAAY,IAAI,2CAA2C,CAC/G,CAAC;KACH;IAED,IAAI;QACF,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACnD,OAAO,MAAM,CAAC,IAAI,CAAC;KACpB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QACxD,OAAO,MAAM,CAAC,IAAI,CAAC;KACpB;AACH,CAAC;AAiCC,sCAAa;AA/Bf,SAAS,eAAe,CAAC,QAA0B,EAAE,OAAuB;IAC1E,MAAM,OAAO,GAAG,kBAAe,CAAC,QAAQ,CAAC,CAAC;IAE1C,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,4BAAmB,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;KAC9D;IAED,IAAI,UAAU,CAAC;IACf,IAAI;QACF,UAAU,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;KAC9C;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,IAAI,4BAAmB,CAC3B,qCAAqC,OAAO,EAAE,CAC/C,CAAC;KACH;IAED,IAAI,CAAC,UAAU,EAAE;QACf,MAAM,IAAI,4BAAmB,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;KAC9D;AACH,CAAC;AAaC,0CAAe"}
@@ -0,0 +1,12 @@
1
+ import 'setimmediate';
2
+ import { Address, BigNumber } from '@atomicfinance/types';
3
+ declare function addressToString(address: Address | string): string;
4
+ declare function sleep(ms: number): Promise<unknown>;
5
+ declare function asyncSetImmediate(): Promise<unknown>;
6
+ declare function caseInsensitiveEqual(left: string, right: string): boolean;
7
+ declare function validateValue(value: BigNumber): void;
8
+ declare function validateSecretHash(secretHash: string): void;
9
+ declare function validateSecret(secret: string): void;
10
+ declare function validateSecretAndHash(secret: string, secretHash: string): void;
11
+ declare function validateExpiration(expiration: number): void;
12
+ export { sleep, addressToString, asyncSetImmediate, caseInsensitiveEqual, validateValue, validateSecret, validateSecretHash, validateSecretAndHash, validateExpiration, };
package/dist/index.js ADDED
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateExpiration = exports.validateSecretAndHash = exports.validateSecretHash = exports.validateSecret = exports.validateValue = exports.caseInsensitiveEqual = exports.asyncSetImmediate = exports.addressToString = exports.sleep = void 0;
4
+ require("setimmediate");
5
+ const crypto_1 = require("@atomicfinance/crypto");
6
+ const errors_1 = require("@atomicfinance/errors");
7
+ const types_1 = require("@atomicfinance/types");
8
+ function addressToString(address) {
9
+ if (typeof address === 'string')
10
+ return address;
11
+ else
12
+ return address.address;
13
+ }
14
+ exports.addressToString = addressToString;
15
+ function sleep(ms) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+ exports.sleep = sleep;
19
+ function asyncSetImmediate() {
20
+ return new Promise((resolve) => setImmediate(resolve));
21
+ }
22
+ exports.asyncSetImmediate = asyncSetImmediate;
23
+ function caseInsensitiveEqual(left, right) {
24
+ left = left && left.toLowerCase();
25
+ right = right && right.toLowerCase();
26
+ return left === right;
27
+ }
28
+ exports.caseInsensitiveEqual = caseInsensitiveEqual;
29
+ function validateValue(value) {
30
+ if (!types_1.BigNumber.isBigNumber(value)) {
31
+ throw new Error(`Invalid value: ${value}`);
32
+ }
33
+ if (value.lte(0)) {
34
+ throw new Error(`Invalid value: ${value}`);
35
+ }
36
+ }
37
+ exports.validateValue = validateValue;
38
+ function validateSecretHash(secretHash) {
39
+ if (typeof secretHash !== 'string') {
40
+ throw new errors_1.InvalidSecretError(`Invalid secret hash type`);
41
+ }
42
+ if (Buffer.from(secretHash, 'hex').toString('hex') !== secretHash) {
43
+ throw new errors_1.InvalidSecretError(`Invalid secret hash. Not Hex.`);
44
+ }
45
+ if (Buffer.byteLength(secretHash, 'hex') !== 32) {
46
+ throw new errors_1.InvalidSecretError(`Invalid secret hash: ${secretHash}`);
47
+ }
48
+ if (crypto_1.sha256('0000000000000000000000000000000000000000000000000000000000000000') === secretHash) {
49
+ throw new errors_1.InvalidSecretError(`Invalid secret hash: ${secretHash}. Secret 0 detected.`);
50
+ }
51
+ }
52
+ exports.validateSecretHash = validateSecretHash;
53
+ function validateSecret(secret) {
54
+ if (typeof secret !== 'string') {
55
+ throw new errors_1.InvalidSecretError(`Invalid secret type`);
56
+ }
57
+ if (Buffer.from(secret, 'hex').toString('hex') !== secret) {
58
+ throw new errors_1.InvalidSecretError(`Invalid secret. Not Hex.`);
59
+ }
60
+ const secretBuff = Buffer.from(secret, 'hex');
61
+ if (secretBuff.length !== 32) {
62
+ throw new errors_1.InvalidSecretError(`Invalid secret size`);
63
+ }
64
+ }
65
+ exports.validateSecret = validateSecret;
66
+ function validateSecretAndHash(secret, secretHash) {
67
+ validateSecret(secret);
68
+ validateSecretHash(secretHash);
69
+ const computedSecretHash = Buffer.from(crypto_1.sha256(secret), 'hex');
70
+ if (!computedSecretHash.equals(Buffer.from(secretHash, 'hex'))) {
71
+ throw new errors_1.InvalidSecretError(`Invalid secret: Does not match expected secret hash: ${secretHash}`);
72
+ }
73
+ }
74
+ exports.validateSecretAndHash = validateSecretAndHash;
75
+ function validateExpiration(expiration) {
76
+ if (isNaN(expiration)) {
77
+ throw new errors_1.InvalidExpirationError(`Invalid expiration. NaN: ${expiration}`);
78
+ }
79
+ if (expiration < 500000000 || expiration > 5000000000000) {
80
+ throw new errors_1.InvalidExpirationError(`Invalid expiration. Out of bounds: ${expiration}`);
81
+ }
82
+ }
83
+ exports.validateExpiration = validateExpiration;
84
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;AAAA,wBAAsB;AAEtB,kDAA+C;AAC/C,kDAG+B;AAC/B,gDAA0D;AAE1D,SAAS,eAAe,CAAC,OAAyB;IAChD,IAAI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DAAwD,UAAU,EAAE,CACrE,CAAC;KACH;AACH,CAAC;AAsBC,sDAAqB;AApBvB,SAAS,kBAAkB,CAAC,UAAkB;IAC5C,IAAI,KAAK,CAAC,UAAU,CAAC,EAAE;QACrB,MAAM,IAAI,+BAAsB,CAAC,4BAA4B,UAAU,EAAE,CAAC,CAAC;KAC5E;IAED,IAAI,UAAU,GAAG,SAAS,IAAI,UAAU,GAAG,aAAa,EAAE;QACxD,MAAM,IAAI,+BAAsB,CAC9B,sCAAsC,UAAU,EAAE,CACnD,CAAC;KACH;AACH,CAAC;AAWC,gDAAkB"}
package/lib/bitcoin.ts ADDED
@@ -0,0 +1,309 @@
1
+ import { base58, padHexStart } from '@atomicfinance/crypto';
2
+ import { InvalidAddressError } from '@atomicfinance/errors';
3
+ import {
4
+ Address,
5
+ bitcoin as bT,
6
+ Transaction,
7
+ TxStatus,
8
+ } from '@atomicfinance/types';
9
+ import BigNumber from 'bignumber.js';
10
+ import * as varuint from 'bip174/src/lib/converter/varint';
11
+ import { BitcoinNetwork, BitcoinNetworks } from 'bitcoin-networks';
12
+ import * as bitcoin from 'bitcoinjs-lib';
13
+ import * as classify from 'bitcoinjs-lib/src/classify';
14
+ import coinselect from 'coinselect';
15
+ import coinselectAccumulative from 'coinselect/accumulative';
16
+ import { findKey } from 'lodash';
17
+
18
+ import { addressToString } from './';
19
+
20
+ const AddressTypes = ['legacy', 'p2sh-segwit', 'bech32'];
21
+
22
+ function calculateFee(
23
+ numInputs: number,
24
+ numOutputs: number,
25
+ feePerByte: number,
26
+ ) {
27
+ return (numInputs * 148 + numOutputs * 34 + 10) * feePerByte;
28
+ }
29
+
30
+ /**
31
+ * Get compressed pubKey from pubKey.
32
+ * @param {!string} pubKey - 65 byte string with prefix, x, y.
33
+ * @return {string} Returns the compressed pubKey of uncompressed pubKey.
34
+ */
35
+ function compressPubKey(pubKey: string) {
36
+ const x = pubKey.substring(2, 66);
37
+ const y = pubKey.substring(66, 130);
38
+ const even = parseInt(y.substring(62, 64), 16) % 2 === 0;
39
+ const prefix = even ? '02' : '03';
40
+
41
+ return prefix + x;
42
+ }
43
+
44
+ /**
45
+ * Get a network object from an address
46
+ * @param {string} address The bitcoin address
47
+ * @return {Network}
48
+ */
49
+ function getAddressNetwork(address: string) {
50
+ // TODO: can this be simplified using just bitcoinjs-lib??
51
+ let networkKey;
52
+ // bech32
53
+ networkKey = findKey(BitcoinNetworks, (network) =>
54
+ address.startsWith(network.bech32),
55
+ );
56
+ // base58
57
+ if (!networkKey) {
58
+ const prefix = base58.decode(address).toString('hex').substring(0, 2);
59
+ networkKey = findKey(BitcoinNetworks, (network) => {
60
+ const pubKeyHashPrefix = padHexStart(network.pubKeyHash.toString(16), 1);
61
+ const scriptHashPrefix = padHexStart(network.scriptHash.toString(16), 1);
62
+ return [pubKeyHashPrefix, scriptHashPrefix].includes(prefix);
63
+ });
64
+ }
65
+ return (BitcoinNetworks as { [key: string]: BitcoinNetwork })[networkKey];
66
+ }
67
+
68
+ type CoinSelectTarget = {
69
+ value: number;
70
+ script?: Buffer;
71
+ id?: string;
72
+ };
73
+
74
+ type CoinSelectResponse = {
75
+ inputs: bT.UTXO[];
76
+ outputs: CoinSelectTarget[];
77
+ change: CoinSelectTarget;
78
+ fee: number;
79
+ };
80
+
81
+ type CoinSelectFunction = (
82
+ utxos: bT.UTXO[],
83
+ targets: CoinSelectTarget[],
84
+ feePerByte: number,
85
+ ) => CoinSelectResponse;
86
+
87
+ function selectCoins(
88
+ utxos: bT.UTXO[],
89
+ targets: CoinSelectTarget[],
90
+ feePerByte: number,
91
+ fixedInputs: bT.UTXO[] = [],
92
+ ) {
93
+ let selectUtxos = utxos;
94
+
95
+ // Default coinselect won't accumulate some inputs
96
+ // TODO: does coinselect need to be modified to ABSOLUTELY not skip an input?
97
+ const coinselectStrat: CoinSelectFunction = fixedInputs.length
98
+ ? coinselectAccumulative
99
+ : coinselect;
100
+ if (fixedInputs.length) {
101
+ selectUtxos = [
102
+ // Order fixed inputs to the start of the list so they are used
103
+ ...fixedInputs,
104
+ ...utxos.filter(
105
+ (utxo) =>
106
+ !fixedInputs.find(
107
+ (input) => input.vout === utxo.vout && input.txid === utxo.txid,
108
+ ),
109
+ ),
110
+ ];
111
+ }
112
+
113
+ const { inputs, outputs, fee } = coinselectStrat(
114
+ selectUtxos,
115
+ targets,
116
+ Math.ceil(feePerByte),
117
+ );
118
+
119
+ let change;
120
+ if (inputs && outputs) {
121
+ change = outputs.find((output) => output.id !== 'main');
122
+ }
123
+
124
+ return { inputs, outputs, fee, change };
125
+ }
126
+
127
+ const OUTPUT_TYPES_MAP = {
128
+ [classify.types.P2WPKH]: 'witness_v0_keyhash',
129
+ [classify.types.P2WSH]: 'witness_v0_scripthash',
130
+ };
131
+
132
+ function decodeRawTransaction(
133
+ hex: string,
134
+ network: BitcoinNetwork,
135
+ ): bT.Transaction {
136
+ const bjsTx = bitcoin.Transaction.fromHex(hex);
137
+
138
+ const vin = bjsTx.ins.map((input) => {
139
+ return <bT.Input>{
140
+ txid: Buffer.from(input.hash).reverse().toString('hex'),
141
+ vout: input.index,
142
+ scriptSig: {
143
+ asm: bitcoin.script.toASM(input.script),
144
+ hex: input.script.toString('hex'),
145
+ },
146
+ txinwitness: input.witness.map((w) => w.toString('hex')),
147
+ sequence: input.sequence,
148
+ };
149
+ });
150
+
151
+ const vout = bjsTx.outs.map((output, n) => {
152
+ const type = classify.output(output.script);
153
+
154
+ const vout: bT.Output = {
155
+ value: output.value / 1e8,
156
+ n,
157
+ scriptPubKey: {
158
+ asm: bitcoin.script.toASM(output.script),
159
+ hex: output.script.toString('hex'),
160
+ reqSigs: 1, // TODO: not sure how to derive this
161
+ type: OUTPUT_TYPES_MAP[type] || type,
162
+ addresses: [],
163
+ },
164
+ };
165
+
166
+ try {
167
+ const address = bitcoin.address.fromOutputScript(output.script, network);
168
+ vout.scriptPubKey.addresses.push(address);
169
+ } catch (e) {
170
+ /** If output script is not parasable, we just skip it */
171
+ }
172
+
173
+ return vout;
174
+ });
175
+
176
+ return {
177
+ txid: bjsTx.getHash(false).reverse().toString('hex'),
178
+ hash: bjsTx.getHash(true).reverse().toString('hex'),
179
+ version: bjsTx.version,
180
+ locktime: bjsTx.locktime,
181
+ size: bjsTx.byteLength(),
182
+ vsize: bjsTx.virtualSize(),
183
+ weight: bjsTx.weight(),
184
+ vin,
185
+ vout,
186
+ hex,
187
+ };
188
+ }
189
+
190
+ function normalizeTransactionObject(
191
+ tx: bT.Transaction,
192
+ fee: number,
193
+ block?: { number: number; hash: string },
194
+ ): Transaction<bT.Transaction> {
195
+ const value = tx.vout.reduce(
196
+ (p, n) => p.plus(new BigNumber(n.value).times(1e8)),
197
+ new BigNumber(0),
198
+ );
199
+ const result = {
200
+ hash: tx.txid,
201
+ value: value.toNumber(),
202
+ _raw: tx,
203
+ confirmations: 0,
204
+ status: tx.confirmations > 0 ? TxStatus.Success : TxStatus.Pending,
205
+ };
206
+
207
+ if (fee) {
208
+ const feePrice = Math.round(fee / tx.vsize);
209
+ Object.assign(result, {
210
+ fee,
211
+ feePrice,
212
+ });
213
+ }
214
+
215
+ if (block) {
216
+ Object.assign(result, {
217
+ blockHash: block.hash,
218
+ blockNumber: block.number,
219
+ confirmations: tx.confirmations,
220
+ });
221
+ }
222
+
223
+ return result;
224
+ }
225
+
226
+ // TODO: This is copy pasta because it's not exported from bitcoinjs-lib
227
+ // https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts#L477
228
+ function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
229
+ let buffer = Buffer.allocUnsafe(0);
230
+
231
+ function writeSlice(slice: Buffer): void {
232
+ buffer = Buffer.concat([buffer, Buffer.from(slice)]);
233
+ }
234
+
235
+ function writeVarInt(i: number): void {
236
+ const currentLen = buffer.length;
237
+ const varintLen = varuint.encodingLength(i);
238
+
239
+ buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
240
+ varuint.encode(i, buffer, currentLen);
241
+ }
242
+
243
+ function writeVarSlice(slice: Buffer): void {
244
+ writeVarInt(slice.length);
245
+ writeSlice(slice);
246
+ }
247
+
248
+ function writeVector(vector: Buffer[]): void {
249
+ writeVarInt(vector.length);
250
+ vector.forEach(writeVarSlice);
251
+ }
252
+
253
+ writeVector(witness);
254
+
255
+ return buffer;
256
+ }
257
+
258
+ function getPubKeyHash(address: string, network: BitcoinNetwork) {
259
+ const outputScript = bitcoin.address.toOutputScript(address, network);
260
+ const type = classify.output(outputScript);
261
+ if (![classify.types.P2PKH, classify.types.P2WPKH].includes(type)) {
262
+ throw new Error(
263
+ `Bitcoin swap doesn't support the address ${address} type of ${type}. Not possible to derive public key hash.`,
264
+ );
265
+ }
266
+
267
+ try {
268
+ const bech32 = bitcoin.address.fromBech32(address);
269
+ return bech32.data;
270
+ } catch (e) {
271
+ const base58 = bitcoin.address.fromBase58Check(address);
272
+ return base58.hash;
273
+ }
274
+ }
275
+
276
+ function validateAddress(_address: Address | string, network: BitcoinNetwork) {
277
+ const address = addressToString(_address);
278
+
279
+ if (typeof address !== 'string') {
280
+ throw new InvalidAddressError(`Invalid address: ${address}`);
281
+ }
282
+
283
+ let pubKeyHash;
284
+ try {
285
+ pubKeyHash = getPubKeyHash(address, network);
286
+ } catch (e) {
287
+ throw new InvalidAddressError(
288
+ `Invalid Address. Failed to parse: ${address}`,
289
+ );
290
+ }
291
+
292
+ if (!pubKeyHash) {
293
+ throw new InvalidAddressError(`Invalid Address: ${address}`);
294
+ }
295
+ }
296
+
297
+ export {
298
+ calculateFee,
299
+ compressPubKey,
300
+ getAddressNetwork,
301
+ CoinSelectTarget,
302
+ selectCoins,
303
+ decodeRawTransaction,
304
+ normalizeTransactionObject,
305
+ witnessStackToScriptWitness,
306
+ AddressTypes,
307
+ getPubKeyHash,
308
+ validateAddress,
309
+ };
package/lib/index.ts ADDED
@@ -0,0 +1,113 @@
1
+ import 'setimmediate';
2
+
3
+ import { sha256 } from '@atomicfinance/crypto';
4
+ import {
5
+ InvalidExpirationError,
6
+ InvalidSecretError,
7
+ } from '@atomicfinance/errors';
8
+ import { Address, BigNumber } from '@atomicfinance/types';
9
+
10
+ function addressToString(address: Address | string): string {
11
+ if (typeof address === 'string') return address;
12
+ else return address.address;
13
+ }
14
+
15
+ function sleep(ms: number) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+
19
+ function asyncSetImmediate() {
20
+ return new Promise((resolve) => setImmediate(resolve));
21
+ }
22
+
23
+ function caseInsensitiveEqual(left: string, right: string) {
24
+ left = left && left.toLowerCase();
25
+ right = right && right.toLowerCase();
26
+
27
+ return left === right;
28
+ }
29
+
30
+ function validateValue(value: BigNumber) {
31
+ if (!BigNumber.isBigNumber(value)) {
32
+ throw new Error(`Invalid value: ${value}`);
33
+ }
34
+
35
+ if (value.lte(0)) {
36
+ throw new Error(`Invalid value: ${value}`);
37
+ }
38
+ }
39
+
40
+ function validateSecretHash(secretHash: string) {
41
+ if (typeof secretHash !== 'string') {
42
+ throw new InvalidSecretError(`Invalid secret hash type`);
43
+ }
44
+
45
+ if (Buffer.from(secretHash, 'hex').toString('hex') !== secretHash) {
46
+ throw new InvalidSecretError(`Invalid secret hash. Not Hex.`);
47
+ }
48
+
49
+ if (Buffer.byteLength(secretHash, 'hex') !== 32) {
50
+ throw new InvalidSecretError(`Invalid secret hash: ${secretHash}`);
51
+ }
52
+
53
+ if (
54
+ sha256(
55
+ '0000000000000000000000000000000000000000000000000000000000000000',
56
+ ) === secretHash
57
+ ) {
58
+ throw new InvalidSecretError(
59
+ `Invalid secret hash: ${secretHash}. Secret 0 detected.`,
60
+ );
61
+ }
62
+ }
63
+
64
+ function validateSecret(secret: string) {
65
+ if (typeof secret !== 'string') {
66
+ throw new InvalidSecretError(`Invalid secret type`);
67
+ }
68
+
69
+ if (Buffer.from(secret, 'hex').toString('hex') !== secret) {
70
+ throw new InvalidSecretError(`Invalid secret. Not Hex.`);
71
+ }
72
+
73
+ const secretBuff = Buffer.from(secret, 'hex');
74
+ if (secretBuff.length !== 32) {
75
+ throw new InvalidSecretError(`Invalid secret size`);
76
+ }
77
+ }
78
+
79
+ function validateSecretAndHash(secret: string, secretHash: string) {
80
+ validateSecret(secret);
81
+ validateSecretHash(secretHash);
82
+
83
+ const computedSecretHash = Buffer.from(sha256(secret), 'hex');
84
+ if (!computedSecretHash.equals(Buffer.from(secretHash, 'hex'))) {
85
+ throw new InvalidSecretError(
86
+ `Invalid secret: Does not match expected secret hash: ${secretHash}`,
87
+ );
88
+ }
89
+ }
90
+
91
+ function validateExpiration(expiration: number) {
92
+ if (isNaN(expiration)) {
93
+ throw new InvalidExpirationError(`Invalid expiration. NaN: ${expiration}`);
94
+ }
95
+
96
+ if (expiration < 500000000 || expiration > 5000000000000) {
97
+ throw new InvalidExpirationError(
98
+ `Invalid expiration. Out of bounds: ${expiration}`,
99
+ );
100
+ }
101
+ }
102
+
103
+ export {
104
+ sleep,
105
+ addressToString,
106
+ asyncSetImmediate,
107
+ caseInsensitiveEqual,
108
+ validateValue,
109
+ validateSecret,
110
+ validateSecretHash,
111
+ validateSecretAndHash,
112
+ validateExpiration,
113
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@atomicfinance/utils",
3
+ "version": "3.0.0",
4
+ "description": "",
5
+ "module": "dist/index.js",
6
+ "main": "dist/index.js",
7
+ "directories": {
8
+ "dist": "dist",
9
+ "src": "lib"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "lib"
14
+ ],
15
+ "scripts": {
16
+ "build": "../../node_modules/.bin/tsc --project tsconfig.json",
17
+ "lint": "../../node_modules/.bin/eslint --ignore-path ../../.eslintignore -c ../../.eslintrc.js .",
18
+ "lint:fix": "../../node_modules/.bin/eslint --fix --ignore-path ../../.eslintignore -c ../../.eslintrc.js ."
19
+ },
20
+ "author": "Atomic Finance <info@atomic.finance>",
21
+ "license": "MIT",
22
+ "engines": {
23
+ "node": ">=14"
24
+ },
25
+ "dependencies": {
26
+ "@atomicfinance/crypto": "^3.0.0",
27
+ "@atomicfinance/errors": "^3.0.0",
28
+ "@atomicfinance/types": "^3.0.0",
29
+ "@babel/runtime": "^7.12.1",
30
+ "bignumber.js": "^9.0.0",
31
+ "bip174": "^2.0.1",
32
+ "bitcoin-networks": "^1.0.0",
33
+ "bitcoinjs-lib": "^5.2.0",
34
+ "coinselect": "^3.1.11",
35
+ "lodash": "^4.17.20",
36
+ "setimmediate": "^1.0.5"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "sideEffects": false
42
+ }