From 091cc8f9db651ff9bc7b73d7abdfb10bcad29345 Mon Sep 17 00:00:00 2001 From: Caleb Kniffen Date: Thu, 31 Aug 2023 19:48:39 -0500 Subject: [PATCH] feat: add `xrpl-secret-numbers` to the monorepo (#2445) - Add `xrpl-secret-numbers` by @WietseWind to the mono repo. - `unpkg` and `jsdelivr` support was simplified by adding fields to package.json. - Unit tests run in a browser and node. BREAKING CHANGES: - `xrpl-secret-numbers` is now `@xrplf/secret-numbers`. - Changed the bundled file produced changed from `dist/browerified.js` to `build/xrplf-secret-numbers-latest.js`. - Bundle variable is `xrplf_secret_numbers` instead of using browserify's loader. - If using CDN instructions in README will need to update to `https://cdn.jsdelivr.net/npm/@xrplf/secret-numbers` Making this library part of the monorepo was discussed in #1788. This solves several problems with the upcoming `xrpl.js@3.0`. `xrpl-secret-numbers` has a dependency of `ripple-keypairs` and `xrpl` has a depenendecy on `xrpl-secret-numbers`. This means that any change would require a separate release of `ripple-keypairs`, then a release of `xrpl-secret-numbers`, followed by `xrpl`. Now they can be released all at once In 3.0 we eliminated the need for many polyfills like `util`, `assert`, and soon to be `buffer` (after noble libs PR is merged). `xrpl-secret-numbers` still needs those. This will also eliminate them and anytime similar changes in the future will be much easier. This further reduces the bundle size of 3.0 branch by over 10% as well as reducing bundler setup. --- package-lock.json | 66 ++++++----- package.json | 1 + packages/secret-numbers/.eslintignore | 12 ++ packages/secret-numbers/.eslintrc.js | 47 ++++++++ packages/secret-numbers/HISTORY.md | 14 +++ packages/secret-numbers/LICENSE | 15 +++ packages/secret-numbers/README.md | 97 ++++++++++++++++ packages/secret-numbers/jest.config.js | 8 ++ packages/secret-numbers/karma.config.js | 39 +++++++ packages/secret-numbers/package.json | 47 ++++++++ packages/secret-numbers/samples/es5.js | 26 +++++ packages/secret-numbers/src/index.ts | 8 ++ packages/secret-numbers/src/schema/Account.ts | 99 ++++++++++++++++ packages/secret-numbers/src/utils/index.ts | 90 +++++++++++++++ packages/secret-numbers/test/api.test.ts | 99 ++++++++++++++++ packages/secret-numbers/test/index.ts | 1 + packages/secret-numbers/test/utils.test.ts | 107 ++++++++++++++++++ .../secret-numbers/test/webpack.config.js | 61 ++++++++++ packages/secret-numbers/tsconfig.build.json | 12 ++ packages/secret-numbers/tsconfig.eslint.json | 4 + packages/secret-numbers/tsconfig.json | 20 ++++ .../secret-numbers/webpack.base.config.js | 14 +++ packages/secret-numbers/webpack.config.js | 8 ++ packages/xrpl/HISTORY.md | 4 +- packages/xrpl/package.json | 5 +- .../src/Wallet/walletFromSecretNumbers.ts | 2 +- packages/xrpl/test/webpack.config.js | 59 +--------- packages/xrpl/webpack.base.config.js | 26 +++++ packages/xrpl/webpack.config.js | 94 +-------------- webpack.config.js | 96 ++++++++++++++++ 30 files changed, 1007 insertions(+), 174 deletions(-) create mode 100644 packages/secret-numbers/.eslintignore create mode 100644 packages/secret-numbers/.eslintrc.js create mode 100644 packages/secret-numbers/HISTORY.md create mode 100644 packages/secret-numbers/LICENSE create mode 100644 packages/secret-numbers/README.md create mode 100644 packages/secret-numbers/jest.config.js create mode 100644 packages/secret-numbers/karma.config.js create mode 100644 packages/secret-numbers/package.json create mode 100644 packages/secret-numbers/samples/es5.js create mode 100644 packages/secret-numbers/src/index.ts create mode 100644 packages/secret-numbers/src/schema/Account.ts create mode 100644 packages/secret-numbers/src/utils/index.ts create mode 100644 packages/secret-numbers/test/api.test.ts create mode 100644 packages/secret-numbers/test/index.ts create mode 100644 packages/secret-numbers/test/utils.test.ts create mode 100644 packages/secret-numbers/test/webpack.config.js create mode 100644 packages/secret-numbers/tsconfig.build.json create mode 100644 packages/secret-numbers/tsconfig.eslint.json create mode 100644 packages/secret-numbers/tsconfig.json create mode 100644 packages/secret-numbers/webpack.base.config.js create mode 100644 packages/secret-numbers/webpack.config.js create mode 100644 packages/xrpl/webpack.base.config.js create mode 100644 webpack.config.js diff --git a/package-lock.json b/package-lock.json index cad4e05ea2..6ef91fb193 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "./packages/*" ], "dependencies": { + "@xrplf/ripple-keypairs": "file:packages/secret-numbers", "ripple-address-codec": "file:packages/ripple-address-codec", "ripple-binary-codec": "file:packages/ripple-binary-codec", "ripple-keypairs": "file:packages/ripple-keypairs", @@ -3013,7 +3014,8 @@ "node_modules/@types/node": { "version": "14.18.36", "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.36.tgz", - "integrity": "sha512-FXKWbsJ6a1hIrRxv+FoukuHnGTgEzKYGi7kilfMae96AL9UNkPFNWJEEYWzdRI9ooIkbr4AKldyuSTLql06vLQ==" + "integrity": "sha512-FXKWbsJ6a1hIrRxv+FoukuHnGTgEzKYGi7kilfMae96AL9UNkPFNWJEEYWzdRI9ooIkbr4AKldyuSTLql06vLQ==", + "dev": true }, "node_modules/@types/normalize-package-data": { "version": "2.4.1", @@ -3478,6 +3480,14 @@ "integrity": "sha512-1k4WCTstvGiTJQYUNTZhz4BM2DI/kVBRXh1Dw5fVaVDiGVb4YOuzxFNgipOWX/EllrjRTN5NNGLJEDk0nsMFEg==", "dev": true }, + "node_modules/@xrplf/ripple-keypairs": { + "resolved": "packages/secret-numbers", + "link": true + }, + "node_modules/@xrplf/secret-numbers": { + "resolved": "packages/secret-numbers", + "link": true + }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", @@ -15692,16 +15702,6 @@ "resolved": "packages/xrpl", "link": true }, - "node_modules/xrpl-secret-numbers": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/xrpl-secret-numbers/-/xrpl-secret-numbers-0.3.4.tgz", - "integrity": "sha512-B3m0OLRsmNLQpN/BUR15+LC4yejM/pdneoWgijfBYbgjVVnpyCF5+Ur7zbAs4nCAlBUZYXnxp+o/rSNZkke9jQ==", - "dependencies": { - "@types/brorand": "^1.0.30", - "brorand": "^1.1.0", - "ripple-keypairs": "^1.1.5" - } - }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", @@ -15823,10 +15823,20 @@ "node": ">= 16" } }, + "packages/secret-numbers": { + "name": "@xrplf/secret-numbers", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "brorand": "^1.1.0", + "ripple-keypairs": "^1.3.0" + } + }, "packages/xrpl": { "version": "2.13.0", "license": "ISC", "dependencies": { + "@xrplf/secret-numbers": "^1.0.0", "bignumber.js": "^9.0.0", "bip32": "^2.0.6", "bip39": "^3.0.4", @@ -15834,8 +15844,7 @@ "ripple-address-codec": "^4.3.1", "ripple-binary-codec": "^1.10.0", "ripple-keypairs": "^1.3.1", - "ws": "^8.2.2", - "xrpl-secret-numbers": "^0.3.3" + "ws": "^8.2.2" }, "devDependencies": { "@types/node": "^16.18.38", @@ -18302,7 +18311,8 @@ "@types/node": { "version": "14.18.36", "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.36.tgz", - "integrity": "sha512-FXKWbsJ6a1hIrRxv+FoukuHnGTgEzKYGi7kilfMae96AL9UNkPFNWJEEYWzdRI9ooIkbr4AKldyuSTLql06vLQ==" + "integrity": "sha512-FXKWbsJ6a1hIrRxv+FoukuHnGTgEzKYGi7kilfMae96AL9UNkPFNWJEEYWzdRI9ooIkbr4AKldyuSTLql06vLQ==", + "dev": true }, "@types/normalize-package-data": { "version": "2.4.1", @@ -18641,6 +18651,20 @@ "integrity": "sha512-1k4WCTstvGiTJQYUNTZhz4BM2DI/kVBRXh1Dw5fVaVDiGVb4YOuzxFNgipOWX/EllrjRTN5NNGLJEDk0nsMFEg==", "dev": true }, + "@xrplf/ripple-keypairs": { + "version": "file:packages/secret-numbers", + "requires": { + "brorand": "^1.1.0", + "ripple-keypairs": "^1.3.0" + } + }, + "@xrplf/secret-numbers": { + "version": "file:packages/secret-numbers", + "requires": { + "brorand": "^1.1.0", + "ripple-keypairs": "^1.3.0" + } + }, "@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", @@ -28077,6 +28101,7 @@ "version": "file:packages/xrpl", "requires": { "@types/node": "^16.18.38", + "@xrplf/secret-numbers": "^1.0.0", "bignumber.js": "^9.0.0", "bip32": "^2.0.6", "bip39": "^3.0.4", @@ -28093,8 +28118,7 @@ "ripple-keypairs": "^1.3.1", "run-s": "^0.0.0", "typedoc": "0.25.0", - "ws": "^8.2.2", - "xrpl-secret-numbers": "^0.3.3" + "ws": "^8.2.2" }, "dependencies": { "@types/node": { @@ -28124,16 +28148,6 @@ } } }, - "xrpl-secret-numbers": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/xrpl-secret-numbers/-/xrpl-secret-numbers-0.3.4.tgz", - "integrity": "sha512-B3m0OLRsmNLQpN/BUR15+LC4yejM/pdneoWgijfBYbgjVVnpyCF5+Ur7zbAs4nCAlBUZYXnxp+o/rSNZkke9jQ==", - "requires": { - "@types/brorand": "^1.0.30", - "brorand": "^1.1.0", - "ripple-keypairs": "^1.1.5" - } - }, "xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index d85a71d6f2..74547565cd 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "update:confirm": "npx npm-check-updates --configFileName .ncurc.json -u" }, "dependencies": { + "@xrplf/ripple-keypairs": "file:packages/secret-numbers", "ripple-address-codec": "file:packages/ripple-address-codec", "ripple-binary-codec": "file:packages/ripple-binary-codec", "ripple-keypairs": "file:packages/ripple-keypairs", diff --git a/packages/secret-numbers/.eslintignore b/packages/secret-numbers/.eslintignore new file mode 100644 index 0000000000..0fc0705592 --- /dev/null +++ b/packages/secret-numbers/.eslintignore @@ -0,0 +1,12 @@ +# Don't ever lint node_modules +node_modules + +# Don't lint build output +dist + +# don't lint nyc coverage output +coverage +.nyc_output + +# Don't lint NYC configuration +nyc.config.js diff --git a/packages/secret-numbers/.eslintrc.js b/packages/secret-numbers/.eslintrc.js new file mode 100644 index 0000000000..c8a3adcfa4 --- /dev/null +++ b/packages/secret-numbers/.eslintrc.js @@ -0,0 +1,47 @@ +module.exports = { + root: true, + + parser: "@typescript-eslint/parser", // Make ESLint compatible with TypeScript + parserOptions: { + // Enable linting rules with type information from our tsconfig + tsconfigRootDir: __dirname, + project: ["./tsconfig.eslint.json"], + + sourceType: "module", // Allow the use of imports / ES modules + + ecmaFeatures: { + impliedStrict: true, // Enable global strict mode + }, + }, + + // Specify global variables that are predefined + env: { + browser: true, // Enable browser global variables + node: true, // Enable node global variables & Node.js scoping + es2020: true, // Add all ECMAScript 2020 globals and automatically set the ecmaVersion parser option to ES2020 + }, + + plugins: [], + extends: ["@xrplf/eslint-config/base"], + + rules: { + // This creates a lot of false positives. We should turn this off in our + // general config. + "jsdoc/require-description-complete-sentence": "off", + + // ** TODO ** + // all of the below are turned off for now during the migration to a + // monorepo. They need to actually be addressed! + // ** + "@typescript-eslint/no-magic-numbers": "off", + "jsdoc/require-returns": "off", + "jsdoc/check-param-names": "off", + "jsdoc/require-throws": "off", + "jsdoc/require-jsdoc": "off", + "jsdoc/require-param": "off", + "jsdoc/check-examples": "off", // Not implemented in eslint 8 + "tsdoc/syntax": "off", + "@typescript-eslint/no-require-imports": "off", + "@typescript-eslint/explicit-member-accessibility": "off", + }, +}; diff --git a/packages/secret-numbers/HISTORY.md b/packages/secret-numbers/HISTORY.md new file mode 100644 index 0000000000..91b3f2e95b --- /dev/null +++ b/packages/secret-numbers/HISTORY.md @@ -0,0 +1,14 @@ +# @xrplf/secret-numbers (xrpl-secret-numbers) Release History + +Subscribe to [the **xrpl-announce** mailing list](https://groups.google.com/g/xrpl-announce) for release announcements. We recommend that `@xrplf/secret-numbers` users stay up-to-date with the latest stable release. + +## Unreleased + +- Add `xrpl-secret-numbers` by @WietseWind to the mono repo. +- `unpkg` and `jsdelivr` support was simplified. +- Unit tests run in a browser and node. + +### BREAKING CHANGES: +- `xrpl-secret-numbers` is now `@xrplf/secret-numbers`. +- The bundled file produced changed from `dist/browerified.js` to `build/xrplf-secret-numbers-latest.js`. +- Bundle variable is `xrplf_secret_numbers` instead of using browserify's loader. diff --git a/packages/secret-numbers/LICENSE b/packages/secret-numbers/LICENSE new file mode 100644 index 0000000000..d85dc9a85e --- /dev/null +++ b/packages/secret-numbers/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2019-2023 Contributers to xrpl.js + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/packages/secret-numbers/README.md b/packages/secret-numbers/README.md new file mode 100644 index 0000000000..b6afef5227 --- /dev/null +++ b/packages/secret-numbers/README.md @@ -0,0 +1,97 @@ +# XRPL Secret Numbers [![npm version](https://badge.fury.io/js/@xrplf%2Fsecret-numbers.svg)](https://www.npmjs.com/@xrplf/secret-numbers) + +For more background information, please read the [proposed Standard](https://github.com/xrp-community/standards-drafts/issues/15). + +A tool to convert Secret Numbers to the widely used Family Seed `s...` format is [available here](https://github.com/WietseWind/secret-numbers-to-family-seed/releases) + +A bundled version of this lib is available at NPM (`build/xrplf-secret-numbers-latest.js`), CDN: https://cdn.jsdelivr.net/npm/@xrplf/secret-numbers. You can access the library as `xrplf_secret_numbers`. Sample: +https://jsfiddle.net/WietseWind/uo1zy0q7/ + +#### Generate XRPL Accounts with a number-based secret: 8 chunks of 6 digits. + +The common formats for XRPL account secrets are (at the time of writing this, July 2019): + +- Family Seed, eg. `sh1HiK7SwjS1VxFdXi7qeMHRedrYX` +- Mnemonic, eg. `car banana apple road ...` + +These formats are prone to typo's and not that user friendly. Using numbers means it's language (spoken, written) agnostic as well. They may be especially intimidating for the public that's relatively new to cryptocurrencies / blockchain technology. + +This library encodes the entropy to generate accounts into 8 chunks of 6 digits, of which 5 digits are 1/8th of the entropy, and a 6th digit contains a checksum allowing realtime typo detection. + +##### A secret now looks like: + +``` +554872 394230 209376 323698 +140250 387423 652803 258676 +``` + +For compatibility with existing clients, this library supports exporting the family seed for a generated / entered "Secret Number"-set as well. + +## API + +The typescript code to use resides in `./src/` and the compiled js in `./dist/` of the package. See the `./samples/` folder for some simple JS samples. + +##### Generating a new account: + +``` +const {Account} = require('@xrplf/secret-numbers') +const account = new Account() +``` + +##### Importing an existing account: + +``` +const {Account} = require('@xrplf/secret-numbers') +const secret = '399150 474506 009147 088773 432160 282843 253738 605430' +const account = new Account(secret) +``` + +Or importing with custom entropy (buffer, 16): + +``` +const {Account} = require('@xrplf/secret-numbers') +const entropy = Buffer.from('0123456789ABCDEF0123456789ABCDEF', 'hex') +const account = new Account(entropy) +``` + +##### After generating / importing: + +You can fetch the account details (address, secret, etc.) using these methods: + +``` +console.log(account.getAddress()) +console.log(account.getSecret()) +``` + +##### Available methods: + +- `getSecret()`: Array[8] +- `getSecretString()`: string `012345 456789 ...` +- `getAddress()`: string `rXXXXXXXX...` +- `getFamilySeed()`: string `sXXXXXXXX...` +- `getKeypair()`: `Keypair({privateKey, publicKey}` + +##### To split/check/encode/decode some more: + +There's a `Utils` export as well: + +``` +const {Account, Utils} = require('@xrplf/secret-numbers') +``` + +Some Utils methods (that you may want to use in your UI / ... before using the Account constructor): + + - To calculate the 6th decimal for a group of 5 digits: + `calculateChecksum(position: number, value: number)`: number + - To check a checksum (either sliced or the 6th char of a string containing numbers: + `checkChecksum(position: number, value: number | string, checksum?: number)`: Boolean + +## Development + +Run `npm run prepublish` to clean, lint, test and build. Or just run `npm run build`, `npm run test` or `npm run lint`. + +Tests are in `./test/` + +## Credits + +This concept is based on an idea by [@nbougalis](https://github.com/nbougalis). diff --git a/packages/secret-numbers/jest.config.js b/packages/secret-numbers/jest.config.js new file mode 100644 index 0000000000..e508e8bda8 --- /dev/null +++ b/packages/secret-numbers/jest.config.js @@ -0,0 +1,8 @@ +// Jest configuration for api +const base = require("../../jest.config.base.js"); + +module.exports = { + ...base, + roots: [...base.roots, "/test"], + displayName: "@xrplf/secret-numbers", +}; diff --git a/packages/secret-numbers/karma.config.js b/packages/secret-numbers/karma.config.js new file mode 100644 index 0000000000..5f623a5db6 --- /dev/null +++ b/packages/secret-numbers/karma.config.js @@ -0,0 +1,39 @@ +const webpackConfig = require("./test/webpack.config"); +delete webpackConfig.entry; + +module.exports = function (config) { + config.set({ + plugins: ["karma-webpack", "karma-jasmine", "karma-chrome-launcher"], + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: "", + + webpack: webpackConfig, + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ["jasmine"], + + // list of files / patterns to load in the browser + files: ["build/xrplf-secret-numbers-latest.js", "test/*.test.ts"], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + // Use webpack to bundle our test files + "test/*.test.ts": ["webpack"], + }, + + browsers: ["ChromeHeadless"], + // runs only one browser at a time + concurrency: 1, + // CI mode + singleRun: true, + client: { + jasmine: { + // ensures that tests are run in order instead of a random order + random: false, + }, + }, + }); +}; diff --git a/packages/secret-numbers/package.json b/packages/secret-numbers/package.json new file mode 100644 index 0000000000..0f7bd45363 --- /dev/null +++ b/packages/secret-numbers/package.json @@ -0,0 +1,47 @@ +{ + "name": "@xrplf/secret-numbers", + "version": "1.0.0", + "description": "Generate XRPL Accounts with a number-based secret: 8 chunks of 6 digits", + "main": "dist/index.js", + "unpkg": "build/xrplf-secret-numbers-latest-min.js", + "jsdelivr": "build/xrplf-secret-numbers-latest-min.js", + "types": "dist/index.d.ts", + "scripts": { + "prepublish": "npm run clean && npm run lint && npm run test && npm run test:browser && npm run build", + "clean": "rm -rf dist build coverage", + "test": "jest --verbose", + "test:browser": "npm run build && npm run build:browserTests && karma start ./karma.config.js --single-run", + "build": "run-s build:lib build:web", + "build:lib": "tsc --build tsconfig.build.json --force", + "build:web": "webpack", + "build:browserTests": "webpack --config ./test/webpack.config.js", + "lint": "eslint . --ext .ts --ext .test.ts --fix", + "analyze": "webpack --analyze" + }, + "files": [ + "build/*", + "dist/**/*.js", + "dist/**/*.js.map", + "dist/**/*.d.ts", + "src/*" + ], + "directories": { + "test": "test" + }, + "dependencies": { + "brorand": "^1.1.0", + "ripple-keypairs": "^1.3.0" + }, + "repository": { + "type": "git", + "url": "git@github.com:XRPLF/xrpl.js.git" + }, + "license": "ISC", + "readmeFilename": "README.md", + "keywords": [ + "xrp", + "xrpl-ledger", + "multi sign", + "sign" + ] +} diff --git a/packages/secret-numbers/samples/es5.js b/packages/secret-numbers/samples/es5.js new file mode 100644 index 0000000000..4e9da83d4b --- /dev/null +++ b/packages/secret-numbers/samples/es5.js @@ -0,0 +1,26 @@ +const {Account} = require('../dist/') + +console.log(`😎 Generate an account`) +const generatedAccount = new Account() +console.log(`\n Generated account address\n `, generatedAccount.getAddress()) +console.log(`\n Generated numbers (secret)\n `, generatedAccount.getSecretString()) + +console.log(`\n\n`) + +const account = [ + '399150', '474506', '009147', '088773', '432160', '282843', '253738', '605430' +] +console.log(`😎 Import account "${account.join(' ')}"`) +const importedAccount = new Account(account) +console.log(`\n Imported account address\n `, importedAccount.getAddress()) +console.log(`\n Imported account family seed\n `, importedAccount.getFamilySeed()) + +console.log(`\n\n`) + +const entropy = Buffer.from('0123456789ABCDEF0123456789ABCDEF', 'hex') +console.log(`😎 Import account from entropy buffer "${entropy.toString('hex')}"`) +const entropyAccount = new Account(entropy) +console.log(`\n Imported account address\n `, entropyAccount.getAddress()) +console.log(`\n Imported account family seed\n `, entropyAccount.getFamilySeed()) + +console.log(`\n\n`) diff --git a/packages/secret-numbers/src/index.ts b/packages/secret-numbers/src/index.ts new file mode 100644 index 0000000000..919677c2d5 --- /dev/null +++ b/packages/secret-numbers/src/index.ts @@ -0,0 +1,8 @@ +/* Methods ==================================================================== */ +import Account from "./schema/Account"; +import * as Utils from "./utils"; + +/* Types ==================================================================== */ + +/* Export ==================================================================== */ +export { Account, Utils }; diff --git a/packages/secret-numbers/src/schema/Account.ts b/packages/secret-numbers/src/schema/Account.ts new file mode 100644 index 0000000000..d8f221fad3 --- /dev/null +++ b/packages/secret-numbers/src/schema/Account.ts @@ -0,0 +1,99 @@ +import * as keypairs from "ripple-keypairs"; + +import * as utils from "../utils"; + +/* Types ==================================================================== */ + +// eslint-disable-next-line import/no-unused-modules -- it is returned by Account.getKeypair +export interface Keypair { + publicKey: string; + privateKey: string; +} + +interface AccountData { + familySeed: string; + address: string; + keypair: Keypair; +} + +/* Class ==================================================================== */ + +export default class Account { + private readonly _secret: string[]; + private readonly _account: AccountData = { + familySeed: "", + address: "", + keypair: { + publicKey: "", + privateKey: "", + }, + }; + + constructor(secretNumbers?: string[] | string | Buffer) { + if (typeof secretNumbers === "string") { + this._secret = utils.parseSecretString(secretNumbers); + } else if (Array.isArray(secretNumbers)) { + this._secret = secretNumbers; + } else if (Buffer.isBuffer(secretNumbers)) { + this._secret = utils.entropyToSecret(secretNumbers); + } else { + this._secret = utils.randomSecret(); + } + + validateLengths(this._secret); + this.derive(); + } + + getSecret(): string[] { + return this._secret; + } + + getSecretString(): string { + return this._secret.join(" "); + } + + getAddress(): string { + return this._account.address; + } + + getFamilySeed(): string { + return this._account.familySeed; + } + + getKeypair(): Keypair { + return this._account.keypair; + } + + toString(): string { + return this.getSecretString(); + } + + private derive(): void { + try { + const entropy = utils.secretToEntropy(this._secret); + this._account.familySeed = keypairs.generateSeed({ entropy }); + this._account.keypair = keypairs.deriveKeypair(this._account.familySeed); + this._account.address = keypairs.deriveAddress( + this._account.keypair.publicKey + ); + } catch (error) { + let message = "Unknown Error"; + if (error instanceof Error) { + message = error.message; + } + // we'll proceed, but let's report it + throw new Error(message); + } + } +} + +function validateLengths(secretNumbers: string[]): void { + if (secretNumbers.length !== 8) { + throw new Error("Secret must have 8 numbers"); + } + secretNumbers.forEach((num) => { + if (num.length !== 6) { + throw new Error("Each secret number must be 6 digits"); + } + }); +} diff --git a/packages/secret-numbers/src/utils/index.ts b/packages/secret-numbers/src/utils/index.ts new file mode 100644 index 0000000000..83c4cfc1f7 --- /dev/null +++ b/packages/secret-numbers/src/utils/index.ts @@ -0,0 +1,90 @@ +import brorand from "brorand"; + +function randomEntropy(): Buffer { + return Buffer.from(brorand(16)); +} + +function calculateChecksum(position: number, value: number): number { + return (value * (position * 2 + 1)) % 9; +} + +function checkChecksum( + position: number, + value: number | string, + checksum?: number +): boolean { + let normalizedChecksum: number; + let normalizedValue: number; + + if (typeof value === "string") { + if (value.length !== 6) { + throw new Error("value must have a length of 6"); + } + normalizedChecksum = parseInt(value.slice(5), 10); + normalizedValue = parseInt(value.slice(0, 5), 10); + } else { + if (typeof checksum !== "number") { + throw new Error("checksum must be a number when value is a number"); + } + normalizedChecksum = checksum; + normalizedValue = value; + } + return (normalizedValue * (position * 2 + 1)) % 9 === normalizedChecksum; +} + +function entropyToSecret(entropy: Buffer): string[] { + const len = new Array(Math.ceil(entropy.length / 2)); + const chunks = Array.from(len, (_a, chunk) => { + const buffChunk = entropy.slice(chunk * 2, (chunk + 1) * 2); + const no = parseInt(buffChunk.toString("hex"), 16); + const fill = "0".repeat(5 - String(no).length); + return fill + String(no) + String(calculateChecksum(chunk, no)); + }); + if (chunks.length !== 8) { + throw new Error("Chucks must have 8 digits"); + } + return chunks; +} + +function randomSecret(): string[] { + return entropyToSecret(randomEntropy()); +} + +function secretToEntropy(secret: string[]): Buffer { + return Buffer.concat( + secret.map((chunk, i) => { + const no = Number(chunk.slice(0, 5)); + const checksum = Number(chunk.slice(5)); + if (chunk.length !== 6) { + throw new Error("Invalid secret: number invalid"); + } + if (!checkChecksum(i, no, checksum)) { + throw new Error("Invalid secret part: checksum invalid"); + } + const hex = `0000${no.toString(16)}`.slice(-4); + return Buffer.from(hex, "hex"); + }) + ); +} + +function parseSecretString(secret: string): string[] { + const normalizedSecret = secret.replace(/[^0-9]/gu, ""); + if (normalizedSecret.length !== 48) { + throw new Error( + "Invalid secret string (should contain 8 blocks of 6 digits" + ); + } + return Array.from(new Array(8), (_a, index) => { + return normalizedSecret.slice(index * 6, (index + 1) * 6); + }); +} + +export { + randomEntropy, + randomSecret, + entropyToSecret, + secretToEntropy, + calculateChecksum, + checkChecksum, + parseSecretString, +}; diff --git a/packages/secret-numbers/test/api.test.ts b/packages/secret-numbers/test/api.test.ts new file mode 100644 index 0000000000..e6973ed679 --- /dev/null +++ b/packages/secret-numbers/test/api.test.ts @@ -0,0 +1,99 @@ +import * as keypairs from "ripple-keypairs"; + +import { Account, Utils } from "../src"; + +describe("API: XRPL Secret Numbers", () => { + describe("Generate new account", () => { + const account = new Account(); + it("Output sanity checks", () => { + expect(account.getAddress()).toMatch(/^r[a-zA-Z0-9]{19,}$/u); + const entropy = Utils.secretToEntropy(`${account.toString()}`.split(" ")); + const familySeed = keypairs.generateSeed({ entropy }); + const keypair = keypairs.deriveKeypair(familySeed); + const address = keypairs.deriveAddress(keypair.publicKey); + expect(address).toEqual(account.getAddress()); + expect(familySeed).toEqual(account.getFamilySeed()); + }); + }); + + describe("Account based on entropy", () => { + const entropy = Buffer.from("0123456789ABCDEF0123456789ABCDEF", "hex"); + const account = new Account(entropy); + + it("familySeed as expected", () => { + expect(account.getFamilySeed()).toEqual("sp5DmDCut79BpgumfHhvRzdxXYQyU"); + }); + it("address as expected", () => { + expect(account.getAddress()).toEqual( + "rMCcybKHfwCSkDHd3M36PAeUniEoygwjR3" + ); + }); + it("Account object to string as expected", () => { + const accountAsStr = + "002913 177673 352434 527196 002910 177672 352435 527190"; + expect(`${account.toString()}`).toEqual(accountAsStr); + }); + }); + + describe("Account based on existing secret", () => { + const secret = [ + "084677", + "005323", + "580272", + "282388", + "626800", + "105300", + "560913", + "071783", + ]; + + const account = new Account(secret); + + it("familySeed as expected", () => { + expect(account.getFamilySeed()).toEqual("sswpWwri7Y11dNCSmXdphgcoPZk3y"); + }); + it("publicKey as expected", () => { + const pubkey = + "020526A0EDC9123F7FBB7588402518B80FCD2C8D8AB4C45F5A68A2F220098EA06F"; + expect(account.getKeypair().publicKey).toEqual(pubkey); + }); + it("privateKey as expected", () => { + const privkey = + "005122B2127B4635FEE7D242FA6EC9B02B611C04494D0D7D49764374D90C8BC8D3"; + expect(account.getKeypair().privateKey).toEqual(privkey); + }); + it("address as expected", () => { + expect(account.getAddress()).toEqual( + "rfqJsRLLmr7wdWnEzW1mP6AVaPSdzmso9Z" + ); + }); + it("Account object to string as expected", () => { + const accountAsStr = + "084677 005323 580272 282388 626800 105300 560913 071783"; + expect(`${account.toString()}`).toEqual(accountAsStr); + }); + }); + + describe("Checksum error", () => { + const secret = [ + "084677", + "005324", + "580272", + "626800", + "282388", + "105300", + "560913", + "071783", + ]; + it("Should throw an Checksum Error", () => { + expect(() => { + // eslint-disable-next-line no-new -- Don't want unused variable + new Account(secret); + }) + // TODO: Remove if jest is removed. + // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- Jest and Jasmine have two different signatures. + // @ts-expect-error + .toThrowError(Error, "Invalid secret part: checksum invalid"); + }); + }); +}); diff --git a/packages/secret-numbers/test/index.ts b/packages/secret-numbers/test/index.ts new file mode 100644 index 0000000000..856e1b127a --- /dev/null +++ b/packages/secret-numbers/test/index.ts @@ -0,0 +1 @@ +/* eslint-disable import/unambiguous -- silence is golden */ diff --git a/packages/secret-numbers/test/utils.test.ts b/packages/secret-numbers/test/utils.test.ts new file mode 100644 index 0000000000..190f943a94 --- /dev/null +++ b/packages/secret-numbers/test/utils.test.ts @@ -0,0 +1,107 @@ +import * as utils from "../src/utils"; + +describe("Utils", () => { + it("randomEntropy: valid output", () => { + const data = utils.randomEntropy(); + expect(typeof data).toEqual("object"); + expect(data instanceof Buffer).toBeTruthy(); + expect(data.length).toEqual(16); + expect(data.toString("hex").length).toEqual(32); + expect(data.toString("hex")).toMatch(/^[a-f0-9]+$/u); + }); + + it("calculateChecksum: 1st position", () => { + expect(utils.calculateChecksum(0, 55988)).toEqual(8); + }); + + it("calculateChecksum: 8th position", () => { + expect(utils.calculateChecksum(7, 49962)).toEqual(0); + }); + + it("checkChecksum: 2nd position, split numbers", () => { + expect(utils.checkChecksum(1, 55450, 3)).toBeTruthy(); + }); + + it("checkChecksum: 7th position, split numbers", () => { + expect(utils.checkChecksum(6, 18373, 7)).toBeTruthy(); + }); + + it("checkChecksum: 4th position, as string", () => { + expect(utils.checkChecksum(3, "391566")).toBeTruthy(); + }); + + it("randomSecret: valid checksums", () => { + utils.randomSecret(); + expect(0).toEqual(0); + }); + + it("randomSecret: valid output", () => { + const data = utils.randomSecret(); + expect(Array.isArray(data)).toBeTruthy(); + expect(data.length).toEqual(8); + expect(typeof data[0]).toEqual("string"); + expect(data[0].length).toEqual(6); + expect(data[7].length).toEqual(6); + }); + + it("entropyToSecret", () => { + const entropy = Buffer.from("76ebb2d06879b45b7568fb9c1ded097c", "hex"); + const secret = [ + "304435", + "457766", + "267453", + "461717", + "300560", + "644127", + "076618", + "024286", + ]; + expect(utils.entropyToSecret(entropy)).toEqual(secret); + }); + + it("secretToEntropy", () => { + const secret = [ + "304435", + "457766", + "267453", + "461717", + "300560", + "644127", + "076618", + "024286", + ]; + const entropy = Buffer.from("76ebb2d06879b45b7568fb9c1ded097c", "hex"); + expect(utils.secretToEntropy(secret)).toEqual(entropy); + }); + + it("parseSecretString with spaces valid", () => { + const secret = [ + "304435", + "457766", + "267453", + "461717", + "300560", + "644127", + "076618", + "024286", + ]; + expect( + utils.parseSecretString( + "304435 457766 267453 461717 300560 644127 076618 024286" + ) + ).toEqual(secret); + expect( + utils.parseSecretString( + "304435457766267453461717300560644127076618024286" + ) + ).toEqual(secret); + expect( + utils.parseSecretString(` + 304435 457766 + 267453 461717 + 300560 644127 + 076618 024286 + `) + ).toEqual(secret); + }); +}); diff --git a/packages/secret-numbers/test/webpack.config.js b/packages/secret-numbers/test/webpack.config.js new file mode 100644 index 0000000000..90456787fc --- /dev/null +++ b/packages/secret-numbers/test/webpack.config.js @@ -0,0 +1,61 @@ +"use strict"; +const assert = require("assert"); +const path = require("path"); +const webpack = require("webpack"); +const { merge } = require("webpack-merge"); + +function webpackForTest(testFileName) { + const match = testFileName.match(/\/?([^\/]*)\.ts$/); + if (!match) { + assert(false, "wrong filename:" + testFileName); + } + + const test = merge(require("../webpack.base.config"), { + mode: "production", + cache: true, + entry: testFileName, + output: { + library: match[1].replace(/-/g, "_"), + path: path.join(__dirname, "./testCompiledForWeb/"), + filename: match[1] + ".js", + }, + plugins: [ + new webpack.DefinePlugin({ + "process.stdout": {}, + }), + ], + module: { + rules: [ + // Compile the tests + { + test: /\.ts$/, + use: [ + { + loader: "ts-loader", + options: { + compilerOptions: { + lib: ["esnext", "dom"], + composite: false, + declaration: false, + declarationMap: false, + }, + }, + }, + ], + }, + ], + }, + node: { + global: true, + __filename: false, + __dirname: true, + }, + resolve: { + extensions: [".ts", ".js", ".json"], + }, + }); + + return test; +} + +module.exports = webpackForTest("./test/index.ts"); diff --git a/packages/secret-numbers/tsconfig.build.json b/packages/secret-numbers/tsconfig.build.json new file mode 100644 index 0000000000..34f205ac23 --- /dev/null +++ b/packages/secret-numbers/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + }, + "include": ["./src/**/*.ts", "./src/**/*.json"], + "references": [ + { + "path": "../ripple-keypairs/tsconfig.json" + } + ] +} diff --git a/packages/secret-numbers/tsconfig.eslint.json b/packages/secret-numbers/tsconfig.eslint.json new file mode 100644 index 0000000000..fb1f25450a --- /dev/null +++ b/packages/secret-numbers/tsconfig.eslint.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "include": ["src/**/*.ts", "test/**/*.ts"] +} diff --git a/packages/secret-numbers/tsconfig.json b/packages/secret-numbers/tsconfig.json new file mode 100644 index 0000000000..fcb2dad123 --- /dev/null +++ b/packages/secret-numbers/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "pretty": true, + "target": "es6", + "lib": ["es2019", "dom"], + "outDir": "./dist", + "declaration": true, + "declarationMap": true, + "strictNullChecks": true, + "noImplicitAny": false, + "noUnusedLocals": true, + "removeComments": true, + "preserveConstEnums": false, + "esModuleInterop": true, + "resolveJsonModule": true, + "preserveSymlinks": true + }, + "include": ["src/**/*.ts", "src/**/*.json"] +} diff --git a/packages/secret-numbers/webpack.base.config.js b/packages/secret-numbers/webpack.base.config.js new file mode 100644 index 0000000000..814959ef93 --- /dev/null +++ b/packages/secret-numbers/webpack.base.config.js @@ -0,0 +1,14 @@ +"use strict"; +const { merge } = require("webpack-merge"); +const { getDefaultConfiguration, wrapForEnv } = require("../../webpack.config"); +const path = require("path"); + +module.exports = merge(getDefaultConfiguration(), { + entry: "./dist/index.js", + // overriding the output path and filename + output: { + library: "xrplf_secret_numbers", + filename: `xrplf-secret-numbers.default.js`, + path: path.join(__dirname, "build/"), + }, +}); diff --git a/packages/secret-numbers/webpack.config.js b/packages/secret-numbers/webpack.config.js new file mode 100644 index 0000000000..fa008d687a --- /dev/null +++ b/packages/secret-numbers/webpack.config.js @@ -0,0 +1,8 @@ +const path = require("path"); +const { getDefaultConfiguration, wrapForEnv } = require("../../webpack.config"); +const { merge } = require("webpack-merge"); + +module.exports = wrapForEnv( + "xrplf-secret-numbers", + merge(getDefaultConfiguration(), require("./webpack.base.config")) +); diff --git a/packages/xrpl/HISTORY.md b/packages/xrpl/HISTORY.md index 497e22e3db..2ef3dc68a4 100644 --- a/packages/xrpl/HISTORY.md +++ b/packages/xrpl/HISTORY.md @@ -12,6 +12,7 @@ Subscribe to [the **xrpl-announce** mailing list](https://groups.google.com/g/xr * Instead of passing various parameters on the `ConnectionsOptions` you know specify the `agent` parameter. This object can use be created by libraries such as `https-proxy-agent` or any that implements the `http.Agent`. * This was changed to both support the latest `https-proxy-agent` and to remove the need to include the package in bundlers. Tests will still be done using `https-proxy-agent` and only tested in a node environment which was the only way it was previously supported anyway * Remove `BroadcastClient` which was deprecated +* Uses `@xrplf/secret-numbers` instead of `xrpl-secret-numbers` ### Bundling Changes * Bundler configurations are much more simplified. @@ -188,9 +189,6 @@ Wallet.fromMmnemonic() * `Wallet.fromMnemonic` detects when an invalid encoding is provided, and throws an error * Made unexpected errors in `submitAndWait` more verbose to make them easier to debug. -### Added -* Support for Automated Market Maker (AMM) transactions and requests as defined in XLS-30. - ## 2.3.1 (2022-06-27) ### Fixed * Signing tx with standard currency codes with lowercase and allowed symbols causing an error on decode. diff --git a/packages/xrpl/package.json b/packages/xrpl/package.json index ed11c0bf29..57d8db143c 100644 --- a/packages/xrpl/package.json +++ b/packages/xrpl/package.json @@ -22,6 +22,7 @@ "ws": "./dist/npm/client/WSWrapper.js" }, "dependencies": { + "@xrplf/secret-numbers": "^1.0.0", "bignumber.js": "^9.0.0", "bip32": "^2.0.6", "bip39": "^3.0.4", @@ -29,11 +30,9 @@ "ripple-address-codec": "^4.3.1", "ripple-binary-codec": "^1.10.0", "ripple-keypairs": "^1.3.1", - "ws": "^8.2.2", - "xrpl-secret-numbers": "^0.3.3" + "ws": "^8.2.2" }, "devDependencies": { - "@types/node": "^16.18.38", "https-proxy-agent": "^7.0.1", "karma": "^6.4.1", diff --git a/packages/xrpl/src/Wallet/walletFromSecretNumbers.ts b/packages/xrpl/src/Wallet/walletFromSecretNumbers.ts index 46e110b7c2..1670a5378a 100644 --- a/packages/xrpl/src/Wallet/walletFromSecretNumbers.ts +++ b/packages/xrpl/src/Wallet/walletFromSecretNumbers.ts @@ -1,4 +1,4 @@ -import { Account } from 'xrpl-secret-numbers' +import { Account } from '@xrplf/secret-numbers' import ECDSA from '../ECDSA' diff --git a/packages/xrpl/test/webpack.config.js b/packages/xrpl/test/webpack.config.js index 5fb27d413f..d7017f1f98 100644 --- a/packages/xrpl/test/webpack.config.js +++ b/packages/xrpl/test/webpack.config.js @@ -1,16 +1,8 @@ 'use strict' +const assert = require('assert') const path = require('path') const webpack = require('webpack') -const assert = require('assert') - -const bnJsReplaces = [ - 'tiny-secp256k1', - 'asn1.js', - 'create-ecdh', - 'miller-rabin', - 'public-encrypt', - 'elliptic', -] +const { merge } = require('webpack-merge') function webpackForTest(testFileName) { const match = testFileName.match(/\/?([^\/]*)\.ts$/) @@ -18,17 +10,12 @@ function webpackForTest(testFileName) { assert(false, 'wrong filename:' + testFileName) } - const test = { + return merge(require('../webpack.base.config'), { mode: 'production', cache: true, - performance: { - hints: false, - maxEntrypointSize: 512000, - maxAssetSize: 512000, - }, externals: [ { - net: 'null', + net: 'null', // net is used in tests to setup mock server }, ], entry: testFileName, @@ -38,37 +25,13 @@ function webpackForTest(testFileName) { filename: match[1] + '.js', }, plugins: [ - new webpack.NormalModuleReplacementPlugin(/^ws$/, './WSWrapper'), - new webpack.ProvidePlugin({ - process: 'process/browser', - }), new webpack.DefinePlugin({ 'process.stdout': {}, }), - new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }), - new webpack.IgnorePlugin({ - resourceRegExp: /^\.\/wordlists\/(?!english)/, - contextRegExp: /bip39\/src$/, - }), - // this is a bit of a hack to prevent 'bn.js' from being installed 6 times - // TODO: any package that is updated to use bn.js 5.x needs to be removed from `bnJsReplaces` above - // https://github.com/webpack/webpack/issues/5593#issuecomment-390356276 - new webpack.NormalModuleReplacementPlugin(/^bn.js$/, (resource) => { - if ( - bnJsReplaces.some((pkg) => - resource.context.includes(`node_modules/${pkg}`), - ) - ) { - resource.request = 'diffie-hellman/node_modules/bn.js' - } - }), ], module: { rules: [ - { - test: /jayson/, - use: 'null', - }, + // Compile the tests { test: /\.ts$/, use: [ @@ -93,19 +56,9 @@ function webpackForTest(testFileName) { __dirname: true, }, resolve: { - alias: { - ws: './dist/npm/client/WSWrapper.js', - }, extensions: ['.ts', '.js', '.json'], - fallback: { - module: false, - buffer: require.resolve('buffer/'), - stream: require.resolve('stream-browserify'), - crypto: require.resolve('crypto-browserify'), - }, }, - } - return test + }) } module.exports = [(env, argv) => webpackForTest('./test/integration/index.ts')] diff --git a/packages/xrpl/webpack.base.config.js b/packages/xrpl/webpack.base.config.js new file mode 100644 index 0000000000..f4ca4153cf --- /dev/null +++ b/packages/xrpl/webpack.base.config.js @@ -0,0 +1,26 @@ +const path = require('path') +const webpack = require('webpack') +const { merge } = require('webpack-merge') +const { getDefaultConfiguration } = require('../../webpack.config') + +module.exports = merge(getDefaultConfiguration(), { + entry: './dist/npm/index.js', + // overriding the output path and filename + output: { + library: 'xrpl', + path: path.join(__dirname, 'build/'), + filename: `xrpl.default.js`, + }, + plugins: [ + new webpack.NormalModuleReplacementPlugin(/^ws$/, './WSWrapper'), + new webpack.IgnorePlugin({ + resourceRegExp: /^\.\/wordlists\/(?!english)/, + contextRegExp: /bip39\/src$/, + }), + ], + resolve: { + alias: { + ws: './dist/npm/client/WSWrapper.js', + }, + }, +}) diff --git a/packages/xrpl/webpack.config.js b/packages/xrpl/webpack.config.js index d858e22aa1..ceeb8b10d1 100644 --- a/packages/xrpl/webpack.config.js +++ b/packages/xrpl/webpack.config.js @@ -1,90 +1,8 @@ 'use strict' -const path = require('path') -const webpack = require('webpack') -const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') +const { merge } = require('webpack-merge') +const { getDefaultConfiguration, wrapForEnv } = require('../../webpack.config') -const bnJsReplaces = [ - 'tiny-secp256k1', - 'asn1.js', - 'create-ecdh', - 'miller-rabin', - 'public-encrypt', - 'elliptic', -] - -function getDefaultConfiguration() { - return { - cache: true, - performance: { hints: false }, - stats: 'errors-only', - entry: './dist/npm/index.js', - output: { - library: 'xrpl', - path: path.join(__dirname, 'build/'), - filename: `xrpl.default.js`, - }, - devtool: 'source-map', - plugins: [ - new webpack.NormalModuleReplacementPlugin(/^ws$/, './WSWrapper'), - new webpack.ProvidePlugin({ process: 'process/browser' }), - new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }), - new webpack.IgnorePlugin({ - resourceRegExp: /^\.\/wordlists\/(?!english)/, - contextRegExp: /bip39\/src$/, - }), - // this is a bit of a hack to prevent 'bn.js' from being installed 6 times - // TODO: any package that is updated to use bn.js 5.x needs to be removed from `bnJsReplaces` above - // https://github.com/webpack/webpack/issues/5593#issuecomment-390356276 - new webpack.NormalModuleReplacementPlugin(/^bn.js$/, (resource) => { - if ( - bnJsReplaces.some((pkg) => - resource.context.includes(`node_modules/${pkg}`), - ) - ) { - resource.request = 'diffie-hellman/node_modules/bn.js' - } - }), - ], - module: { - rules: [ - { - test: /\.js$/, - use: ['source-map-loader'], - }, - ], - }, - resolve: { - alias: { - ws: './dist/npm/client/WSWrapper.js', - }, - extensions: ['.js', '.json'], - // We don't want to webpack any of the local dependencies: - // ripple-address-codec, ripple-binary-codec, ripple-keypairs, which are - // symlinked together via lerna - symlinks: false, - fallback: { - buffer: require.resolve('buffer/'), - stream: require.resolve('stream-browserify'), - crypto: require.resolve('crypto-browserify'), - }, - }, - } -} - -module.exports = [ - (env, argv) => { - const config = getDefaultConfiguration() - config.mode = 'development' - config.output.filename = `xrpl-latest.js` - return config - }, - (env, argv) => { - const config = getDefaultConfiguration() - config.mode = 'production' - config.output.filename = `xrpl-latest-min.js` - if (process.argv.includes('--analyze')) { - config.plugins.push(new BundleAnalyzerPlugin()) - } - return config - }, -] +module.exports = wrapForEnv( + 'xrpl', + merge(getDefaultConfiguration(), require('./webpack.base.config')), +) diff --git a/webpack.config.js b/webpack.config.js new file mode 100644 index 0000000000..d602a0da37 --- /dev/null +++ b/webpack.config.js @@ -0,0 +1,96 @@ +"use strict"; +const webpack = require("webpack"); +const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); +const { merge } = require("webpack-merge"); + +// TODO: Remove with #2273 +const bnJsReplaces = [ + "tiny-secp256k1", + "asn1.js", + "create-ecdh", + "miller-rabin", + "public-encrypt", + "elliptic", +]; + +function getDefaultConfiguration() { + return { + cache: true, + performance: { + hints: false, + maxEntrypointSize: 512000, + maxAssetSize: 512000, + }, + stats: "errors-only", + devtool: "source-map", + plugins: [ + new webpack.ProvidePlugin({ process: "process/browser" }), + new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"] }), + // TODO: Remove with #2273 + new webpack.NormalModuleReplacementPlugin(/^bn.js$/, (resource) => { + if ( + bnJsReplaces.some((pkg) => + resource.context.includes(`node_modules/${pkg}`) + ) + ) { + resource.request = "diffie-hellman/node_modules/bn.js"; + } + }), + ], + module: { + rules: [ + { + test: /\.js$/, + use: ["source-map-loader"], + }, + ], + }, + resolve: { + extensions: [".js", ".json"], + // We don't want to webpack any of the local dependencies: + // ripple-address-codec, ripple-binary-codec, ripple-keypairs, which are + // symlinked together via lerna + symlinks: false, + fallback: { + buffer: require.resolve("buffer"), + stream: require.resolve("stream-browserify"), + crypto: require.resolve("crypto-browserify"), + }, + }, + }; +} + +module.exports = { + getDefaultConfiguration, + wrapForEnv: (filename, config) => { + return [ + (env, argv) => { + const localConfig = merge(config, { + mode: "development", + output: { + filename: `${filename}-latest.js`, + }, + }); + return localConfig; + }, + (env, argv) => { + const localConfig = merge(config, { + mode: "production", + output: { + filename: `${filename}-latest.min.js`, + }, + }); + + if (process.argv.includes("--analyze")) { + localConfig.plugins.push( + new BundleAnalyzerPlugin({ + analyzerPort: `auto`, + analyzerMode: "static", + }) + ); + } + return localConfig; + }, + ]; + }, +};