diff --git a/package.json b/package.json index 2e9b98a..385b381 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { - "name": "bitkey", - "version": "0.0.0-development", + "name": "@contco/bitkey", + "version": "0.0.1", "description": "bitkey is the bitcoin key management package", "main": "./lib/src/index.js", "files": [ @@ -16,11 +16,12 @@ "semantic-release": "semantic-release", "test:watch": "jest --watch", "test": "jest --coverage", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test:build": "run-s build" }, "repository": { "type": "git", - "url": "git+https://github.com/contco/bitkey.git" + "url": "https://github.com/contco/bitkey.git" }, "license": "MIT", "author": { @@ -59,9 +60,12 @@ "ts-node": "^10.2.1", "typescript": "^4.2.4" }, + "publishConfig": { + "registry": "https://npm.pkg.github.com/" + }, "config": { "commitizen": { - "path": "./node_modules/@ryansonshine/cz-conventional-changelog" + "path": "node_modules/cz-conventional-changelog" } }, "lint-staged": { diff --git a/src/.eslintrc b/src/.eslintrc deleted file mode 100644 index e69de29..0000000 diff --git a/src/address.js b/src/address.ts similarity index 92% rename from src/address.js rename to src/address.ts index ead78aa..7fbb5b0 100644 --- a/src/address.js +++ b/src/address.ts @@ -1,3 +1,5 @@ +/* eslint-disable */ + 'use strict'; var _ = require('lodash'); @@ -49,11 +51,13 @@ var PublicKey = require('./publickey'); * @returns {Address} A new valid and frozen instance of an Address * @constructor */ -function Address(data, network, type, multisigType) { +export const Address:any = (data:any, network:networkType, type:string, multisigType:string) =>{ + const self: any = this; + /* jshint maxcomplexity: 12 */ /* jshint maxstatements: 20 */ - if (!(this instanceof Address)) { + if (!(self instanceof Address)) { return new Address(data, network, type); } @@ -81,7 +85,7 @@ function Address(data, network, type, multisigType) { throw new TypeError('Third argument must be "pubkeyhash", "scripthash", "witnesspubkeyhash", "witnessscripthash", or "taproot".'); } - var info = this._classifyArguments(data, network, type); + var info = self._classifyArguments(data, network, type); // set defaults if not set info.network = info.network || Networks.get(network) || Networks.defaultNetwork; @@ -103,7 +107,7 @@ function Address(data, network, type, multisigType) { * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Object} An "info" object with "type", "network", and "hashBuffer" */ -Address.prototype._classifyArguments = function(data, network, type) { +Address.prototype._classifyArguments = function(data:any, network:networkType, type:string) { /* jshint maxcomplexity: 10 */ // transform and validate input data if ((data instanceof Buffer || data instanceof Uint8Array) && (data.length === 20 || data.length === 32)) { @@ -141,8 +145,8 @@ Address.PayToTaproot = 'taproot'; * @returns {Object} An object with keys: hashBuffer * @private */ -Address._transformHash = function(hash, network, type) { - var info = {}; +Address._transformHash = function(hash:any, network:networkType, type:string) { + var info:any = {}; if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) { throw new TypeError('Address supplied is not a buffer.'); } @@ -163,7 +167,7 @@ Address._transformHash = function(hash, network, type) { * @param {Network=} data.network - the name of the network associated * @return {Address} */ -Address._transformObject = function(data) { +Address._transformObject = function(data:any) { $.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property'); $.checkArgument(data.type, 'Must provide a `type` property'); return { @@ -180,8 +184,8 @@ Address._transformObject = function(data) { * @returns {Object} An object with keys: network and type * @private */ -Address._classifyFromVersion = function(buffer) { - var version = {}; +Address._classifyFromVersion = function(buffer:Buffer) { + var version:any = {}; if (buffer.length > 21) { var info = Bech32.decode(buffer.toString('utf8')); @@ -232,9 +236,9 @@ Address._classifyFromVersion = function(buffer) { * @returns {Object} An object with keys: hashBuffer, network and type * @private */ -Address._transformBuffer = function(buffer, network, type) { +Address._transformBuffer = function(buffer:any, network:networkType, type:string) { /* jshint maxcomplexity: 9 */ - var info = {}; + var info:any = {}; if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) { throw new TypeError('Address supplied is not a buffer.'); } @@ -276,8 +280,8 @@ Address._transformBuffer = function(buffer, network, type) { * @returns {Object} An object with keys: hashBuffer, type * @private */ -Address._transformPublicKey = function(pubkey, network, type) { - var info = {}; +Address._transformPublicKey = function(pubkey:any, network:networkType, type:string) { + var info:any = {}; if (!(pubkey instanceof PublicKey)) { throw new TypeError('Address must be an instance of PublicKey.'); } @@ -305,7 +309,7 @@ Address._transformPublicKey = function(pubkey, network, type) { * @returns {Object} An object with keys: hashBuffer, type * @private */ -Address._transformScript = function(script, network) { +Address._transformScript = function(script:any, network:networkType) { $.checkArgument(script instanceof Script, 'script must be a Script instance'); var info = script.getAddressInfo(network); if (!info) { @@ -328,7 +332,7 @@ Address._transformScript = function(script, network) { * @param {string} type - Either 'scripthash' or 'witnessscripthash'. If nestedWitness is set, then this is ignored * @return {Address} */ -Address.createMultisig = function(publicKeys, threshold, network, nestedWitness, type) { +Address.createMultisig = function(publicKeys:any, threshold:number, network:networkType, nestedWitness:boolean, type:string) { network = network || publicKeys[0].network || Networks.defaultNetwork; if (type && type !== Address.PayToScriptHash && type !== Address.PayToWitnessScriptHash) { throw new TypeError('Type must be either scripthash or witnessscripthash to create multisig.'); @@ -357,7 +361,7 @@ Address.createMultisig = function(publicKeys, threshold, network, nestedWitness, * @returns {Object} An object with keys: hashBuffer, network and type * @private */ -Address._transformString = function(data, network, type) { +Address._transformString = function(data:string, network:networkType, type:string) { if (typeof(data) !== 'string') { throw new TypeError('data parameter supplied is not a string.'); } @@ -394,7 +398,7 @@ Address._transformString = function(data, network, type) { * @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromPublicKey = function(data, network, type) { +Address.fromPublicKey = function(data:any, network:networkType, type:string) { var info = Address._transformPublicKey(data, network, type); network = network || Networks.defaultNetwork; return new Address(info.hashBuffer, network, info.type); @@ -407,7 +411,7 @@ Address.fromPublicKey = function(data, network, type) { * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromPublicKeyHash = function(hash, network) { +Address.fromPublicKeyHash = function(hash:any, network:networkType) { var info = Address._transformHash(hash); return new Address(info.hashBuffer, network, Address.PayToPublicKeyHash); }; @@ -420,7 +424,7 @@ Address.fromPublicKeyHash = function(hash, network) { * @param {string} type - Either 'scripthash' or 'witnessscripthash' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromScriptHash = function(hash, network, type) { +Address.fromScriptHash = function(hash:any, network:networkType, type:any) { $.checkArgument(hash, 'hash parameter is required'); var info = Address._transformHash(hash); if (type === Address.PayToWitnessScriptHash && hash.length !== 32) { @@ -441,7 +445,7 @@ Address.fromScriptHash = function(hash, network, type) { * @param {string} type - Either 'scripthash' or 'witnessscripthash' * @returns {Address} A new valid and frozen instance of an Address */ -Address.payingTo = function(script, network, type) { +Address.payingTo = function(script:any, network:networkType, type:any) { $.checkArgument(script, 'script is required'); $.checkArgument(script instanceof Script, 'script must be instance of Script'); var hash; @@ -466,7 +470,7 @@ Address.payingTo = function(script, network, type) { * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromScript = function(script, network) { +Address.fromScript = function(script:any, network:networkType) { $.checkArgument(script instanceof Script, 'script must be a Script instance'); var info = Address._transformScript(script, network); return new Address(info.hashBuffer, network, info.type); @@ -480,7 +484,7 @@ Address.fromScript = function(script, network) { * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromBuffer = function(buffer, network, type) { +Address.fromBuffer = function(buffer:Buffer, network:networkType, type:string) { var info = Address._transformBuffer(buffer, network, type); return new Address(info.hashBuffer, info.network, info.type); }; @@ -493,7 +497,7 @@ Address.fromBuffer = function(buffer, network, type) { * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Address} A new valid and frozen instance of an Address */ -Address.fromString = function(str, network, type) { +Address.fromString = function(str:string, network:networkType, type:string) { var info = Address._transformString(str, network, type); return new Address(info.hashBuffer, info.network, info.type); }; @@ -504,7 +508,7 @@ Address.fromString = function(str, network, type) { * @param {string} json - An JSON string or Object with keys: hash, network and type * @returns {Address} A new valid instance of an Address */ -Address.fromObject = function fromObject(obj) { +Address.fromObject = function fromObject(obj:any){ $.checkState( JSUtil.isHexa(obj.hash), 'Unexpected hash property, "' + obj.hash + '", expected to be hex.' @@ -527,7 +531,7 @@ Address.fromObject = function fromObject(obj) { * @param {string} type - The type of address: 'script' or 'pubkey' * @returns {null|Error} The corresponding error message */ -Address.getValidationError = function(data, network, type) { +Address.getValidationError = function(data:string, network:networkType, type:string) { var error; try { /* jshint nonew: false */ @@ -551,7 +555,7 @@ Address.getValidationError = function(data, network, type) { * @param {string} type - The type of address: 'script' or 'pubkey' * @returns {boolean} The corresponding error message */ -Address.isValid = function(data, network, type) { +Address.isValid = function(data:string, network:networkType, type:string) { return !Address.getValidationError(data, network, type); }; @@ -647,6 +651,5 @@ Address.prototype.inspect = function() { return ''; }; -module.exports = Address; var Script = require('./script'); diff --git a/src/hdprivatekey.js b/src/hdprivatekey.ts similarity index 64% rename from src/hdprivatekey.js rename to src/hdprivatekey.ts index 8fc3f6c..c03b17a 100644 --- a/src/hdprivatekey.js +++ b/src/hdprivatekey.ts @@ -1,29 +1,29 @@ -'use strict'; - - -var assert = require('assert'); -var buffer = require('buffer'); -var _ = require('lodash'); -var $ = require('./util/preconditions'); - -var BN = require('./crypto/bn'); -var Base58 = require('./encoding/base58'); -var Base58Check = require('./encoding/base58check'); -var Hash = require('./crypto/hash'); -var Network = require('./networks'); -var Point = require('./crypto/point'); -var PrivateKey = require('./privatekey'); -var Random = require('./crypto/random'); - -var errors = require('./errors'); -var hdErrors = errors.HDPrivateKey; -var BufferUtil = require('./util/buffer'); -var JSUtil = require('./util/js'); +/* eslint-disable */ -var MINIMUM_ENTROPY_BITS = 128; -var BITS_TO_BYTES = 1 / 8; -var MAXIMUM_ENTROPY_BITS = 512; +'use strict'; +const assert = require('assert'); +const buffer = require('buffer'); +const _ = require('lodash'); +const $ = require('./util/preconditions'); + +const BN = require('./crypto/bn'); +const Base58 = require('./encoding/base58'); +const Base58Check = require('./encoding/base58check'); +const Hash = require('./crypto/hash'); +const Network = require('./networks'); +const Point = require('./crypto/point'); +const PrivateKey = require('./privatekey'); +const Random = require('./crypto/random'); + +const errors = require('./errors'); +const hdErrors = errors.HDPrivateKey; +const BufferUtil = require('./util/buffer'); +const JSUtil = require('./util/js'); + +const MINIMUM_ENTROPY_BITS = 128; +const BITS_TO_BYTES = 1 / 8; +const MAXIMUM_ENTROPY_BITS = 512; /** * Represents an instance of an hierarchically derived private key. @@ -33,36 +33,41 @@ var MAXIMUM_ENTROPY_BITS = 512; * @constructor * @param {string|Buffer|Object} arg */ -function HDPrivateKey(arg) { +export const HDPrivateKey: any = (arg: any) => { + const self: any = this; + /* jshint maxcomplexity: 10 */ if (arg instanceof HDPrivateKey) { return arg; } - if (!(this instanceof HDPrivateKey)) { + if (!(self instanceof HDPrivateKey)) { return new HDPrivateKey(arg); } if (!arg) { - return this._generateRandomly(); + return self._generateRandomly(); } if (Network.get(arg)) { - return this._generateRandomly(arg); + return self._generateRandomly(arg); } else if (_.isString(arg) || BufferUtil.isBuffer(arg)) { if (HDPrivateKey.isValidSerialized(arg)) { - this._buildFromSerialized(arg); + self._buildFromSerialized(arg); } else if (JSUtil.isValidJSON(arg)) { - this._buildFromJSON(arg); - } else if (BufferUtil.isBuffer(arg) && HDPrivateKey.isValidSerialized(arg.toString())) { - this._buildFromSerialized(arg.toString()); + self._buildFromJSON(arg); + } else if ( + BufferUtil.isBuffer(arg) && + HDPrivateKey.isValidSerialized(arg.toString()) + ) { + self._buildFromSerialized(arg.toString()); } else { throw HDPrivateKey.getSerializedError(arg); } } else if (_.isObject(arg)) { - this._buildFromObject(arg); + self._buildFromObject(arg); } else { throw new hdErrors.UnrecognizedArgument(arg); } -} +}; /** * Verifies that a given path is valid. @@ -71,9 +76,9 @@ function HDPrivateKey(arg) { * @param {boolean?} hardened * @return {boolean} */ -HDPrivateKey.isValidPath = function(arg, hardened) { +HDPrivateKey.isValidPath = function (arg: stringNumberType, hardened: boolean) { if (_.isString(arg)) { - var indexes = HDPrivateKey._getDerivationIndexes(arg); + const indexes = HDPrivateKey._getDerivationIndexes(arg); return indexes !== null && _.every(indexes, HDPrivateKey.isValidPath); } @@ -95,8 +100,8 @@ HDPrivateKey.isValidPath = function(arg, hardened) { * @param {string} path * @return {Array} */ -HDPrivateKey._getDerivationIndexes = function(path) { - var steps = path.split('/'); +HDPrivateKey._getDerivationIndexes = function (path: string) { + const steps = path.split('/'); // Special cases: if (_.includes(HDPrivateKey.RootElementAlias, path)) { @@ -107,15 +112,15 @@ HDPrivateKey._getDerivationIndexes = function(path) { return null; } - var indexes = steps.slice(1).map(function(step) { - var isHardened = step.slice(-1) === '\''; + const indexes = steps.slice(1).map(function (step) { + const isHardened = step.slice(-1) === "'"; if (isHardened) { step = step.slice(0, -1); } if (!step || step[0] === '-') { return NaN; } - var index = +step; // cast to number + let index = +step; // cast to number if (isHardened) { index += HDPrivateKey.Hardened; } @@ -152,7 +157,10 @@ HDPrivateKey._getDerivationIndexes = function(path) { * @param {string|number} arg * @param {boolean?} hardened */ -HDPrivateKey.prototype.derive = function(arg, hardened) { +HDPrivateKey.prototype.derive = function ( + arg: stringNumberType, + hardened: boolean +) { return this.deriveNonCompliantChild(arg, hardened); }; @@ -185,7 +193,10 @@ HDPrivateKey.prototype.derive = function(arg, hardened) { * @param {string|number} arg * @param {boolean?} hardened */ -HDPrivateKey.prototype.deriveChild = function(arg, hardened) { +HDPrivateKey.prototype.deriveChild = function ( + arg: stringNumberType, + hardened: boolean +) { if (_.isNumber(arg)) { return this._deriveWithNumber(arg, hardened); } else if (_.isString(arg)) { @@ -211,7 +222,10 @@ HDPrivateKey.prototype.deriveChild = function(arg, hardened) { * @param {string|number} arg * @param {boolean?} hardened */ -HDPrivateKey.prototype.deriveNonCompliantChild = function(arg, hardened) { +HDPrivateKey.prototype.deriveNonCompliantChild = function ( + arg: stringNumberType, + hardened: boolean +) { if (_.isNumber(arg)) { return this._deriveWithNumber(arg, hardened, true); } else if (_.isString(arg)) { @@ -221,7 +235,11 @@ HDPrivateKey.prototype.deriveNonCompliantChild = function(arg, hardened) { } }; -HDPrivateKey.prototype._deriveWithNumber = function(index, hardened, nonCompliant) { +HDPrivateKey.prototype._deriveWithNumber = function ( + index: number, + hardened: boolean, + nonCompliant: any +) { /* jshint maxstatements: 20 */ /* jshint maxcomplexity: 10 */ if (!HDPrivateKey.isValidPath(index, hardened)) { @@ -233,55 +251,64 @@ HDPrivateKey.prototype._deriveWithNumber = function(index, hardened, nonComplian index += HDPrivateKey.Hardened; } - var indexBuffer = BufferUtil.integerAsBuffer(index); - var data; + const indexBuffer = BufferUtil.integerAsBuffer(index); + let data; if (hardened && nonCompliant) { // The private key serialization in this case will not be exactly 32 bytes and can be // any value less, and the value is not zero-padded. - var nonZeroPadded = this.privateKey.bn.toBuffer(); + const nonZeroPadded = this.privateKey.bn.toBuffer(); data = BufferUtil.concat([Buffer.from([0]), nonZeroPadded, indexBuffer]); } else if (hardened) { // This will use a 32 byte zero padded serialization of the private key - var privateKeyBuffer = this.privateKey.bn.toBuffer({size: 32}); - assert(privateKeyBuffer.length === 32, 'length of private key buffer is expected to be 32 bytes'); + const privateKeyBuffer = this.privateKey.bn.toBuffer({ size: 32 }); + assert( + privateKeyBuffer.length === 32, + 'length of private key buffer is expected to be 32 bytes' + ); data = BufferUtil.concat([Buffer.from([0]), privateKeyBuffer, indexBuffer]); } else { data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); } - var hash = Hash.sha512hmac(data, this._buffers.chainCode); - var leftPart = BN.fromBuffer(hash.slice(0, 32), { - size: 32 + const hash = Hash.sha512hmac(data, this._buffers.chainCode); + const leftPart = BN.fromBuffer(hash.slice(0, 32), { + size: 32, }); - var chainCode = hash.slice(32, 64); + const chainCode = hash.slice(32, 64); - var privateKey = leftPart.add(this.privateKey.toBigNumber()).umod(Point.getN()).toBuffer({ - size: 32 - }); + const privateKey = leftPart + .add(this.privateKey.toBigNumber()) + .umod(Point.getN()) + .toBuffer({ + size: 32, + }); if (!PrivateKey.isValid(privateKey)) { // Index at this point is already hardened, we can pass null as the hardened arg return this._deriveWithNumber(index + 1, null, nonCompliant); } - var derived = new HDPrivateKey({ + const derived = new HDPrivateKey({ network: this.network, depth: this.depth + 1, parentFingerPrint: this.fingerPrint, childIndex: index, chainCode: chainCode, - privateKey: privateKey + privateKey: privateKey, }); return derived; }; -HDPrivateKey.prototype._deriveFromString = function(path, nonCompliant) { +HDPrivateKey.prototype._deriveFromString = function ( + path: string, + nonCompliant: any +) { if (!HDPrivateKey.isValidPath(path)) { throw new hdErrors.InvalidPath(path); } - var indexes = HDPrivateKey._getDerivationIndexes(path); - var derived = indexes.reduce(function(prev, index) { + const indexes = HDPrivateKey._getDerivationIndexes(path); + const derived = indexes.reduce(function (prev: any, index: number) { return prev._deriveWithNumber(index, null, nonCompliant); }, this); @@ -297,7 +324,10 @@ HDPrivateKey.prototype._deriveFromString = function(path, nonCompliant) { * network provided matches the network serialized. * @return {boolean} */ -HDPrivateKey.isValidSerialized = function(data, network) { +HDPrivateKey.isValidSerialized = function ( + data: dataType, + network: networkType +) { return !HDPrivateKey.getSerializedError(data, network); }; @@ -310,7 +340,10 @@ HDPrivateKey.isValidSerialized = function(data, network) { * network provided matches the network serialized. * @return {errors.InvalidArgument|null} */ -HDPrivateKey.getSerializedError = function(data, network) { +HDPrivateKey.getSerializedError = function ( + data: dataType, + network: networkType +) { /* jshint maxcomplexity: 10 */ if (!(_.isString(data) || BufferUtil.isBuffer(data))) { return new hdErrors.UnrecognizedArgument('Expected string or buffer'); @@ -327,7 +360,7 @@ HDPrivateKey.getSerializedError = function(data, network) { return new hdErrors.InvalidLength(data); } if (!_.isUndefined(network)) { - var error = HDPrivateKey._validateNetwork(data, network); + const error = HDPrivateKey._validateNetwork(data, network); if (error) { return error; } @@ -335,64 +368,98 @@ HDPrivateKey.getSerializedError = function(data, network) { return null; }; -HDPrivateKey._validateNetwork = function(data, networkArg) { - var network = Network.get(networkArg); +HDPrivateKey._validateNetwork = function ( + data: dataType, + networkArg: networkType +) { + const network = Network.get(networkArg); if (!network) { return new errors.InvalidNetworkArgument(networkArg); } - var version = data.slice(0, 4); + const version = data.slice(0, 4); if (BufferUtil.integerFromBuffer(version) !== network.xprivkey) { return new errors.InvalidNetwork(version); } return null; }; -HDPrivateKey.fromString = function(arg) { +HDPrivateKey.fromString = function (arg: any) { $.checkArgument(_.isString(arg), 'No valid string was provided'); return new HDPrivateKey(arg); }; -HDPrivateKey.fromObject = function(arg) { +HDPrivateKey.fromObject = function (arg: any) { $.checkArgument(_.isObject(arg), 'No valid argument was provided'); return new HDPrivateKey(arg); }; -HDPrivateKey.prototype._buildFromJSON = function(arg) { +HDPrivateKey.prototype._buildFromJSON = function (arg: any) { return this._buildFromObject(JSON.parse(arg)); }; -HDPrivateKey.prototype._buildFromObject = function(arg) { +HDPrivateKey.prototype._buildFromObject = function (arg: any) { /* jshint maxcomplexity: 12 */ // TODO: Type validation - var buffers = { - version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xprivkey) : arg.version, - depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth, - parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint, - childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex, - chainCode: _.isString(arg.chainCode) ? Buffer.from(arg.chainCode,'hex') : arg.chainCode, - privateKey: (_.isString(arg.privateKey) && JSUtil.isHexa(arg.privateKey)) ? Buffer.from(arg.privateKey,'hex') : arg.privateKey, - checksum: arg.checksum ? (arg.checksum.length ? arg.checksum : BufferUtil.integerAsBuffer(arg.checksum)) : undefined + const buffers = { + version: arg.network + ? BufferUtil.integerAsBuffer(Network.get(arg.network).xprivkey) + : arg.version, + depth: _.isNumber(arg.depth) + ? BufferUtil.integerAsSingleByteBuffer(arg.depth) + : arg.depth, + parentFingerPrint: _.isNumber(arg.parentFingerPrint) + ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) + : arg.parentFingerPrint, + childIndex: _.isNumber(arg.childIndex) + ? BufferUtil.integerAsBuffer(arg.childIndex) + : arg.childIndex, + chainCode: _.isString(arg.chainCode) + ? Buffer.from(arg.chainCode, 'hex') + : arg.chainCode, + privateKey: + _.isString(arg.privateKey) && JSUtil.isHexa(arg.privateKey) + ? Buffer.from(arg.privateKey, 'hex') + : arg.privateKey, + checksum: arg.checksum + ? arg.checksum.length + ? arg.checksum + : BufferUtil.integerAsBuffer(arg.checksum) + : undefined, }; return this._buildFromBuffers(buffers); }; -HDPrivateKey.prototype._buildFromSerialized = function(arg) { - var decoded = Base58Check.decode(arg); - var buffers = { +HDPrivateKey.prototype._buildFromSerialized = function (arg: any) { + const decoded = Base58Check.decode(arg); + const buffers = { version: decoded.slice(HDPrivateKey.VersionStart, HDPrivateKey.VersionEnd), depth: decoded.slice(HDPrivateKey.DepthStart, HDPrivateKey.DepthEnd), - parentFingerPrint: decoded.slice(HDPrivateKey.ParentFingerPrintStart, - HDPrivateKey.ParentFingerPrintEnd), - childIndex: decoded.slice(HDPrivateKey.ChildIndexStart, HDPrivateKey.ChildIndexEnd), - chainCode: decoded.slice(HDPrivateKey.ChainCodeStart, HDPrivateKey.ChainCodeEnd), - privateKey: decoded.slice(HDPrivateKey.PrivateKeyStart, HDPrivateKey.PrivateKeyEnd), - checksum: decoded.slice(HDPrivateKey.ChecksumStart, HDPrivateKey.ChecksumEnd), - xprivkey: arg + parentFingerPrint: decoded.slice( + HDPrivateKey.ParentFingerPrintStart, + HDPrivateKey.ParentFingerPrintEnd + ), + childIndex: decoded.slice( + HDPrivateKey.ChildIndexStart, + HDPrivateKey.ChildIndexEnd + ), + chainCode: decoded.slice( + HDPrivateKey.ChainCodeStart, + HDPrivateKey.ChainCodeEnd + ), + privateKey: decoded.slice( + HDPrivateKey.PrivateKeyStart, + HDPrivateKey.PrivateKeyEnd + ), + checksum: decoded.slice( + HDPrivateKey.ChecksumStart, + HDPrivateKey.ChecksumEnd + ), + xprivkey: arg, }; return this._buildFromBuffers(buffers); }; -HDPrivateKey.prototype._generateRandomly = function(network) { +HDPrivateKey.prototype._generateRandomly = function (network: networkType) { return HDPrivateKey.fromSeed(Random.getRandomBuffer(64), network); }; @@ -403,7 +470,7 @@ HDPrivateKey.prototype._generateRandomly = function(network) { * @param {*} network * @return HDPrivateKey */ -HDPrivateKey.fromSeed = function(hexa, network) { +HDPrivateKey.fromSeed = function (hexa: any, network: any) { /* jshint maxcomplexity: 8 */ if (JSUtil.isHexaString(hexa)) { hexa = Buffer.from(hexa, 'hex'); @@ -417,7 +484,7 @@ HDPrivateKey.fromSeed = function(hexa, network) { if (hexa.length > MAXIMUM_ENTROPY_BITS * BITS_TO_BYTES) { throw new hdErrors.InvalidEntropyArgument.TooMuchEntropy(hexa); } - var hash = Hash.sha512hmac(hexa, Buffer.from('Bitcoin seed')); + const hash = Hash.sha512hmac(hexa, Buffer.from('Bitcoin seed')); return new HDPrivateKey({ network: Network.get(network) || Network.defaultNetwork, @@ -425,15 +492,13 @@ HDPrivateKey.fromSeed = function(hexa, network) { parentFingerPrint: 0, childIndex: 0, privateKey: hash.slice(0, 32), - chainCode: hash.slice(32, 64) + chainCode: hash.slice(32, 64), }); }; - - -HDPrivateKey.prototype._calcHDPublicKey = function() { +HDPrivateKey.prototype._calcHDPublicKey = function () { if (!this._hdPublicKey) { - var HDPublicKey = require('./hdpublickey'); + const HDPublicKey = require('./hdpublickey'); this._hdPublicKey = new HDPublicKey(this); } }; @@ -454,21 +519,26 @@ HDPrivateKey.prototype._calcHDPublicKey = function() { * representation * @return {HDPrivateKey} this */ -HDPrivateKey.prototype._buildFromBuffers = function(arg) { +HDPrivateKey.prototype._buildFromBuffers = function (arg: any) { /* jshint maxcomplexity: 8 */ /* jshint maxstatements: 20 */ HDPrivateKey._validateBufferArguments(arg); JSUtil.defineImmutable(this, { - _buffers: arg + _buffers: arg, }); - var sequence = [ - arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode, - BufferUtil.emptyBuffer(1), arg.privateKey + const sequence = [ + arg.version, + arg.depth, + arg.parentFingerPrint, + arg.childIndex, + arg.chainCode, + BufferUtil.emptyBuffer(1), + arg.privateKey, ]; - var concat = buffer.Buffer.concat(sequence); + const concat = buffer.Buffer.concat(sequence); if (!arg.checksum || !arg.checksum.length) { arg.checksum = Base58Check.checksum(concat); } else { @@ -477,15 +547,15 @@ HDPrivateKey.prototype._buildFromBuffers = function(arg) { } } - var network = Network.get(BufferUtil.integerFromBuffer(arg.version)); - var xprivkey; + const network = Network.get(BufferUtil.integerFromBuffer(arg.version)); + let xprivkey; xprivkey = Base58Check.encode(buffer.Buffer.concat(sequence)); arg.xprivkey = Buffer.from(xprivkey); - var privateKey = new PrivateKey(BN.fromBuffer(arg.privateKey), network); - var publicKey = privateKey.toPublicKey(); - var size = HDPrivateKey.ParentFingerPrintSize; - var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); + const privateKey = new PrivateKey(BN.fromBuffer(arg.privateKey), network); + const publicKey = privateKey.toPublicKey(); + const size = HDPrivateKey.ParentFingerPrintSize; + const fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); JSUtil.defineImmutable(this, { xprivkey: xprivkey, @@ -493,7 +563,7 @@ HDPrivateKey.prototype._buildFromBuffers = function(arg) { depth: BufferUtil.integerFromSingleByteBuffer(arg.depth), privateKey: privateKey, publicKey: publicKey, - fingerPrint: fingerPrint + fingerPrint: fingerPrint, }); this._hdPublicKey = null; @@ -501,29 +571,33 @@ HDPrivateKey.prototype._buildFromBuffers = function(arg) { Object.defineProperty(this, 'hdPublicKey', { configurable: false, enumerable: true, - get: function() { + get: function () { this._calcHDPublicKey(); return this._hdPublicKey; - } + }, }); Object.defineProperty(this, 'xpubkey', { configurable: false, enumerable: true, - get: function() { + get: function () { this._calcHDPublicKey(); return this._hdPublicKey.xpubkey; - } + }, }); return this; }; -HDPrivateKey._validateBufferArguments = function(arg) { - var checkBuffer = function(name, size) { - var buff = arg[name]; +HDPrivateKey._validateBufferArguments = function (arg: any) { + const checkBuffer = function (name: string, size: number) { + const buff = arg[name]; assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer'); assert( buff.length === size, - name + ' has not the expected size: found ' + buff.length + ', expected ' + size + name + + ' has not the expected size: found ' + + buff.length + + ', expected ' + + size ); }; checkBuffer('version', HDPrivateKey.VersionSize); @@ -543,7 +617,7 @@ HDPrivateKey._validateBufferArguments = function(arg) { * * @return string */ -HDPrivateKey.prototype.toString = function() { +HDPrivateKey.prototype.toString = function () { return this.xprivkey; }; @@ -551,7 +625,7 @@ HDPrivateKey.prototype.toString = function() { * Returns the console representation of this extended private key. * @return string */ -HDPrivateKey.prototype.inspect = function() { +HDPrivateKey.prototype.inspect = function () { return ''; }; @@ -574,19 +648,25 @@ HDPrivateKey.prototype.inspect = function() { * * @return {Object} */ -HDPrivateKey.prototype.toObject = HDPrivateKey.prototype.toJSON = function toObject() { - return { - network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version), 'xprivkey').name, - depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), - fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), - parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), - childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), - chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), - privateKey: this.privateKey.toBuffer().toString('hex'), - checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), - xprivkey: this.xprivkey +HDPrivateKey.prototype.toObject = HDPrivateKey.prototype.toJSON = + function toObject() { + return { + network: Network.get( + BufferUtil.integerFromBuffer(this._buffers.version), + 'xprivkey' + ).name, + depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), + fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), + parentFingerPrint: BufferUtil.integerFromBuffer( + this._buffers.parentFingerPrint + ), + childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), + chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), + privateKey: this.privateKey.toBuffer().toString('hex'), + checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), + xprivkey: this.xprivkey, + }; }; -}; /** * Build a HDPrivateKey from a buffer @@ -594,7 +674,7 @@ HDPrivateKey.prototype.toObject = HDPrivateKey.prototype.toJSON = function toObj * @param {Buffer} arg * @return {HDPrivateKey} */ -HDPrivateKey.fromBuffer = function(arg) { +HDPrivateKey.fromBuffer = function (arg: Buffer) { return new HDPrivateKey(arg.toString()); }; @@ -603,7 +683,7 @@ HDPrivateKey.fromBuffer = function(arg) { * * @return {string} */ -HDPrivateKey.prototype.toBuffer = function() { +HDPrivateKey.prototype.toBuffer = function () { return BufferUtil.copy(this._buffers.xprivkey); }; @@ -613,7 +693,7 @@ HDPrivateKey.DefaultChildIndex = 0; HDPrivateKey.Hardened = 0x80000000; HDPrivateKey.MaxIndex = 2 * HDPrivateKey.Hardened; -HDPrivateKey.RootElementAlias = ['m', 'M', 'm\'', 'M\'']; +HDPrivateKey.RootElementAlias = ['m', 'M', "m'", "M'"]; HDPrivateKey.VersionSize = 4; HDPrivateKey.DepthSize = 1; @@ -631,16 +711,19 @@ HDPrivateKey.VersionEnd = HDPrivateKey.VersionStart + HDPrivateKey.VersionSize; HDPrivateKey.DepthStart = HDPrivateKey.VersionEnd; HDPrivateKey.DepthEnd = HDPrivateKey.DepthStart + HDPrivateKey.DepthSize; HDPrivateKey.ParentFingerPrintStart = HDPrivateKey.DepthEnd; -HDPrivateKey.ParentFingerPrintEnd = HDPrivateKey.ParentFingerPrintStart + HDPrivateKey.ParentFingerPrintSize; +HDPrivateKey.ParentFingerPrintEnd = + HDPrivateKey.ParentFingerPrintStart + HDPrivateKey.ParentFingerPrintSize; HDPrivateKey.ChildIndexStart = HDPrivateKey.ParentFingerPrintEnd; -HDPrivateKey.ChildIndexEnd = HDPrivateKey.ChildIndexStart + HDPrivateKey.ChildIndexSize; +HDPrivateKey.ChildIndexEnd = + HDPrivateKey.ChildIndexStart + HDPrivateKey.ChildIndexSize; HDPrivateKey.ChainCodeStart = HDPrivateKey.ChildIndexEnd; -HDPrivateKey.ChainCodeEnd = HDPrivateKey.ChainCodeStart + HDPrivateKey.ChainCodeSize; +HDPrivateKey.ChainCodeEnd = + HDPrivateKey.ChainCodeStart + HDPrivateKey.ChainCodeSize; HDPrivateKey.PrivateKeyStart = HDPrivateKey.ChainCodeEnd + 1; -HDPrivateKey.PrivateKeyEnd = HDPrivateKey.PrivateKeyStart + HDPrivateKey.PrivateKeySize; +HDPrivateKey.PrivateKeyEnd = + HDPrivateKey.PrivateKeyStart + HDPrivateKey.PrivateKeySize; HDPrivateKey.ChecksumStart = HDPrivateKey.PrivateKeyEnd; -HDPrivateKey.ChecksumEnd = HDPrivateKey.ChecksumStart + HDPrivateKey.CheckSumSize; +HDPrivateKey.ChecksumEnd = + HDPrivateKey.ChecksumStart + HDPrivateKey.CheckSumSize; assert(HDPrivateKey.ChecksumEnd === HDPrivateKey.SerializedByteSize); - -module.exports = HDPrivateKey; diff --git a/src/hdpublickey.js b/src/hdpublickey.ts similarity index 91% rename from src/hdpublickey.js rename to src/hdpublickey.ts index 2e26c8c..f5ae618 100644 --- a/src/hdpublickey.js +++ b/src/hdpublickey.ts @@ -1,3 +1,4 @@ +/* eslint-disable */ 'use strict'; var _ = require('lodash'); @@ -28,22 +29,24 @@ var BufferUtil = require('./util/buffer'); * @constructor * @param {Object|string|Buffer} arg */ -function HDPublicKey(arg) { +export const HDPublicKey:any = (arg:any) =>{ + const self: any = this; + /* jshint maxcomplexity: 12 */ /* jshint maxstatements: 20 */ if (arg instanceof HDPublicKey) { return arg; } - if (!(this instanceof HDPublicKey)) { + if (!(self instanceof HDPublicKey)) { return new HDPublicKey(arg); } if (arg) { if (_.isString(arg) || BufferUtil.isBuffer(arg)) { var error = HDPublicKey.getSerializedError(arg); if (!error) { - return this._buildFromSerialized(arg); + return self._buildFromSerialized(arg); } else if (BufferUtil.isBuffer(arg) && !HDPublicKey.getSerializedError(arg.toString())) { - return this._buildFromSerialized(arg.toString()); + return self._buildFromSerialized(arg.toString()); } else { if (error instanceof hdErrors.ArgumentIsPrivateExtended) { return new HDPrivateKey(arg).hdPublicKey; @@ -53,9 +56,9 @@ function HDPublicKey(arg) { } else { if (_.isObject(arg)) { if (arg instanceof HDPrivateKey) { - return this._buildFromPrivate(arg); + return self._buildFromPrivate(arg); } else { - return this._buildFromObject(arg); + return self._buildFromObject(arg); } } else { throw new hdErrors.UnrecognizedArgument(arg); @@ -72,7 +75,7 @@ function HDPublicKey(arg) { * @param {string|number} arg * @return {boolean} */ -HDPublicKey.isValidPath = function(arg) { +HDPublicKey.isValidPath = function(arg: stringNumberType) { if (_.isString(arg)) { var indexes = HDPrivateKey._getDerivationIndexes(arg); return indexes !== null && _.every(indexes, HDPublicKey.isValidPath); @@ -110,7 +113,7 @@ HDPublicKey.isValidPath = function(arg) { * * @param {string|number} arg */ -HDPublicKey.prototype.derive = function(arg, hardened) { +HDPublicKey.prototype.derive = function(arg:stringNumberType, hardened:boolean) { return this.deriveChild(arg, hardened); }; @@ -139,7 +142,7 @@ HDPublicKey.prototype.derive = function(arg, hardened) { * * @param {string|number} arg */ -HDPublicKey.prototype.deriveChild = function(arg, hardened) { +HDPublicKey.prototype.deriveChild = function(arg:stringNumberType, hardened:boolean) { if (_.isNumber(arg)) { return this._deriveWithNumber(arg, hardened); } else if (_.isString(arg)) { @@ -149,7 +152,7 @@ HDPublicKey.prototype.deriveChild = function(arg, hardened) { } }; -HDPublicKey.prototype._deriveWithNumber = function(index, hardened) { +HDPublicKey.prototype._deriveWithNumber = function(index:number, hardened:boolean) { if (index >= HDPublicKey.Hardened || hardened) { throw new hdErrors.InvalidIndexCantDeriveHardened(); } @@ -182,7 +185,7 @@ HDPublicKey.prototype._deriveWithNumber = function(index, hardened) { return derived; }; -HDPublicKey.prototype._deriveFromString = function(path) { +HDPublicKey.prototype._deriveFromString = function(path:string) { /* jshint maxcomplexity: 8 */ if (_.includes(path, "'")) { throw new hdErrors.InvalidIndexCantDeriveHardened(); @@ -191,7 +194,7 @@ HDPublicKey.prototype._deriveFromString = function(path) { } var indexes = HDPrivateKey._getDerivationIndexes(path); - var derived = indexes.reduce(function(prev, index) { + var derived = indexes.reduce(function(prev:any, index:number) { return prev._deriveWithNumber(index); }, this); @@ -207,7 +210,7 @@ HDPublicKey.prototype._deriveFromString = function(path) { * network provided matches the network serialized. * @return {boolean} */ -HDPublicKey.isValidSerialized = function(data, network) { +HDPublicKey.isValidSerialized = function(data:dataType, network:networkType) { return _.isNull(HDPublicKey.getSerializedError(data, network)); }; @@ -220,7 +223,7 @@ HDPublicKey.isValidSerialized = function(data, network) { * network provided matches the network serialized. * @return {errors|null} */ -HDPublicKey.getSerializedError = function(data, network) { +HDPublicKey.getSerializedError = function(data:dataType, network:networkType) { /* jshint maxcomplexity: 10 */ /* jshint maxstatements: 20 */ if (!(_.isString(data) || BufferUtil.isBuffer(data))) { @@ -250,7 +253,7 @@ HDPublicKey.getSerializedError = function(data, network) { return null; }; -HDPublicKey._validateNetwork = function(data, networkArg) { +HDPublicKey._validateNetwork = function(data:dataType, networkArg:networkType) { var network = Network.get(networkArg); if (!network) { return new errors.InvalidNetworkArgument(networkArg); @@ -262,7 +265,7 @@ HDPublicKey._validateNetwork = function(data, networkArg) { return null; }; -HDPublicKey.prototype._buildFromPrivate = function (arg) { +HDPublicKey.prototype._buildFromPrivate = function (arg:any) { var args = _.clone(arg._buffers); var point = Point.getG().mul(BN.fromBuffer(args.privateKey)); args.publicKey = Point.pointToCompressed(point); @@ -273,7 +276,7 @@ HDPublicKey.prototype._buildFromPrivate = function (arg) { return this._buildFromBuffers(args); }; -HDPublicKey.prototype._buildFromObject = function(arg) { +HDPublicKey.prototype._buildFromObject = function(arg:any) { /* jshint maxcomplexity: 10 */ // TODO: Type validation var buffers = { @@ -289,7 +292,7 @@ HDPublicKey.prototype._buildFromObject = function(arg) { return this._buildFromBuffers(buffers); }; -HDPublicKey.prototype._buildFromSerialized = function(arg) { +HDPublicKey.prototype._buildFromSerialized = function(arg:any) { var decoded = Base58Check.decode(arg); var buffers = { version: decoded.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd), @@ -321,7 +324,7 @@ HDPublicKey.prototype._buildFromSerialized = function(arg) { * representation * @return {HDPublicKey} this */ -HDPublicKey.prototype._buildFromBuffers = function(arg) { +HDPublicKey.prototype._buildFromBuffers = function(arg:any) { /* jshint maxcomplexity: 8 */ /* jshint maxstatements: 20 */ @@ -365,8 +368,8 @@ HDPublicKey.prototype._buildFromBuffers = function(arg) { return this; }; -HDPublicKey._validateBufferArguments = function(arg) { - var checkBuffer = function(name, size) { +HDPublicKey._validateBufferArguments = function(arg:any) { + var checkBuffer = function(name:string, size:number) { var buff = arg[name]; assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer, it\'s ' + typeof buff); assert( @@ -385,12 +388,12 @@ HDPublicKey._validateBufferArguments = function(arg) { } }; -HDPublicKey.fromString = function(arg) { +HDPublicKey.fromString = function(arg:any) { $.checkArgument(_.isString(arg), 'No valid string was provided'); return new HDPublicKey(arg); }; -HDPublicKey.fromObject = function(arg) { +HDPublicKey.fromObject = function(arg:any) { $.checkArgument(_.isObject(arg), 'No valid argument was provided'); return new HDPublicKey(arg); }; @@ -448,7 +451,7 @@ HDPublicKey.prototype.toObject = HDPublicKey.prototype.toJSON = function toObjec * @param {Buffer} arg * @return {HDPublicKey} */ -HDPublicKey.fromBuffer = function(arg) { +HDPublicKey.fromBuffer = function(arg:Buffer) { return new HDPublicKey(arg); }; @@ -491,6 +494,4 @@ HDPublicKey.ChecksumStart = HDPublicKey.PublicKeyEnd; HDPublicKey.ChecksumEnd = HDPublicKey.ChecksumStart + HDPublicKey.CheckSumSize; assert(HDPublicKey.PublicKeyEnd === HDPublicKey.DataSize); -assert(HDPublicKey.ChecksumEnd === HDPublicKey.SerializedByteSize); - -module.exports = HDPublicKey; +assert(HDPublicKey.ChecksumEnd === HDPublicKey.SerializedByteSize); \ No newline at end of file diff --git a/src/networks.js b/src/networks.ts similarity index 92% rename from src/networks.js rename to src/networks.ts index cb88005..a5b3afd 100644 --- a/src/networks.js +++ b/src/networks.ts @@ -1,10 +1,12 @@ +/* eslint-disable */ + 'use strict'; var _ = require('lodash'); var BufferUtil = require('./util/buffer'); var JSUtil = require('./util/js'); -var networks = []; -var networkMaps = {}; +var networks:networkType[] = []; +var networkMaps:any = {}; /** * A network is merely a map containing values that correspond to version @@ -12,7 +14,7 @@ var networkMaps = {}; * (a.k.a. "mainnet") and "testnet". * @constructor */ -function Network() {} +export const Network:any = () => {} Network.prototype.toString = function toString() { return this.name; @@ -26,7 +28,7 @@ Network.prototype.toString = function toString() { * @param {string|Array} keys - if set, only check if the magic number associated with this name matches * @return Network */ -function get(arg, keys) { +function get(arg?:networkType, keys?:keyType) { if (~networks.indexOf(arg)) { return arg; } @@ -34,9 +36,7 @@ function get(arg, keys) { if (!_.isArray(keys)) { keys = [keys]; } - var containsArg = function(key) { - return networks[index][key] === arg; - }; + var containsArg = (key: keyType, index:number) => networks[index][key] === arg; for (var index in networks) { if (_.some(keys, containsArg)) { return networks[index]; @@ -69,9 +69,9 @@ function get(arg, keys) { * @param {Array} data.dnsSeeds - An array of dns seeds * @return Network */ -function addNetwork(data) { +function addNetwork(data:any) { - var network = new Network(); + var network:any = new Network(); JSUtil.defineImmutable(network, { name: data.name, @@ -101,7 +101,7 @@ function addNetwork(data) { dnsSeeds: data.dnsSeeds }); } - _.each(network, function(value) { + _.each(network, function(value:any) { if (!_.isUndefined(value) && !_.isObject(value)) { if(!networkMaps[value]) { networkMaps[value] = []; @@ -122,7 +122,7 @@ function addNetwork(data) { * Will remove a custom network * @param {Network} network */ -function removeNetwork(network) { +function removeNetwork(network:networkType) { for (var i = 0; i < networks.length; i++) { if (networks[i] === network) { networks.splice(i, 1); diff --git a/src/tsconfig.json b/src/tsconfig.json deleted file mode 100644 index 5679481..0000000 --- a/src/tsconfig.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Projects */ - // "incremental": true, /* Enable incremental compilation */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ - // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "resolveJsonModule": true, /* Enable importing .json files */ - // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ - // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ - // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ - } -} diff --git a/src/type.d.ts b/src/type.d.ts new file mode 100644 index 0000000..035adb1 --- /dev/null +++ b/src/type.d.ts @@ -0,0 +1,7 @@ +type stringNumberType = string | number; + +type dataType = string | Buffer; + +type networkType = string | number | Network; + +type keyType = string | Array; diff --git a/tsconfig.json b/tsconfig.json index 22bbbd2..e611533 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,20 +1,19 @@ { "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ - /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./lib/", /* Redirect output structure to the directory. */ + "outDir": "./lib/", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ @@ -23,9 +22,8 @@ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true, /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ @@ -33,7 +31,6 @@ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ @@ -41,7 +38,6 @@ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ - /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ @@ -50,23 +46,23 @@ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - /* Advanced Options */ - "skipLibCheck": true, /* Skip type checking of declaration files. */ - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ }, - "include": ["src/**/*.ts", "test/**/*.ts"] -} + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} \ No newline at end of file