From 1fb1f9d7432a3b9a63b0a4206b99f4f489cca7c4 Mon Sep 17 00:00:00 2001 From: Luke Schoen Date: Fri, 19 Oct 2018 17:33:58 +0200 Subject: [PATCH] docs: Fixes #157. Add Gitbook documentation for Polkadot-JS Common (#231) * fix: Remove prior docs attempt files * docs: Add Gitbook docs for common repo with examples. See detailed comments * Remove old attempt at docs in docs/ folders * Add Typedoc config typedoc.js * Add .nvmrc for easily switching Node.js version with NVM * Add ESLint config .eslintrc.json and .eslintignore * Fix in tsconfig.json so is keyring not util-keyring * Update package.json with dependencies and script same as in polkadot-js/api * Update root README fixing CI icons, adding guide same as in polkadot-js/api, and fixing link to keyring, not util-keyring * Update root .gitignore with Gitbook build files same as in polkadot-js/api * Add Gitbook docs structure same as in polkadot-js/api * Add Gitbook examples for keyring, trie-db, util-crypto * Add Gitbook outer summary for the menu, Readme, logo and styles same as in polkadot-js/api * Add Gitbook config book.json * docs: Remove db and util-rlp from Gitbook summary menu since RLP not in PoC-3 * docs: Add Typedocs with examples for db MemoryDb and DiskDb * docs: Update db/ Readme with CI icons fixed, and indicating that no methods exposed in Common Docs * docs: Update keyring Readme with CI icons fixed and link to Common Docs * fix: Fix keyring package.json info to refer to common, not client * fix: Updates license in 4x files in keyring/address folder with keyring, not util-keyring * docs: Add Typedocs to Keyring class, pair function, and testKeyring function * docs: Update keyring Readme with CI icons fixed and link to Common Docs * fix: Update package.json moving @polkadot/db from devDependencies to dependencies * fix: Update test to iterate array not object with forEach * fix: Use semicolon instead of comma in tests to fix linting errors. Fix typo * docs: Add Typedoc to Trie class * docs: Add Typedoc to is functions * docs: Update keyring Readme with CI icons fixed and link to Common Docs * fix: Add return type to encodeAux function * docs: Add Typedoc to encode function * fix: Fix formatting of Typedoc example for root * docs: Add Typedoc for genRoot * docs: Add Typedoc for pairsUniq * docs: Add Typedoc for getSharedLength * docs: Add Typedoc for sharedPrefixLength * fix: Fix formatting of Typedoc example for rootOrdered, asNibbles, fromNibbles * fix: Various fixes to util-crypto. See commit detail comments * Update root Readme with class and function info * Fix typos and Typedoc examples * Expose mnemonic by exporting it in an index.ts * Fix naming from naclKeypair to naclKeypairFromRandom * Fix typos * Fix randomAsU8s to be randomAsU8a * Fix spelling of bitLength * fix: Various fixes to util-rlp. See detailed commit comments * Update keyring Readme with CI icons fixed and link to Common Docs mentioning since RLP not in PoC-3 nothing exposed in Common Docs * Add Typedocs * Move Typedocs to different file so they appear in Common Docs * fix: Various fixes to util. See detailed commit comments * Update root Readme to use Yarn and list and explain exposed Common Docs methods * Fix typos and Typedoc examples * fix: Restore tests back using variable they were iterating over before * docs: Move nested part of Summary to individual package Readme. Add Usage to Readmes * fix: Add missing semicolon to existing test * fix: Remove docs/gitbook folder and files since generated by CI * feat: Update Gitignore to ignore CI-generated files like .html and docs/gitbook/ folder * docs: Remove CI-icons from all packages within polkadot-js/common, except its root Readme * fix: Update to incorporate changes from PR #233 and #229 * fix: Ignore build directories in Jest tests using modulePathIgnorePatterns * fix: Remove useless docs/html from .gitignore since there is no html subdirectory * fix: Update util-crypto README with link to mnemonicToSeed instead of toSecret * docs: Update keyring create account example to show result to user * fix: Update dependencies in examples so the examples work again * fix: Update keyring example 02 load accounts not to use addFromAddress * fix: Update .gitignore so it is suitable for both polkadot-js common and api * fix: Adjust .gitignore after testing changes that work with polkadot-js api too * fix: Resolve .gitignore to overcome FileNotFoundError: No README file (or is ignored) * fix: Remove from Git tracking docs/.nojekyll since generated * fix: Add lerna to gitignore to match api repo * Revert to original .gitignore. Does not work without Gitbooks files Git tracked * docs: Hide trie-db Examples since have limited use --- .eslintignore | 2 + .eslintrc.json | 5 + .gitignore | 4 +- .nvmrc | 1 + README.md | 36 ++-- book.json | 24 +++ docs/CONTRIBUTING.md | 46 +++++ docs/GLOSSARY.md | 0 docs/README.md | 38 +++++ docs/SUMMARY.md | 18 ++ docs/examples/.gitignore | 1 + .../keyring/01_create_account/README.md | 5 + .../keyring/01_create_account/index.js | 19 +++ .../keyring/01_create_account/package.json | 19 +++ .../keyring/02_load_accounts/README.md | 5 + .../keyring/02_load_accounts/index.js | 31 ++++ .../keyring/02_load_accounts/package.json | 19 +++ docs/examples/keyring/README.md | 12 ++ .../trie-db/01_create_patricia_trie/README.md | 5 + .../trie-db/01_create_patricia_trie/index.js | 13 ++ .../01_create_patricia_trie/package.json | 19 +++ .../02_get_set_del_trie_nodes/README.md | 5 + .../02_get_set_del_trie_nodes/index.js | 48 ++++++ .../02_get_set_del_trie_nodes/package.json | 19 +++ .../03_duplicate_trie_with_snapshot/README.md | 5 + .../03_duplicate_trie_with_snapshot/index.js | 24 +++ .../package.json | 19 +++ .../04_show_size_trie_node_info/README.md | 5 + .../04_show_size_trie_node_info/index.js | 65 +++++++ .../04_show_size_trie_node_info/package.json | 19 +++ .../05_empty_close_drop_trie/README.md | 5 + .../trie-db/05_empty_close_drop_trie/index.js | 55 ++++++ .../05_empty_close_drop_trie/package.json | 19 +++ docs/examples/trie-db/README.md | 12 ++ .../01_encrypt_decrypt_message_nacl/README.md | 5 + .../01_encrypt_decrypt_message_nacl/index.js | 24 +++ .../package.json | 18 ++ .../02_sign_verify_message_nacl/README.md | 5 + .../02_sign_verify_message_nacl/index.js | 32 ++++ .../02_sign_verify_message_nacl/package.json | 18 ++ .../README.md | 5 + .../index.js | 26 +++ .../package.json | 18 ++ docs/examples/util-crypto/README.md | 13 ++ docs/logo.png | Bin 0 -> 7497 bytes docs/styles/website.css | 48 ++++++ jest.config.js | 11 +- package.json | 9 +- packages/db/README.md | 32 +++- packages/db/src/Disk.ts | 55 ++++++ packages/db/src/Memory.ts | 56 ++++++ .../src/engines/unused/LevelDb.spec.js-unused | 16 +- .../src/engines/unused/RocksDb.spec.js-unused | 16 +- packages/keyring/README.md | 39 +++-- packages/keyring/docs/README.md | 8 - packages/keyring/docs/address.md | 3 - packages/keyring/docs/pair.md | 3 - packages/keyring/package.json | 6 +- packages/keyring/src/address/defaults.ts | 2 +- .../keyring/src/address/setPrefix.spec.js | 2 +- packages/keyring/src/address/setPrefix.ts | 2 +- packages/keyring/src/address/types.d.ts | 2 +- packages/keyring/src/index.ts | 160 ++++++++++++++++++ packages/keyring/src/pair/index.ts | 32 ++++ packages/keyring/src/testing.ts | 22 +++ packages/trie-db/README.md | 30 +++- packages/trie-db/package.json | 4 +- packages/trie-db/src/ethereum.spec.js | 2 +- packages/trie-db/src/index.spec.js | 24 +-- packages/trie-db/src/index.ts | 9 + packages/trie-db/src/util/is.ts | 30 ++++ packages/trie-hash/README.md | 48 ++++-- packages/trie-hash/docs/README.md | 48 ------ packages/trie-hash/src/encode/aux.ts | 2 +- packages/trie-hash/src/encode/index.ts | 24 +++ packages/trie-hash/src/root.ts | 16 +- packages/trie-hash/src/rootOrdered.ts | 16 +- packages/trie-hash/src/util/asNibbles.ts | 8 +- packages/trie-hash/src/util/fromNibbles.ts | 8 +- packages/trie-hash/src/util/genRoot.ts | 5 + packages/trie-hash/src/util/pairsUniq.ts | 5 + packages/trie-hash/src/util/sharedLength.ts | 8 + .../trie-hash/src/util/sharedPrefixLength.ts | 4 + packages/util-crypto/README.md | 113 +++++++++++-- packages/util-crypto/docs/README.md | 11 -- packages/util-crypto/docs/blake2.md | 40 ----- packages/util-crypto/docs/keccak.md | 40 ----- packages/util-crypto/docs/nacl.md | 76 --------- packages/util-crypto/docs/random.md | 58 ------- packages/util-crypto/docs/sha512.md | 22 --- packages/util-crypto/docs/xxhash.md | 40 ----- packages/util-crypto/src/blake2/asHex.ts | 10 +- packages/util-crypto/src/blake2/asU8a.ts | 10 +- .../util-crypto/src/blake2/blake2b/asHex.ts | 8 +- .../util-crypto/src/blake2/blake2b/asU8a.ts | 8 +- packages/util-crypto/src/index.ts | 1 + packages/util-crypto/src/keccak/asHex.ts | 8 +- packages/util-crypto/src/keccak/asU8a.ts | 8 +- packages/util-crypto/src/mnemonic/generate.ts | 13 ++ packages/util-crypto/src/mnemonic/index.ts | 3 + packages/util-crypto/src/mnemonic/toSeed.ts | 18 ++ packages/util-crypto/src/mnemonic/validate.ts | 14 ++ packages/util-crypto/src/nacl/decrypt.ts | 8 +- packages/util-crypto/src/nacl/encrypt.ts | 8 +- .../src/nacl/keypair/fromRandom.ts | 10 +- .../src/nacl/keypair/fromSecret.ts | 8 +- .../util-crypto/src/nacl/keypair/fromSeed.ts | 8 +- .../src/nacl/keypair/fromString.ts | 8 +- packages/util-crypto/src/nacl/sign.ts | 8 +- packages/util-crypto/src/nacl/verify.ts | 8 +- packages/util-crypto/src/random/asHex.spec.js | 2 +- packages/util-crypto/src/random/asHex.ts | 8 +- packages/util-crypto/src/random/asNumber.ts | 8 +- packages/util-crypto/src/random/asU8a.ts | 8 +- packages/util-crypto/src/sha512/asU8a.ts | 8 +- packages/util-crypto/src/xxhash/asHex.ts | 10 +- packages/util-crypto/src/xxhash/asU8a.ts | 10 +- .../util-crypto/src/xxhash/xxhash64/asBn.ts | 8 +- .../util-crypto/src/xxhash/xxhash64/asHex.ts | 8 +- .../util-crypto/src/xxhash/xxhash64/asRaw.ts | 8 +- .../src/xxhash/xxhash64/asValue.ts | 15 ++ packages/util-rlp/README.md | 50 ++++-- packages/util-rlp/docs/README.md | 40 ----- packages/util-rlp/src/decode.ts | 11 -- packages/util-rlp/src/decoder/index.ts | 15 ++ packages/util-rlp/src/encode.ts | 11 -- packages/util-rlp/src/encoder/index.ts | 15 ++ packages/util/README.md | 46 +++-- packages/util/src/array/filter.ts | 10 +- packages/util/src/assert.ts | 12 +- packages/util/src/bn/toBn.ts | 12 +- packages/util/src/bn/toHex.ts | 10 +- packages/util/src/bn/toU8a.ts | 8 +- packages/util/src/buffer/toU8a.ts | 8 +- packages/util/src/ext/error.ts | 8 +- packages/util/src/hex/addPrefix.ts | 8 +- packages/util/src/hex/fixLength.ts | 12 +- packages/util/src/hex/hasPrefix.ts | 8 +- packages/util/src/hex/stripPrefix.ts | 8 +- packages/util/src/hex/toBn.ts | 8 +- packages/util/src/hex/toNumber.ts | 8 +- packages/util/src/hex/toU8a.ts | 10 +- packages/util/src/is/bn.ts | 10 +- packages/util/src/is/boolean.ts | 8 +- packages/util/src/is/buffer.ts | 8 +- packages/util/src/is/error.ts | 8 +- packages/util/src/is/function.ts | 8 +- packages/util/src/is/hex.ts | 10 +- packages/util/src/is/instanceOf.ts | 8 +- packages/util/src/is/ip.ts | 14 +- packages/util/src/is/null.ts | 8 +- packages/util/src/is/number.ts | 8 +- packages/util/src/is/object.ts | 10 +- packages/util/src/is/observable.ts | 8 +- packages/util/src/is/string.ts | 8 +- packages/util/src/is/u8a.ts | 8 +- packages/util/src/is/undefined.ts | 8 +- packages/util/src/logger.ts | 10 +- packages/util/src/number/toHex.ts | 10 +- packages/util/src/number/toU8a.ts | 8 +- packages/util/src/promisify.ts | 10 +- packages/util/src/string/lowerFirst.ts | 8 +- packages/util/src/string/shorten.ts | 8 +- packages/util/src/string/toU8a.ts | 8 +- packages/util/src/string/upperFirst.ts | 8 +- packages/util/src/u8a/concat.ts | 14 +- packages/util/src/u8a/fixLength.ts | 12 +- packages/util/src/u8a/toBn.ts | 8 +- packages/util/src/u8a/toBuffer.ts | 8 +- packages/util/src/u8a/toHex.ts | 8 +- packages/util/src/u8a/toString.ts | 8 +- packages/util/src/u8a/toU8a.ts | 10 +- tsconfig.json | 2 +- typedoc.js | 16 ++ 174 files changed, 2158 insertions(+), 709 deletions(-) create mode 100644 .eslintignore create mode 100644 .eslintrc.json create mode 100644 .nvmrc create mode 100644 book.json create mode 100644 docs/CONTRIBUTING.md create mode 100644 docs/GLOSSARY.md create mode 100644 docs/README.md create mode 100644 docs/SUMMARY.md create mode 100644 docs/examples/.gitignore create mode 100644 docs/examples/keyring/01_create_account/README.md create mode 100755 docs/examples/keyring/01_create_account/index.js create mode 100644 docs/examples/keyring/01_create_account/package.json create mode 100644 docs/examples/keyring/02_load_accounts/README.md create mode 100755 docs/examples/keyring/02_load_accounts/index.js create mode 100644 docs/examples/keyring/02_load_accounts/package.json create mode 100644 docs/examples/keyring/README.md create mode 100644 docs/examples/trie-db/01_create_patricia_trie/README.md create mode 100755 docs/examples/trie-db/01_create_patricia_trie/index.js create mode 100644 docs/examples/trie-db/01_create_patricia_trie/package.json create mode 100644 docs/examples/trie-db/02_get_set_del_trie_nodes/README.md create mode 100755 docs/examples/trie-db/02_get_set_del_trie_nodes/index.js create mode 100644 docs/examples/trie-db/02_get_set_del_trie_nodes/package.json create mode 100644 docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md create mode 100755 docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js create mode 100644 docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json create mode 100644 docs/examples/trie-db/04_show_size_trie_node_info/README.md create mode 100755 docs/examples/trie-db/04_show_size_trie_node_info/index.js create mode 100644 docs/examples/trie-db/04_show_size_trie_node_info/package.json create mode 100644 docs/examples/trie-db/05_empty_close_drop_trie/README.md create mode 100755 docs/examples/trie-db/05_empty_close_drop_trie/index.js create mode 100644 docs/examples/trie-db/05_empty_close_drop_trie/package.json create mode 100644 docs/examples/trie-db/README.md create mode 100644 docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/README.md create mode 100755 docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js create mode 100644 docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/package.json create mode 100644 docs/examples/util-crypto/02_sign_verify_message_nacl/README.md create mode 100755 docs/examples/util-crypto/02_sign_verify_message_nacl/index.js create mode 100644 docs/examples/util-crypto/02_sign_verify_message_nacl/package.json create mode 100644 docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/README.md create mode 100755 docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js create mode 100644 docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/package.json create mode 100644 docs/examples/util-crypto/README.md create mode 100644 docs/logo.png create mode 100644 docs/styles/website.css delete mode 100644 packages/keyring/docs/README.md delete mode 100644 packages/keyring/docs/address.md delete mode 100644 packages/keyring/docs/pair.md delete mode 100644 packages/trie-hash/docs/README.md delete mode 100644 packages/util-crypto/docs/README.md delete mode 100644 packages/util-crypto/docs/blake2.md delete mode 100644 packages/util-crypto/docs/keccak.md delete mode 100644 packages/util-crypto/docs/nacl.md delete mode 100644 packages/util-crypto/docs/random.md delete mode 100644 packages/util-crypto/docs/sha512.md delete mode 100644 packages/util-crypto/docs/xxhash.md delete mode 100644 packages/util-rlp/docs/README.md create mode 100644 typedoc.js diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..8fcb34f2b --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +**/build/* +**/node_modules/* diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 000000000..168417947 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "./node_modules/@polkadot/dev/config/eslint.js" + ] +} diff --git a/.gitignore b/.gitignore index 17bec4699..30384b275 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ _book/ build/ coverage/ -docs/ node_modules/ tmp/ .DS_Store @@ -9,8 +8,9 @@ tmp/ .env.development.local .env.test.local .env.production.local -package-lock.json +lerna-debug.log* npm-debug.log* +package-lock.json yarn-debug.log* yarn-error.log* store.db diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 000000000..f599e28b8 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +10 diff --git a/README.md b/README.md index 1a82b07f8..f606588fe 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,22 @@ [![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) ![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square) [![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/util.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/util) -[![travis](https://img.shields.io/travis/polkadot-js/util.svg?style=flat-square)](https://travis-ci.org/polkadot-js/util) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/util.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/util/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/util.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/util?branch=master) +[![travis](https://img.shields.io/travis/polkadot-js/common.svg?style=flat-square)](https://travis-ci.org/polkadot-js/common) +[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common/maintainability) +[![coverage](https://img.shields.io/coveralls/polkadot-js/common.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/common?branch=master) [![greenkeeper](https://img.shields.io/badge/greenkeeper-enabled-brightgreen.svg?style=flat-square)](https://greenkeeper.io/) -[![dependency](https://david-dm.org/polkadot-js/util.svg?style=flat-square)](https://david-dm.org/polkadot-js/util) -[![devDependency](https://david-dm.org/polkadot-js/util/dev-status.svg?style=flat-square)](https://david-dm.org/polkadot-js/util#info=devDependencies) -# @polkadot/util +# @polkadot/common Various useful utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. +## overview + It is split up into a number of internal packages, namely utilities - +- [keyring](packages/keyring/) Keyring management - [util](packages/util/) General utilities - [util-crypto](packages/util-crypto/) Crypto and hashing utilities -- [util-keyring](packages/util-keyring/) Keyring management - [util-rlp](packages/util-rlp/) RLP encoding & decoding Various useful trie and database interfaces - @@ -26,7 +25,22 @@ Various useful trie and database interfaces - - [trie-db](packages/trie-db/) Merkle Patricia Tree implementation adapcted for Polkadot - [trie-hash](packages/trie-hash/) Calculate hashes (either ordered or unordered) from a set of inputs -## Contributing +## development -- Bootstrap the dependencies, `yarn` -- Make any changes in the relevant package, on master merges new versions will be published automatically to npmjs +Contributions are welcome! + +To start off, this repo (along with others in the [@polkadot](https://github.com/polkadot-js/) family) uses yarn workspaces to organise the code. As such, after cloning, its dependencies _should_ be installed via `yarn`, not via npm; the latter will result in broken dependencies. + +To get started - + +1. Clone the repo locally, via `git clone https://github.com/polkadot-js/common ` +2. Ensure that you have a recent version of Node.js, for development purposes [Node 10](https://nodejs.org/en/) is recommended. +3. Ensure that you have a recent version of Yarn, for development purposes [Yarn >=1.3.2](https://yarnpkg.com/docs/install) is required. +4. Install the dependencies by running `yarn` +5. Build the API Docs, via `yarn run build` +6. Ready! Now you can launch the API Docs, via `yarn gitbook serve` +7. Access the API Docs via [http://localhost:4000](http://localhost:4000) + +## tutorials + +Looking for tutorials to get started? Look at [examples](https://polkadot.js.org/api/examples/keyring/) for guides on how to use the API. diff --git a/book.json b/book.json new file mode 100644 index 000000000..f773bd9f6 --- /dev/null +++ b/book.json @@ -0,0 +1,24 @@ +{ + "title": "Polkadot Common Book", + "gitbook": ">=2.4.0", + "plugins": [ + "include-codeblock", + "insert-logo-link", + "mermaid-gb3", + "-highlight", + "sunlight-highlighter" + ], + "root": "docs", + "pluginsConfig": { + "insert-logo-link": { + "src": "/common/logo.png", + "url": "https://polkadot.js.org" + }, + "sunlight-highlighter": { + "theme": "gitbook" + } + }, + "styles": { + "website": "styles/website.css" + } +} diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 000000000..3df749e6f --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,46 @@ +# Contributing + +## What? + +Individuals making significant and valuable contributions are given commit-access to a project to contribute as they see fit. +A project is more like an open wiki than a standard guarded open source project. + +## Rules + +There are a few basic ground-rules for contributors (including the maintainer(s) of the project): + +. **No `--force` pushes** or modifying the Git history in any way. If you need to rebase, ensure you do it in your own repo. +. **Non-master branches**, prefixed with a short name moniker (e.g. `-`) must be used for ongoing work. +. **All modifications** must be made in a **pull-request** to solicit feedback from other contributors. +. A pull-request *must not be merged until CI* has finished successfully. + +Merging pull requests once CI is successful: + +. A pull request with no large change to logic that is an urgent fix may be merged after a non-author contributor has reviewed it well. +. No PR should be merged until all reviews' comments are addressed. + +.Reviewing pull requests: +When reviewing a pull request, the end-goal is to suggest useful changes to the author. Reviews should finish with approval unless there are issues that would result in: + +. Buggy behaviour. +. Undue maintenance burden. +. Breaking with house coding style. +. Pessimisation (i.e. reduction of speed as measured in the projects benchmarks). +. Feature reduction (i.e. it removes some aspect of functionality that a significant minority of users rely on). +. Uselessness (i.e. it does not strictly add a feature or fix a known issue). + +.Reviews may not be used as an effective veto for a PR because: +. There exists a somewhat cleaner/better/faster way of accomplishing the same feature/fix. +. It does not fit well with some other contributors' longer-term vision for the project. + +## Releases + +Declaring formal releases remains the prerogative of the project maintainer(s). + +## Changes to this arrangement + +This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change. + +## Heritage + +These contributing guidelines are modified from the "OPEN Open Source Project" guidelines for the Level project: https://github.com/Level/community/blob/master/CONTRIBUTING.md diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..87631ce62 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,38 @@ +# Polkadot Javascript Common + +Various useful utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. + +It is split up into a number of internal packages, namely utilities - + +- [keyring](keyring/README.md) Keyring management +- [util](util/README.md) General utilities +- [util-crypto](util-crypto/README.md) Crypto and hashing utilities +- [util-rlp](util-rlp/README.md) RLP encoding & decoding + +Various useful trie and database interfaces - + +- [db](db/README.md) Sync memory and disk database interfaces +- [trie-db](trie-db/README.md) Merkle Patricia Tree implementation adapcted for Polkadot +- [trie-hash](trie-hash/README.md) Calculate hashes (either ordered or unordered) from a set of inputs + +This guide describes Polkadot Javascript Common. + +{% include "SUMMARY.md" %} + +## The Polkadot Project + +You can read more about the Polkadot Network at https://polkadot.network/ + +## Github repositories + +You can find the Polkadot repositories at: + +- https://github.com/polkadot-js +- https://github.com/paritytech/polkadot +- https://github.com/paritytech/substrate + +This documentation is generated from https://github.com/polkadot-js/api + +## Contributing + +Contribution to Polkadot JS Common are more than welcome. You can [report issues](https://github.com/polkadot-js/common/issues/new) and [log feature requests](https://github.com/polkadot-js/common/issues/new). diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md new file mode 100644 index 000000000..b34aa406a --- /dev/null +++ b/docs/SUMMARY.md @@ -0,0 +1,18 @@ +## Packages + +- [keyring](keyring/README.md) +- [trie-db](trie-db/README.md) +- [trie-hash](trie-hash/README.md) +- [util](util/README.md) +- [util-crypto](util-crypto/README.md) + +## Examples + +- [Keyring](examples/keyring/README.md) + - [Create Account](examples/keyring/01_create_account/README.md) + - [Load Accounts](examples/keyring/02_load_accounts/README.md) +- [Util-Crypto](examples/util-crypto/README.md) + - [Encrypt & Decrypt Message](examples/util-crypto/01_encrypt_decrypt_message_nacl/README.md) + - [Sign & Verify Message](examples/util-crypto/02_sign_verify_message_nacl/README.md) + - [Create & Validate Mnemonic](examples/util-crypto/03_mnemonic_generate_validate_bip39/README.md) + diff --git a/docs/examples/.gitignore b/docs/examples/.gitignore new file mode 100644 index 000000000..8ee01d321 --- /dev/null +++ b/docs/examples/.gitignore @@ -0,0 +1 @@ +yarn.lock diff --git a/docs/examples/keyring/01_create_account/README.md b/docs/examples/keyring/01_create_account/README.md new file mode 100644 index 000000000..c8f26fdf3 --- /dev/null +++ b/docs/examples/keyring/01_create_account/README.md @@ -0,0 +1,5 @@ +# Create Account + +The following example shows how to create and account with keyring. + +[include](index.js) diff --git a/docs/examples/keyring/01_create_account/index.js b/docs/examples/keyring/01_create_account/index.js new file mode 100755 index 000000000..79cdd2807 --- /dev/null +++ b/docs/examples/keyring/01_create_account/index.js @@ -0,0 +1,19 @@ +// Import Keyring class and utility function +const Keyring = require('@polkadot/keyring').default; +const stringToU8a = require('@polkadot/util/string/toU8a').default; + +async function main () { + // Create account seed for Alice + const ALICE_SEED = 'Alice'.padEnd(32, ' '); + + // Create an instance of the Keyring + const keyring = new Keyring(); + + // Create pair and add Alice to keyring pair dictionary (with account seed) + const pairAlice = keyring.addFromSeed(stringToU8a(ALICE_SEED)); + + console.log(`Created keyring pair for Alice with address: ` + + `${keyring.getPair(pairAlice.address()).address()}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/keyring/01_create_account/package.json b/docs/examples/keyring/01_create_account/package.json new file mode 100644 index 000000000..6e485ff23 --- /dev/null +++ b/docs/examples/keyring/01_create_account/package.json @@ -0,0 +1,19 @@ +{ + "name": "01_create_account", + "version": "0.1.0", + "description": "Example showing how to create an account", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/util": "^0.32.2", + "@polkadot/keyring": "^0.32.1" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/keyring/02_load_accounts/README.md b/docs/examples/keyring/02_load_accounts/README.md new file mode 100644 index 000000000..3b6934260 --- /dev/null +++ b/docs/examples/keyring/02_load_accounts/README.md @@ -0,0 +1,5 @@ +# Load Accounts + +The following example shows how to load all accounts from the keyring as pairs and convert them into JSON format. + +[include](index.js) diff --git a/docs/examples/keyring/02_load_accounts/index.js b/docs/examples/keyring/02_load_accounts/index.js new file mode 100755 index 000000000..04acdbb6f --- /dev/null +++ b/docs/examples/keyring/02_load_accounts/index.js @@ -0,0 +1,31 @@ +// Import Keyring class and utility function +const Keyring = require('@polkadot/keyring').default; +const stringToU8a = require('@polkadot/util/string/toU8a').default; + +async function main () { + // Create account seed for Alice and Bob + const ALICE_SEED = 'Alice'.padEnd(32, ' '); + const BOB_SEED = 'Bob'.padEnd(32, ' '); + + // Create an instance of the Keyring + const keyring = new Keyring(); + + // Create their pairs with account seeds. Add to keyring pair dictionary + keyring.addFromSeed(stringToU8a(ALICE_SEED)); + keyring.addFromSeed(stringToU8a(BOB_SEED)); + + // Note that we did not use `addFromAddress` since it does not add the + // secret key to memory so we cannot later retrieve it with `getPairs` + + // Retrieve all keyring pairs from the keyring pair dictionary + keyring + .getPairs() + .forEach((pair, index) => { + const address = pair.address(); + + console.log(`${index} account has json: `, + JSON.stringify(keyring.toJson(address), null, 2)); + }); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/keyring/02_load_accounts/package.json b/docs/examples/keyring/02_load_accounts/package.json new file mode 100644 index 000000000..f334a8dc4 --- /dev/null +++ b/docs/examples/keyring/02_load_accounts/package.json @@ -0,0 +1,19 @@ +{ + "name": "02_load_accounts", + "version": "0.1.0", + "description": "Example showing how to load accounts", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/util": "^0.32.2", + "@polkadot/keyring": "^0.32.1" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/keyring/README.md b/docs/examples/keyring/README.md new file mode 100644 index 000000000..f00cfb416 --- /dev/null +++ b/docs/examples/keyring/README.md @@ -0,0 +1,12 @@ +# Keyring Examples + +Here you will find a list of examples that takes you through the basics of connecting to a local node, retrieving data from the Node and chain and execute transactions on the chain. + +## Running the examples + +From within each folder run the following to install required dependencies and to execute the example: +```shell +yarn; +yarn start +``` + diff --git a/docs/examples/trie-db/01_create_patricia_trie/README.md b/docs/examples/trie-db/01_create_patricia_trie/README.md new file mode 100644 index 000000000..40e45cdd6 --- /dev/null +++ b/docs/examples/trie-db/01_create_patricia_trie/README.md @@ -0,0 +1,5 @@ +# Create Patricia Trie + +The following example shows how to create a Patricia Trie. + +[include](index.js) diff --git a/docs/examples/trie-db/01_create_patricia_trie/index.js b/docs/examples/trie-db/01_create_patricia_trie/index.js new file mode 100755 index 000000000..6bae9e587 --- /dev/null +++ b/docs/examples/trie-db/01_create_patricia_trie/index.js @@ -0,0 +1,13 @@ +const Trie = require('@polkadot/trie-db').default; + +async function main () { + const trie = new Trie(); + + // Open the database for each of the trie instances + trie.open(); + + // Initial root value is valid + console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/01_create_patricia_trie/package.json b/docs/examples/trie-db/01_create_patricia_trie/package.json new file mode 100644 index 000000000..17952a2b6 --- /dev/null +++ b/docs/examples/trie-db/01_create_patricia_trie/package.json @@ -0,0 +1,19 @@ +{ + "name": "01_create_patricia_trie", + "version": "0.1.0", + "description": "Example showing how to create a Patricia Trie", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/trie-db": "^0.32.1", + "@polkadot/db": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md b/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md new file mode 100644 index 000000000..7740be5e2 --- /dev/null +++ b/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md @@ -0,0 +1,5 @@ +# Get & Set & Delete Trie Nodes + +The following example shows how to get, set, and delete nodes of a Patricia Trie. + +[include](index.js) diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js b/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js new file mode 100755 index 000000000..fd6dd56ab --- /dev/null +++ b/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js @@ -0,0 +1,48 @@ +const toU8a = require('@polkadot/util/u8a/toU8a').default; +const Trie = require('@polkadot/trie-db').default; + +async function main () { + const trie = new Trie(); + + // Open the database for each of the trie instances + trie.open(); + + // Initial root value is valid + console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); + + // Create a branch under the trie root with a key of 'test' and a value of 'one' + trie.put(toU8a('test'), toU8a('one')); + + // Store the root hash of the trie root node in a variable + const trieRootNodeHash = trie.getRoot(); + + // Store the root node object in a variable + const trieRootNode = trie.getNode(trieRootNodeHash); + + // Show the node object of the root node hash + console.log(`Root node object: ${trieRootNode}`); + + // Show the updated root hash value of the trie root node + console.log(`Updated root hash value: ${trie.getRoot()}`); + + const branch = trie.get(toU8a('test')); + // Retrieve the value of a given key named 'test' in the trie + console.log(`Current value of key 'test': ${branch}`); + + // Deletes the value of a given key named 'test' in the trie branch + trie.del(toU8a('test')); + + // Retrieve the value of a given key named 'test' in the trie + console.log(`Updated value of key 'test' after deleting it: ${trie.get(toU8a('test'))}`); + + // Set the root hash value of the trie root node (if necessary) + trie.setRoot(trieRootNodeHash); + + // Show the node object of the root node hash + console.log(`Root node object: ${trie.getRoot()}`); + + // Retrieve the value of a given key named 'test' in the trie + console.log(`Restored value of key 'test' after restoring root node: ${branch}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json b/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json new file mode 100644 index 000000000..68f0c8f27 --- /dev/null +++ b/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json @@ -0,0 +1,19 @@ +{ + "name": "02_get_set_del_trie_nodes", + "version": "0.1.0", + "description": "Example showing how to get, set, and delete nodes of a Patricia Trie", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/trie-db": "^0.32.1", + "@polkadot/db": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md new file mode 100644 index 000000000..9e4418910 --- /dev/null +++ b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md @@ -0,0 +1,5 @@ +# Duplicate Patricia Trie with Snapshot + +The following example shows how to duplicate a Patricia Trie by taking a snapshot. + +[include](index.js) diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js new file mode 100755 index 000000000..1004b823d --- /dev/null +++ b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js @@ -0,0 +1,24 @@ +const Trie = require('@polkadot/trie-db').default; + +async function main () { + const trie = new Trie(); + + // Use `back` to later store a snapshot of the `trie` + const back = new Trie(); + + // Open the database for each of the trie instances + trie.open(); + back.open(); + + // Initial root value is valid + console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); + + // Create a snapshot of the `trie` data into `back` + trie.snapshot(back, () => {}); + + // Show value of snapshot's root is same as original trie's root + console.log(`Snapshot root value matches original trie root: ` + + `${back.getRoot() === trie.getRoot()}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json new file mode 100644 index 000000000..f17309761 --- /dev/null +++ b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json @@ -0,0 +1,19 @@ +{ + "name": "03_duplicate_trie_with_snapshot", + "version": "0.1.0", + "description": "Example showing how to duplicate Patricia Trie nodes with a snapshot", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/trie-db": "^0.32.1", + "@polkadot/db": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/README.md b/docs/examples/trie-db/04_show_size_trie_node_info/README.md new file mode 100644 index 000000000..67358aea3 --- /dev/null +++ b/docs/examples/trie-db/04_show_size_trie_node_info/README.md @@ -0,0 +1,5 @@ +# Show Size and Node Info of a Patricia Trie + +The following example shows how to show the size and node information of a Patricia Trie. + +[include](index.js) diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/index.js b/docs/examples/trie-db/04_show_size_trie_node_info/index.js new file mode 100755 index 000000000..9b9961b8d --- /dev/null +++ b/docs/examples/trie-db/04_show_size_trie_node_info/index.js @@ -0,0 +1,65 @@ +const toU8a = require('@polkadot/util/u8a/toU8a').default; +const Trie = require('@polkadot/trie-db').default; +const { + isEmptyNode, + isKvNode, + isExtensionNode, + isLeafNode, + isBranchNode +} = require('@polkadot/trie-db/util/is'); + +async function main () { + const trie = new Trie(); + + // Use `back` to later store a snapshot of the `trie` + const back = new Trie(); + + // Open the database for each of the trie instances + trie.open(); + back.open(); + + // Initial root value is valid + console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); + + // Create two branches under the trie root with + // key 'branch1' and 'branch2' and a values of 'one' and 'two' + trie.put(toU8a('test'), toU8a('one')); + trie.put(toU8a('test'), toU8a('two')); + + // Store the root hash of the trie root node in a variable + const trieRootNodeHash = trie.getRoot(); + + // Store the root node object in a variable + const trieRootNode = trie.getNode(trieRootNodeHash); + + // Show the node object of the root node hash + console.log(`Root node object: ${trieRootNode}`); + + // Show information about the trie node + console.log(`Is root node object empty? : ${isEmptyNode(trieRootNode)}`); + console.log(`Is root node object a KV node? : ${isKvNode(trieRootNode)}`); + + // Show information about the trie that is Merkle Patricia Trie specific + // Reference: https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization + console.log(`Is root node object an Extension node? : ${isExtensionNode(trieRootNode)}`); + console.log(`Is root node object an Leaf node? : ${isLeafNode(trieRootNode)}`); + console.log(`Is root node object an Branch node? : ${isBranchNode(trieRootNode)}`); + + // Retrieve the value of a given key named 'test' in the trie + console.log(`Current value of key 'test': ${trie.get(toU8a('test'))}`); + + // Create a snapshot of the `trie` data into `back` + trie.snapshot(back, () => {}); + + // Show that value of the snapshot's root is the same as the original trie's root + console.log(`Snapshot root value matches original trie root: ${back.getRoot() === trie.getRoot()}`); + + // Deletes the value of a given key named 'test' in the trie branch + trie.del(toU8a('test')); + + // Show size of the database for each of the trie instances + console.log(`Size of 'trie' database: ${trie.size()}`); + console.log(`Size of 'back' database: ${back.size()}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/package.json b/docs/examples/trie-db/04_show_size_trie_node_info/package.json new file mode 100644 index 000000000..6115f5635 --- /dev/null +++ b/docs/examples/trie-db/04_show_size_trie_node_info/package.json @@ -0,0 +1,19 @@ +{ + "name": "04_show_size_trie_node_info", + "version": "0.1.0", + "description": "Example showing how to show size and node info of a Patricia Trie", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/trie-db": "^0.32.1", + "@polkadot/db": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/README.md b/docs/examples/trie-db/05_empty_close_drop_trie/README.md new file mode 100644 index 000000000..b0ea20678 --- /dev/null +++ b/docs/examples/trie-db/05_empty_close_drop_trie/README.md @@ -0,0 +1,5 @@ +# Empty & Close & Drop a Patricia Trie + +The following example shows how to empty, close, and drop a Patricia Trie. + +[include](index.js) diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/index.js b/docs/examples/trie-db/05_empty_close_drop_trie/index.js new file mode 100755 index 000000000..8cac90e97 --- /dev/null +++ b/docs/examples/trie-db/05_empty_close_drop_trie/index.js @@ -0,0 +1,55 @@ +const toU8a = require('@polkadot/util/u8a/toU8a').default; +const Trie = require('@polkadot/trie-db').default; +const { + isEmptyNode, + isKvNode +} = require('@polkadot/trie-db/util/is'); + +async function main () { + const trie = new Trie(); + + // Open the database for each of the trie instances + trie.open(); + + // Initial root value is valid + console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); + + // Create a branch under the trie root with a key of 'branch1' and 'branch2' + // and a value of 'one' and 'two' + trie.put(toU8a('branch1'), toU8a('one')); + trie.put(toU8a('branch2'), toU8a('two')); + + // Retrieve the value of a given key named 'branch1' and 'branch2' in the trie + console.log(`Stored value of key 'branch1': ${trie.get(toU8a('branch1'))}`); + console.log(`Stored value of key 'branch2': ${trie.get(toU8a('branch2'))}`); + + // Store the root hash of the trie root node in a variable + const trieRootNodeHash = trie.getRoot(); + + // Store the root node object in a variable + const trieRootNode = trie.getNode(trieRootNodeHash); + + // Show information about the trie node + console.log(`Is root node object empty? : ${isEmptyNode(trieRootNode)}`); + console.log(`Is root node object a KV node? : ${isKvNode(trieRootNode)}`); + + // Deletes the value of a given key named 'branch1' in the trie branch + trie.del(toU8a('branch1')); + + // Retrieve the value of a given key named 'test' in the trie + console.log(`Stored value of key 'branch1': ${trie.get(toU8a('branch1'))}`); + + // Empty, close, and drop the database for each of the trie instances + trie.empty(); + + // Retrieve the value of a given key named 'test' in the trie + console.log(`Stored value of key 'branch2': ${trie.get(toU8a('branch2'))}`); + + // Close the trie + trie.close(); + + // Drop the trie + trie.drop(); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/package.json b/docs/examples/trie-db/05_empty_close_drop_trie/package.json new file mode 100644 index 000000000..b36ca1086 --- /dev/null +++ b/docs/examples/trie-db/05_empty_close_drop_trie/package.json @@ -0,0 +1,19 @@ +{ + "name": "05_empty_close_drop_trie", + "version": "0.1.0", + "description": "Example showing how to empty, close, and drop a Patricia Trie", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/trie-db": "^0.32.1", + "@polkadot/db": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/trie-db/README.md b/docs/examples/trie-db/README.md new file mode 100644 index 000000000..85b939af9 --- /dev/null +++ b/docs/examples/trie-db/README.md @@ -0,0 +1,12 @@ +# Trie-DB Examples + +Here you will find a list of examples that takes you through the basics of creating a Patricia Trie, creating key/value pair branches, retrieving the value of a branch with its key, deleting branches, saving the root node hash to a variable and then later setting the root node hash to restore the trie to its previous state, duplicating the trie with a snapshot, showing the size of the trie and other node information, and emptying, closing, and dropping the trie. + +## Running the examples + +From within each folder run the following to install required dependencies and to execute the example: +```shell +yarn; +yarn start +``` + diff --git a/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/README.md b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/README.md new file mode 100644 index 000000000..3af78ecb1 --- /dev/null +++ b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/README.md @@ -0,0 +1,5 @@ +# Encrypt & Decrypt Message using NaCl + +The following example shows how to encrypt and decrypt a message with NaCl (pronouced "salt"), which is a Networking and Cryptography library used in util-crypto. + +[include](index.js) diff --git a/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js new file mode 100755 index 000000000..13afb75e6 --- /dev/null +++ b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js @@ -0,0 +1,24 @@ +const { naclEncrypt } = require('@polkadot/util-crypto'); +const { naclDecrypt } = require('@polkadot/util-crypto'); + +async function main () { + const secret = new Uint8Array(32); + const messagePreEncryption = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]); + const noncePreEncryption = new Uint8Array(24); + + // Encrypt the message + const { encrypted, nonce } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption); + + // Show contents of the encrypted message + console.log(`Encrypted message: ${JSON.stringify(encrypted, null, 2)}`); + + // Decrypt the message + const messageDecrypted = naclDecrypt(encrypted, nonce, secret); + // Convert each Uint8Array to a string for comparison + const isMatch = messagePreEncryption.toString === messageDecrypted.toString; + + // Verify that the decrypted message matches the original message + console.log(`Does the decrypted message match the original message? ${isMatch}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/package.json b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/package.json new file mode 100644 index 000000000..146a5c14a --- /dev/null +++ b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/package.json @@ -0,0 +1,18 @@ +{ + "name": "01_encrypt_decrypt_message_nacl", + "version": "0.1.0", + "description": "Example showing how to encrypt and decrypt a message using NaCl", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/util-crypto": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/util-crypto/02_sign_verify_message_nacl/README.md b/docs/examples/util-crypto/02_sign_verify_message_nacl/README.md new file mode 100644 index 000000000..2e4e9c768 --- /dev/null +++ b/docs/examples/util-crypto/02_sign_verify_message_nacl/README.md @@ -0,0 +1,5 @@ +# Sign & Verify Message using NaCl + +The following example shows how to sign and verify a message with NaCl (pronouced "salt"), which is a Networking and Cryptography library used in util-crypto. + +[include](index.js) diff --git a/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js b/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js new file mode 100755 index 000000000..fb5763ed2 --- /dev/null +++ b/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js @@ -0,0 +1,32 @@ +const stringToU8a = require('@polkadot/util/string/toU8a').default; +const { randomAsU8a } = require('@polkadot/util-crypto'); + +const { naclKeypairFromSeed } = require('@polkadot/util-crypto'); +const { naclEncrypt } = require('@polkadot/util-crypto'); +const { naclSign } = require('@polkadot/util-crypto'); +const { naclVerify } = require('@polkadot/util-crypto'); + +async function main () { + // Create account seed for Alice as fallback if generated mnemonic not valid + const seedAlice = 'Alice'.padEnd(32, ' '); + + // Generate new public/secret keypair for Alice from the supplied seed + const { secretKey, publicKey } = naclKeypairFromSeed(stringToU8a(seedAlice)); + + // Encrypt message. Create Uint8Array's filled with random bytes of specified length + const secret = randomAsU8a(32); + const messagePreEncryption = stringToU8a('please send me DOTs'); + const noncePreEncryption = randomAsU8a(24); + + const { encrypted, nonce } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption); + + // Sign the message with a valid signature + const messageSignature = naclSign(encrypted, secretKey); + + // Validate that the message was correctly signed + const isValidSignature = naclVerify(encrypted, messageSignature, publicKey); + + console.log(`Was the message correctly signed? ${isValidSignature}`); +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/util-crypto/02_sign_verify_message_nacl/package.json b/docs/examples/util-crypto/02_sign_verify_message_nacl/package.json new file mode 100644 index 000000000..67e7bbc33 --- /dev/null +++ b/docs/examples/util-crypto/02_sign_verify_message_nacl/package.json @@ -0,0 +1,18 @@ +{ + "name": "02_sign_verify_message_nacl", + "version": "0.1.0", + "description": "Example showing how to sign and verify a message using NaCl", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/util-crypto": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/README.md b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/README.md new file mode 100644 index 000000000..9cf5bdbd1 --- /dev/null +++ b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/README.md @@ -0,0 +1,5 @@ +# Create & Generate Mnemonic using BIP39 + +The following example shows how to create and generate mnemonics using BIP39. + +[include](index.js) diff --git a/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js new file mode 100755 index 000000000..57cb9a411 --- /dev/null +++ b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js @@ -0,0 +1,26 @@ +const { mnemonicGenerate } = require('@polkadot/util-crypto'); +const { mnemonicToSeed } = require('@polkadot/util-crypto'); +const { mnemonicValidate } = require('@polkadot/util-crypto'); +const { toSecret } = require('@polkadot/util-crypto'); +const { naclKeypairFromSeed } = require('@polkadot/util-crypto'); + +async function main () { + // Create mnemonic string for Alice using BIP39 + const mnemonicAlice = mnemonicGenerate(); + + // Validate the mnemic string that was generated + const isValidMnemonic = mnemonicValidate(mnemonicAlice); + + console.log(`isValidMnemonic: ${isValidMnemonic}`); + + // Create valid seed from mnemonic as u8a and convert it to a string + // FIXME - Replace with mnemonicToSeed once exposed + const seedAlice = mnemonicToSeed(mnemonicAlice); + + // Generate new public/secret keypair for Alice from the supplied seed + const { secretKey, publicKey } = naclKeypairFromSeed(seedAlice); + + // Encrypt, Sign and Validate the message. See Example 'Sign & Verify Message' +} + +main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/package.json b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/package.json new file mode 100644 index 000000000..67e7bbc33 --- /dev/null +++ b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/package.json @@ -0,0 +1,18 @@ +{ + "name": "02_sign_verify_message_nacl", + "version": "0.1.0", + "description": "Example showing how to sign and verify a message using NaCl", + "main": "index.js", + "author": "ltfschoen", + "license": "MIT", + "scripts": { + "clean": "rimraf node_modules", + "start": "node index.js" + }, + "dependencies": { + "@polkadot/util-crypto": "^0.32.2" + }, + "devDependencies": { + "rimraf": "^2.6.2" + } +} diff --git a/docs/examples/util-crypto/README.md b/docs/examples/util-crypto/README.md new file mode 100644 index 000000000..7aff9985a --- /dev/null +++ b/docs/examples/util-crypto/README.md @@ -0,0 +1,13 @@ +# Util-Crypto Examples + +Here you will find a list of examples that takes you through the basics of encrypting and decrypting messages using NaCl, signing a message with a seed and verifying it using NaCl, and generating and validating mnemonics for account seeds. + +## Running the examples + +From within each folder run the following to install required dependencies and to execute the example: +```shell +yarn; +yarn start +``` + + diff --git a/docs/logo.png b/docs/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..d96e7fccd2639a99a3c2c866f8fcb4d28f3c71c0 GIT binary patch literal 7497 zcmb_=2{e>{`}Zw`Y$=2+(`3&uV;y7PVzQTHsVuXZFrzUT5<(Or`;w)SB}=wKmh5Ct zlI%O#vuBC_@!Ou??>W!^eV_B5_j}HL?(2N7&-dD|>s}t480j*f;yDEX05eig`zinc zdjJ3^(4PPRAm?W-002y~cr7gxZM>_Clbt63=sk|T;bC@d=iE_MWT1KigXl;4dyh|? zqIp_POFJ+Q7Nk0Hq4DYS$;>$OLc-ng>~zVzQWo_E^)Hj+E7x0C-(`!w%XWLYzJHO* zdS9t#YYUHY+~`J^(&~vIq~=4-%RE#~q*!T1;pDW$*iPIC^?B;rhpKQ* z)7M}LF)=D&FV(l~#tjXiR*3b5=7s&aU0*p=(JM2W(@22Sl=0Hu?;G8x58#JaX`vOs zH)C@#GoY6qFiuR2Wrp$rKi1_w0D#nuDG^{?>{|3i0L${cf$dc6uHOSDpvEAk-~`hw z^^cg)3{vel$j{dFfe8~=6&fTz;@VDMAziJQNwYBZI920^mr*~_0IwfhteY=|zLo|gso&)H)z{>CxMA<) z*rO{Ki>VT*1a&3C!su)np1P9;zSB4>!;N|P=xXUf*D`X-%?u^Q%;N+dcU#4xK4-_M z+GNwbO%Qi8wMvL{z4buwO+?A-Dv+F3dbF~Qu%Q5REdV0Ma%MC-!Xnxk!IyXJViu-l z0T$q)GKO4yQcICNetS!YmR)b^vg0qB>l%0RgyWMyXD(*|T=XUnqds>8s;1Z@(J`4) zIhtVO-i53@f7yFi0`TN9MKbCZ@@9KlW+egpL z-F#cpu&-zA?-e7r0e8`%8CTkqgp;bjB+h(1l4pGKX7~`Vvzg{Ss@rHYD{`4(Qcd@& z&9!^4%@;)7LJ)d#e#U$+cwU!$xsWp&S`K)3X3ae0rUwEC=8cPx zoqoO?>eId<49gFwS%H;YW7z&2fMav{UZs~W(c9<%*s7lk8n5I1S{TfzJkD%G17q-Q8GSn)9;h^7NdL$d9HIw`dMp7B{wOjXn3Q1TtzmXn|50D#NqeQWi+BCt zSCYY!rxhMmYKyETQ*^Hi22V$tzdEZJ!~WC`t(d2Yqe-X+_S$H}6*&s=O z1J8RFC;wvw(##){;~*@`l<&G-5Ff%)CVCq2;%onNhA?*xn@ zt1G>Tio(1KMl?8H-A>Eefj0c?@Oagy{(g_otbN^IZ_G=58hhhwa1?%cp88GQ=>Rx& zQJqA9Re)DO=t*PdfuQgpyP&g7?aYo$J3Of}OVak|6}fe|7@lBx`gr)D71+(s364vc zWQUth%43w^HL)pOVTrRM(V}OIT5m=h3bz=nxQe||QSiSs=~Fk-p;EUz4)g4)g5SPS zkhG&x@TA}Qjy+;nc7z;)&!4~0>n_vQ(JIkpfGz#x6ftnU#DhBTWFYfXrUV7se!o!a z+pN5@Q1WxMZC~vObpew%u1g_8T1wi+Y1Gzd$iLL3gbM{5uuo}X2z{ebrSTv@J0R!e zGWTY#5Plw;=%m<5ik`7-k2n8n4l_TMd)>SxuOhEAPb;4>Ki*QHbmi^DAkC1TbKC%L zk!Od(Oz;}!AogJDfMBgZWMTbo`Q(uN5WfE&Lp89T01nzm#<{OSg+UWh%KnWigrf{(EI$xdCb5J82+x zUfcyjy0z#v`h>i3_mWGlo6?+7#eRkUNPmS5R|nUUnuRK5YTS{ZHv$?V9f63b)anQl zWO~i@89F_068vI7>l~{y-(F8|%eC3}0~?v~kNfosP8A3j%#9L8!K+rQ?G2m3I;_v+ z^6q{snOJEMYUpRKS!vkfp4o^s4(+D1QM1Wdl^iotqpRVqk@M-NQPzmE{V@JYtwC+r zH||K|sEq0ZRgRwul`oAK4JYjiy|-+=XCS(9mTf0s$v;rzy#HXpZk=M?*vYcsZ$b20 z@0vWJO9QrMer87CwQ@9C=ofDe(?MtV>gBN0<9eFt5_Vo6eXP1r78agHtlxmWb;-zfz372yQi<|LTDKT zcKhmw>BG;a`it>v@z){yuDgvhS$Bf^^K4#JYF59zkEw5KzRr@%neSCoVY?MO_+xOy zQKG-Ydc!N9vfSkMV$nUn%*v+vaHQ-rv4Hq!z@(-JkLnbj%`7%#mCqs)ei{83*@kdh z=ahMW6CWG=0P!4JTlN_$TP++eDh$uN*6+5$Tefkq6FH`^vi|LzUD?3Og20b}z2FwL z*#nB3@j+@_wSRTxw&IF)Nm^x1PHJ|V)!2y1r%$5^eUypXkJJ#u2ZsB;JnOw*14`)} zSrhrKC>A?Eh8wDN+aju*%w;|JI@P>tF!t@8sKgdY0Rh*lW$lB<(Q3L!-g$C)TOV7W zN7EV8CL>&|Tq-8QRulJ1RB<~;lN;@a@?)iYu0C@--TP_83g~40MCgTc5w}CCHaBL< z+i`EgK9DBv4E8PdH{Wusk^FG@J!q-9#HQV6`Mu&k=ahM$bNY~+hs3JWLHuHkd)a=e zK*f2_ou%rSdkU+eD{8y>n`JwEt^(iHvOOI(T=p-n>e4BtD|M^!@0U+KoiXDXK9&#S^lc@ zsLE2}LF$&z3|&8~p}>^d=mKPA`8s{9CIHa-b+l8b5@|O}fE7=5k36gbHE=rV{+Uk) z0S7pnk{T+&`$7H-^+6}l3vP>kCV1CLc&GXqzb__F8-liMtS)t)pUt0`6s2l@HadFF z9LQz(`Fv@4*>Y%T-%dt-1V|FWyKAbK1o$}816hN!-OaddVzkv==G_;5PXGX5aM81L z1prQ=@#|l9fh9)2_A_)VMlaz;`V6sq%=zwu-grH`ZKg3uyi z?8q2xJ2FNEEDeRhAuuQeCSwLwM8Mz(S-DG4X#^DdJJgVf#$!GI6I50KA*=8YD28l@ zwj^S?I@nux-q|5X483{+ZP1}X=K$itvA5P2C{1qd95 zk%yoZ;V6s@+TLCk{d;r`4H3p9JPuE=bNai~W2?}3G(yf^4lV-fj(bN1>}uzZ zL4*I;#Q%qA{8xJaIPc+rA^dw~$U+g)us_rNyKYw^mh53i!f4Y*q;he4t4|_2CV{?0!#frd-UJs_jgnOqep));Q!AaNgWTf-_s@a z@0t9K_qV~P3i^HPs`lk$@~<(j3i{WB07F2lfJtCA)w=`mApkgaAE~WjMoC^y@ijP$ z=V?i^>lV29$f$?kF-S#M3nJv0J6Dm}#XZRn)4tg0Dd#BopmmnMY&{qTyNm*HO-8t^ z9RzUMfBm8ceXsYG?@--7srsT7&t%anw;N$XR{k7Mf;5$%=XxM^S{gnm8CjbpznH8_ z``OaI-?iV>JMS^-IXdU5B(3DJLK8B-+ci?qt-evR#oaJ{CU2w0mWr+|0~O z3BGp!B(#)_jqg%0D?Gd@|Bz#p2`8kOBJS9~` zu2{mu&CRd`5hIAK7Qer|Hs8e&+T?Zb9>$WNk1wTpT?W?$s0*G^r2H6nG>#N2KI91; zo=IwpAEVgZ9ox7Wmd-mR4*=c5u>z7Z55W>PuNw(s=Ts`JG0#^&P}U|hGle_7dS*!P zZ@$U5F5_48xw(-+;w|$%I-JhH;eT6gl6&9~duL}zdvTIiM9b6~Wnp2Ve&WY7a@`b6 zJtn-kxVWwDilJ`moM-9|MHvEttoq!mnS(y8Oi)Yl&bU+e(k6q*p9VrF59>V|g~7w6^WWoBN!HMO(f z$NDxYDJeObcfCWSy_LFgb;sDiAS@!HdkN9O(q?=E$t~j4N!77k@%rNa;KbY!07&d6 zh#l6OaFXhBx2BzruxZry%5HHoUyN!g&?_tymvwZf$KXe071}ynR~|`MI`M9dz16VL~Qk&NF=K zV`uZ-o6gRVxQme=2TE{{cRmjf-?X;QjVs^@pAx@xsfahUsVhY(nDxo*ELP)mPEO8` zU2{`YjmbrLZ*(D6SGQ$fz{6LFz2w!yo{uSGrx-b@{LVPtpZTbSy!PP@SGn1fmZ_Eq zfqt{g={*~B-6+qYQfG^CczBGQ6`fycY3W%JBin&xcSe6GH7eO?ZoW6`ZfYFHGTqI; zd#=}k57^t!x~*t-^QM8g3P0tMBbtd)F(rMMd=aicyb=7g;x_bgGa28hqy{#uuRuD#Ug3r_Nc%xgk;}TqwPn zhK+Tf9QYW58|rLN$2$rM2@#db*yb)o>d7i7h%hFB=TYy<~A+3{8T5D)9yu9 zmI$WBL6#??1;WYLUhEI5I`V1nFhPW~)jZ5INzAut=oM)*zQKG&|NhUrJENnc6lE4b zqTOhUpWa{ntzm4P?hO_FNo_;l3;xG=E^t^M!WB4upT3fh3Xgo?bQqMd4+CKZm3o~8~?bjYk z8FPr=FcPmbpDdTjRl}+Ny0UYYM|1~bUFyOce{*%qYi%*CWvbj{aef{tcn0vBNSc;3 z%8H)0+}qn5{Tk&Udxf1?GH_Kq^`~BISL^t=?fP2d>R=H{w=H^Qq*4K+!tJ}WG9p%B zeEm8H=gRQ=Xi^|6km+*c>x&0@TGZOTZ4q;^i_C305ubPTi%Iy9)=55?$qHv^Mp04E zJUQo*j%i+Y0_n>~Fp*4-X`EHzXJzyV@qe@ zk~7%Y@NgE1AIf8&p1a9rF=)3HhwaGU7BFQ;MuX^?nVAK9+;`V!VlGb4&SvJNg+kNr zzs|RMiW;9M`_|key;0?lu&H!sHsco63Wr~i4x7OjLD$Pe94}-Pib|@)1 z`%KS^{uxj^x541=XX|Jb9M+s8qyTJGD}n4l@r+- z(!_4fS$tW6Q#@vIzHhOeJSw_0r*(>+KL-G`WvNxZM0>G>W7*KMyHa9Y)H@cyr=})5 zTU1R=ZKg0%PdnwRvx7t7(DL;7!GU+>$l<~6#>xu8sja>Jnu2Bi*X`}?qN1W_3dG~a z!wd`$-+a4J7eM#x*Dn+bC3U;XqSAf2%5!7MeLq#@o;-0hOr~0*-9l7Uv~Xyd@tkC1 zf|n?JeMFFmRkfEK3!FHryc8Q7tJ4Aa?eDC5cz96Pe)?o0!D(INqr#tPps%mL&dTEI z>I!@GScH$88+mRpjmm~oxyLaZ%{9c*TyYAB`5>>Sd;$>eu4DgoH^);${#v2?LK^0d zyxE)NK#l4$Q*YU^Z|Z`QTVJBRpj=BUD@Nyb-xL&hAW|0l3;H{fDxBD~UiN%{Kusrm zp7UvGX=yO4KwMnh84t}kjAdNkfDp54T0w4Z?yFbY&d>pH9Kn(ac%TkCO|KXA>ag#6 z1;kzthr{{!s4B7{eLC?_>GVzQ`TSY8NJU6fgd70Mt zOjT_YjBDzZ*(`&^iv(ouu=$0PY%0jFXX%&)_eT5rbY=($pPhkAHGLHM*9VKl#1ibO zy-DVf3DL3-H#Fm=52LuD;M2&&P%fTF-Zsx4=!Lv~PRdH47xxJ9G|3(o%baNPef`_* wD0^6J_5nhMT}ETZ2*!5&qVf-dnQ6m!*Y4iJU12uM span { + color: rgb(147, 157, 163); +} + +.book-summary ul.summary li.chapter.active { + background: #fff; + border-radius: 1.6rem 0 0 1.6rem; +} + +.book-summary ul.summary li.chapter.active ul li.chapter > a { + color: rgba(0,0,0,.87); +} + +.book-summary ul.summary li.chapter.active > a { + color: #fd8824; +} + +.book-summary ul.summary li.chapter a, +.book-summary ul.summary li.chapter span { + font-weight: 600; + font-size: 1.1em; +} + +.book-summary ul.summary li.chapter > a, +.book-summary ul.summary li > a.gitbook-link +{ + color: #eee; +} + +.book-summary ul.summary li.chapter > a:hover, +.book-summary ul.summary li > a.gitbook-link:hover, +.book-summary ul.summary li.chapter.active ul li.chapter > a:hover { + color: #fd8824; + text-decoration: none; +} diff --git a/jest.config.js b/jest.config.js index 979d4440e..be488936d 100644 --- a/jest.config.js +++ b/jest.config.js @@ -7,5 +7,14 @@ module.exports = Object.assign({}, config, { '@polkadot/trie-(db-old|db|hash)(.*)$': '/packages/trie-$1/src/$2', '@polkadot/util-(crypto|rlp)(.*)$': '/packages/util-$1/src/$2', '@polkadot/util(.*)$': '/packages/util/src/$1' - } + }, + modulePathIgnorePatterns: [ + '/packages/db/build', + '/packages/keyring/build', + '/packages/trie-db/build', + '/packages/trie-hash/build', + '/packages/util/build', + '/packages/util-crypto/build', + '/packages/util-rlp/build' + ] }); diff --git a/package.json b/package.json index 2eb0eaf51..f205aa592 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "typescript": "^3.0.1" }, "scripts": { - "build": "polkadot-dev-build-ts", + "build": "polkadot-dev-build-ts && polkadot-dev-build-docs", "check": "tslint --project . && tsc --noEmit", "clean": "polkadot-dev-clean-build", "postinstall": "polkadot-dev-yarn-only", @@ -22,5 +22,12 @@ "devDependencies": { "@polkadot/dev": "^0.20.25", "@polkadot/ts": "^0.1.30" + }, + "dependencies": { + "babel-plugin-module-resolver": "^3.1.1", + "gitbook-plugin-include-codeblock": "^3.2.2", + "gitbook-plugin-insert-logo-link": "^1.0.1", + "gitbook-plugin-mermaid-gb3": "^2.1.0", + "gitbook-plugin-sunlight-highlighter": "^0.4.3" } } diff --git a/packages/db/README.md b/packages/db/README.md index 865ade2af..027253271 100644 --- a/packages/db/README.md +++ b/packages/db/README.md @@ -1,3 +1,33 @@ # @polkadot/db -This is an implementation of a basic sync in-memory and on-disk database with overlays +This is an implementation of a basic sync in-memory and on-disk database with overlays. Memory is currently used by polkadot-js/client + +## Usage + +Installation - + +``` +yarn add @polkadot/db +``` + +Classes can be imported as follows: + +```js +// Default exports +import DiskDb from '@polkadot/db/Disk'; +import MemoryDb from '@polkadot/db/Memory'; +import TransactionDb from '@polkadot/db/engines/TransactionDb'; +``` + +## Documentation and Available Utilities + +No classes or methods are exposed on the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/db/). + +However, the key classes that are available include: + +- db + - Classes + - Engines + - DiskDb + - MemoryDb + - TransactionDb \ No newline at end of file diff --git a/packages/db/src/Disk.ts b/packages/db/src/Disk.ts index 8040cca57..8eb2d62f9 100644 --- a/packages/db/src/Disk.ts +++ b/packages/db/src/Disk.ts @@ -8,6 +8,61 @@ import FileFlatDb from './FileFlatDb'; import LruDb from './engines/LruDb'; import TransactionDb from './engines/TransactionDb'; +/** + * @name DiskDb + * @summary Creates DiskDb database using LruDb for caching with FileFlatDb and extending TransactionDb. + * @description Create an instance of a Disk database using + * LruDb (for caching with FileFlatDb) and extending TransactionDb. + * Note that LruDB uses the [Least Recently Used (LRU) cache algorithm](https://www.npmjs.com/package/lru_map) + * @example + *
+ * + * ```javascript + * import stringToU8a from '@polkadot/util/string/toU8a'; + * import DiskDb from '@polkadot/db/Disk'; + * import TransactionDb from '@polkadot/db/engines/TransactionDb'; + * + * // Creat diskDb instance that wraps LruDb with backing and Lru cache + * const diskDb = new DiskDb(); + * + * // Creat txDb instance that uses diskDb + * const txDb = new TransactionDb(diskDb); + * + * // Open the disk db backing database. Clears the Lru cache + * diskDb.open(); + * + * // Declare key/value pair to allocate to store under a the key + * const key = stringToU8a('key'); + * const value = stringToU8a('some value'); + * + * // Store key/value pair in disk db backing and also in Lru cache + * diskDb.put(key, value); + * + * // Retrieve value for key from disk db. Returns cached value if key + * // in cache, otherwise returns backing value for key and stores + * // this latest retrieved key/value pair in Lru cache + * valueRetrieved = diskDb.get(key); + * + * // Delete key/value pair from disk db backing and set the key to null in Lru cache + * diskDb.del(key); + * + * // Transaction to Store key/value pair in transaction db + * const isTxSuccess = txDb.transaction(() => { + * txDb.put(key, value); + * + * // Boolean to indicate whether transaction was successful or not + * return true; + * }); + * + * console.log(`Transaction successful?: ${isTxSuccess}`); + * + * // Retrieve transaction value from diskDb db + * console.log(`Transfered value: ${diskDb.get(key)}`); + * + * // Close the diskDb database and clear Lru cache + * diskDb.close(); + * ``` + */ export default class DiskDb extends TransactionDb { constructor (base: string, name: string, options?: BaseDbOptions) { super( diff --git a/packages/db/src/Memory.ts b/packages/db/src/Memory.ts index 37d6763ce..1090b15d1 100644 --- a/packages/db/src/Memory.ts +++ b/packages/db/src/Memory.ts @@ -7,6 +7,62 @@ import { BaseDbOptions } from './types'; import MemoryDb from './engines/MemoryDb'; import TransactionDb from './engines/TransactionDb'; +/** + * @name MemoryDb + * @summary Creates a MemoryDb database extending TransactionDb + * @description Create an instance of a Memory database using + * MemoryDb and extending TransactionDb. + * `options` argument (optional) used to specifies whether + * to use compression. + * - Enable compression when storing "blocks" since they compress well. + * - Disable compression when storing "state" Transactions Trie + * using @polkadot/trie-db or @polkadot/db/src/engines/TransactionDb.ts + * (potentially LevelDb or RocksDb implementation of a Merkle Patricia Trie) + * data structure serialised with Recursive Length Prefix (RLP) encoding + * @example + *
+ * + * ```javascript + * import stringToU8a from '@polkadot/util/string/toU8a'; + * import MemoryDb from '@polkadot/db/Memory'; + * import TransactionDb from '@polkadot/db/engines/TransactionDb'; + * + * const memoryDb = new MemoryDb(); + * const txDb = new TransactionDb(memoryDb); + * + * // Open the memory database + * memoryDb.open(); + * + * // Declare key/value pair to allocate to store under a the key + * const key = stringToU8a('key'); + * const value = stringToU8a('some value'); + * + * // Store key/value pair in memory db + * memoryDb.put(key, value); + * + * // Retrieve value for key from memory db + * valueRetrieved = memoryDb.get(key); + * + * // Delete key/value pair from memory db + * memoryDb.del(key); + * + * // Transaction to Store key/value pair in transaction db + * const isTxSuccess = txDb.transaction(() => { + * txDb.put(key, value); + * + * // Boolean to indicate whether transaction was successful or not + * return true; + * }); + * + * console.log(`Transaction successful?: ${isTxSuccess}`); + * + * // Retrieve transaction value from memory db + * console.log(`Transfered value: ${memoryDb.get(key)}`); + * + * // Close the memory database + * memoryDb.close(); + * ``` + */ export default class Memory extends TransactionDb { constructor (options?: BaseDbOptions) { super(new MemoryDb(options)); diff --git a/packages/db/src/engines/unused/LevelDb.spec.js-unused b/packages/db/src/engines/unused/LevelDb.spec.js-unused index b9a67cea0..adb128a87 100644 --- a/packages/db/src/engines/unused/LevelDb.spec.js-unused +++ b/packages/db/src/engines/unused/LevelDb.spec.js-unused @@ -5,7 +5,7 @@ import mkdirp from 'mkdirp'; import os from 'os'; import path from 'path'; -import toU8a from '@polkadot/util/u8a/fromString'; +import stringToU8a from '@polkadot/util/string/toU8a'; import LevelDb from './LevelDb'; @@ -26,8 +26,8 @@ describe.skip('LevelDb', () => { }); it('sets & retrieves', () => { - const key = toU8a('key0'); - const value = toU8a('value0'); + const key = stringToU8a('key0'); + const value = stringToU8a('value0'); db.put(key, value); @@ -35,15 +35,15 @@ describe.skip('LevelDb', () => { }); it('retrieves null for non-existing', () => { - const key = toU8a('key1'); + const key = stringToU8a('key1'); expect(db.get(key)).toEqual(null); }); it('overrides values', () => { - const key = toU8a('key2'); - const value = toU8a('value1'); - const replace = toU8a('value2'); + const key = stringToU8a('key2'); + const value = stringToU8a('value1'); + const replace = stringToU8a('value2'); db.put(key, value); @@ -55,7 +55,7 @@ describe.skip('LevelDb', () => { }); it('deletes values', () => { - const key = toU8a('key2'); + const key = stringToU8a('key2'); db.del(key); diff --git a/packages/db/src/engines/unused/RocksDb.spec.js-unused b/packages/db/src/engines/unused/RocksDb.spec.js-unused index dcf902040..b4eb5f81e 100644 --- a/packages/db/src/engines/unused/RocksDb.spec.js-unused +++ b/packages/db/src/engines/unused/RocksDb.spec.js-unused @@ -5,7 +5,7 @@ import mkdirp from 'mkdirp'; import os from 'os'; import path from 'path'; -import toU8a from '@polkadot/util/u8a/fromString'; +import stringToU8a from '@polkadot/util/string/toU8a'; import RocksDb from './RocksDb'; @@ -26,8 +26,8 @@ describe.skip('RocksDb', () => { }); it('sets & retrieves', () => { - const key = toU8a('key0'); - const value = toU8a('value0'); + const key = stringToU8a('key0'); + const value = stringToU8a('value0'); db.put(key, value); @@ -35,15 +35,15 @@ describe.skip('RocksDb', () => { }); it('retrieves null for non-existing', () => { - const key = toU8a('key1'); + const key = stringToU8a('key1'); expect(db.get(key)).toEqual(null); }); it('overrides values', () => { - const key = toU8a('key2'); - const value = toU8a('value1'); - const replace = toU8a('value2'); + const key = stringToU8a('key2'); + const value = stringToU8a('value1'); + const replace = stringToU8a('value2'); db.put(key, value); @@ -55,7 +55,7 @@ describe.skip('RocksDb', () => { }); it('deletes values', () => { - const key = toU8a('key2'); + const key = stringToU8a('key2'); db.del(key); diff --git a/packages/keyring/README.md b/packages/keyring/README.md index 7b466e8c6..0c1feabc2 100644 --- a/packages/keyring/README.md +++ b/packages/keyring/README.md @@ -1,13 +1,30 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square) -[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/keyring.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/keyring) -[![travis](https://img.shields.io/travis/polkadot-js/client.svg?style=flat-square)](https://travis-ci.org/polkadot-js/client) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/client.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/client/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/client.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/client?branch=master) -[![dependency](https://david-dm.org/polkadot-js/client.svg?style=flat-square&path=packages/keyring)](https://david-dm.org/polkadot-js/client?path=packages/keyring) -[![devDependency](https://david-dm.org/polkadot-js/client/dev-status.svg?style=flat-square&path=packages/keyring)](https://david-dm.org/polkadot-js/client?path=packages/keyring#info=devDependencies) - # @polkadot/keyring -Key management +Key management of user accounts including generation and retrieval of keyring pairs from a variety of input combinations. + +## Usage + +Installation - + +``` +yarn add @polkadot/keyring +``` + +Classes and Functions can be imported as follows: + +```js +import Keyring from '@polkadot/keyring'; // Default export +import { pair } from '@polkadot/keyring/pair'; +import { testKeyring } from '@polkadot/keyring/testing'; +``` + +## Documentation and Available Utilities + +Below is a list of currently exposed methods published at the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/keyring/). + +- [keyring](https://polkadot.js.org/common/keyring/README.md) + - Classes + - [Keyring](https://polkadot.js.org/common/keyring/classes/_index_.keyring.md) + - Functions + - [pair](https://polkadot.js.org/common/keyring/modules/_pair_index_.md) + - [testKeyring](https://polkadot.js.org/common/keyring/modules/_testing_.md) diff --git a/packages/keyring/docs/README.md b/packages/keyring/docs/README.md deleted file mode 100644 index 1e71b5a16..000000000 --- a/packages/keyring/docs/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Available interfaces - - - -- [address](address.md) -- [pair](pair.md) - -# Available methods \ No newline at end of file diff --git a/packages/keyring/docs/address.md b/packages/keyring/docs/address.md deleted file mode 100644 index c43f83fc5..000000000 --- a/packages/keyring/docs/address.md +++ /dev/null @@ -1,3 +0,0 @@ -# address - - diff --git a/packages/keyring/docs/pair.md b/packages/keyring/docs/pair.md deleted file mode 100644 index 6f4489c48..000000000 --- a/packages/keyring/docs/pair.md +++ /dev/null @@ -1,3 +0,0 @@ -# pair - - diff --git a/packages/keyring/package.json b/packages/keyring/package.json index 7228b9683..5ec15e6c8 100644 --- a/packages/keyring/package.json +++ b/packages/keyring/package.json @@ -12,7 +12,7 @@ }, "repository": { "type": "git", - "url": "git+https://github.com/polkadot-js/client.git" + "url": "git+https://github.com/polkadot-js/common.git" }, "keywords": [ "Polkadot", @@ -26,9 +26,9 @@ "contributors": [], "license": "ISC", "bugs": { - "url": "https://github.com/polkadot-js/client/issues" + "url": "https://github.com/polkadot-js/common/issues" }, - "homepage": "https://github.com/polkadot-js/client/tree/master/packages/keyring#readme", + "homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme", "dependencies": { "@babel/runtime": "^7.0.0", "@polkadot/util": "^0.32.3", diff --git a/packages/keyring/src/address/defaults.ts b/packages/keyring/src/address/defaults.ts index 83ad71c6b..b045ba7c0 100644 --- a/packages/keyring/src/address/defaults.ts +++ b/packages/keyring/src/address/defaults.ts @@ -1,4 +1,4 @@ -// Copyright 2017-2018 @polkadot/util-keyring authors & contributors +// Copyright 2017-2018 @polkadot/keyring authors & contributors // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. diff --git a/packages/keyring/src/address/setPrefix.spec.js b/packages/keyring/src/address/setPrefix.spec.js index 34e609998..cd0da2583 100644 --- a/packages/keyring/src/address/setPrefix.spec.js +++ b/packages/keyring/src/address/setPrefix.spec.js @@ -1,4 +1,4 @@ -// Copyright 2017-2018 @polkadot/util-keyring authors & contributors +// Copyright 2017-2018 @polkadot/keyring authors & contributors // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. diff --git a/packages/keyring/src/address/setPrefix.ts b/packages/keyring/src/address/setPrefix.ts index caa6e78b5..8763725bb 100644 --- a/packages/keyring/src/address/setPrefix.ts +++ b/packages/keyring/src/address/setPrefix.ts @@ -1,4 +1,4 @@ -// Copyright 2017-2018 @polkadot/util-keyring authors & contributors +// Copyright 2017-2018 @polkadot/keyring authors & contributors // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. diff --git a/packages/keyring/src/address/types.d.ts b/packages/keyring/src/address/types.d.ts index 2cabaa40d..7b96aa8a7 100644 --- a/packages/keyring/src/address/types.d.ts +++ b/packages/keyring/src/address/types.d.ts @@ -1,4 +1,4 @@ -// Copyright 2017-2018 @polkadot/util-keyring authors & contributors +// Copyright 2017-2018 @polkadot/keyring authors & contributors // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. diff --git a/packages/keyring/src/index.ts b/packages/keyring/src/index.ts index 7c90584cb..7c5f9759a 100644 --- a/packages/keyring/src/index.ts +++ b/packages/keyring/src/index.ts @@ -11,6 +11,24 @@ import { decodeAddress, encodeAddress, setAddressPrefix } from './address'; import createPair from './pair'; import Pairs from './pairs'; +/** + * # @polkadot/common/keyring + * + * ## Overview + * + * @name Keyring + * @summary Keyring management of user accounts + * @description Allows generation of keyring pairs from a variety of input combinations, such as + * json object containing account address or public key, account metadata, and account encoded using + * `addFromJson`, or by providing those values as arguments separately to `addFromAddress`, + * or by providing the mnemonic (seed phrase) and account metadata as arguments to `addFromMnemonic`. + * Stores the keyring pairs in a keyring pair dictionary. Removal of the keyring pairs from the keyring pair + * dictionary is achieved using `removePair`. Retrieval of all the stored pairs via `getPairs` or perform + * lookup of a pair for a given account address or public key using `getPair`. JSON metadata associated with + * an account may be obtained using `toJson` accompanied by the account passphrase. + * @example See [Polkadot-JS Common Keyring Examples](https://polkadot.js.org/api/common/examples/keyring/) and the [Polkadot-JS Apps ui-keyring package](https://github.com/polkadot-js/apps/tree/master/packages/ui-keyring) + * where it is implemented. + */ export default class Keyring implements KeyringInstance { private _pairs: Pairs; @@ -18,35 +36,159 @@ export default class Keyring implements KeyringInstance { this._pairs = new Pairs(); } + /** + * @name addPair + * @signature addPair (pair: KeyringPair): KeyringPair + * @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary + */ addPair (pair: KeyringPair): KeyringPair { return this._pairs.add(pair); } + /** + * @name addFromAddress + * @signature addFromAddress (address: string | Uint8Array, meta?: KeyringPair$Meta, defaultEncoded?: Uint8Array): KeyringPair + * @summary Stores an account, given an account address, as a Key/Value (public key, pair) in Keyring Pair Dictionary + * @description Allows user to explicitely provide separate inputs including account address or public key, and optionally + * the associated account metadata, and the default encoded value as arguments (that may be obtained from the json file + * of an account backup), and then generates a keyring pair from them that it passes to + * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. + */ addFromAddress (address: string | Uint8Array, meta?: KeyringPair$Meta, defaultEncoded?: Uint8Array): KeyringPair { // @ts-ignore no secretKey - cannot unlock return this.addPair(createPair({ publicKey: decodeAddress(address) }, meta, defaultEncoded)); } + /** + * @name addFromJson + * @signature addFromJson ({ address, encoded, meta }: KeyringPair$Json): KeyringPair + * @summary Stores an account, given JSON data, as a Key/Value (public key, pair) in Keyring Pair Dictionary + * @description Allows user to provide a json object argument that contains account information (that may be obtained from the json file + * of an account backup), and then generates a keyring pair from it that it passes to + * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. + * @example + * Refer to an actual implementation in [Polkadot-JS ui-keyring > account > save](https://github.com/polkadot-js/apps/blob/master/packages/ui-keyring/src/account/save.ts#L15) + */ addFromJson ({ address, encoded, meta }: KeyringPair$Json): KeyringPair { return this.addFromAddress(address, meta, hexToU8a(encoded)); } + /** + * @name addFromMnemonic + * @signature addFromMnemonic (mnemonic: string, meta?: KeyringPair$Meta): KeyringPair + * @summary Stores an account, given a mnemonic, as a Key/Value (public key, pair) in Keyring Pair Dictionary + * @description Allows user to provide a mnemonic (seed phrase that is provided when account is originally created) + * argument and a metadata argument that contains account information (that may be obtained from the json file + * of an account backup), and then generates a keyring pair from it that it passes to + * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. + */ addFromMnemonic (mnemonic: string, meta?: KeyringPair$Meta): KeyringPair { return this.addFromSeed(mnemonicToSeed(mnemonic), meta); } + /** + * @name addFromSeed + * @signature addFromSeed (seed: Uint8Array, meta?: KeyringPair$Meta): KeyringPair + * @summary Stores an account, given seed data, as a Key/Value (public key, pair) in Keyring Pair Dictionary + * @description Stores in a keyring pair dictionary the public key of the pair as a key and the pair as the associated value. + * Allows user to provide the account seed as an argument, and then generates a keyring pair from it that it passes to + * `addPair` to store in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. + * @example + *
+ * + * ```javascript + * import Keyring from '@polkadot/keyring'; + * import stringToU8a from '@polkadot/util/string/toU8a'; + * + * const ALICE_SEED = 'Alice'.padEnd(32, ' '); + * + * // Create an instance of the Keyring + * const keyring = new Keyring(); + * + * // Add Alice to our keyring pair dictionary (with the known seed for the account) + * const pairAlice = keyring.addFromSeed(stringToU8a(ALICE_SEED)); + * ``` + * + * Refer to an actual implementation in [Polkadot-JS ui-keyring > account > create](https://github.com/polkadot-js/apps/blob/master/packages/ui-keyring/src/account/create.ts#L11) + */ addFromSeed (seed: Uint8Array, meta?: KeyringPair$Meta): KeyringPair { return this.addPair(createPair(naclKeypairFromSeed(seed), meta)); } + /** + * @name getPair + * @signature getPair (address: string | Uint8Array): KeyringPair + * @summary Retrieves an account keyring pair from the Keyring Pair Dictionary, given an account address + * @description Returns a keyring pair value from the keyring pair dictionary by performing + * a key lookup using the provided account address or public key (after decoding it). + * @example + *
+ * + * ```javascript + * import Keyring from '@polkadot/keyring'; + * import stringToU8a from '@polkadot/util/string/toU8a'; + * + * const ALICE_SEED = 'Alice'.padEnd(32, ' '); + * + * // Create an instance of the Keyring + * const keyring = new Keyring(); + * + * // Add Alice to our keyring pair dictionary (with the known seed for the account) + * const pairAlice = keyring.addFromSeed(stringToU8a(ALICE_SEED)); + * + * // Retrieve the same pair that is stored in the keyring pair dictionary by + * // providing the account address as an argument, and also the public key as an argument. + * // The pairs that are returned should both be the same value as `pairAlice` above + * const pairAliceRetrievedWithAddress = keyring.getPair(pairAlice.address()); + * const pairAliceRetrievedWithPublicKey = keyring.getPair(pairAlice.publicKey()); + * + * // Check if all returned pairs are the same + * console.log(`Are all pairs the same? : ` + + * `${pairAlice === pairAliceRetrievedWithAddress === pairAliceRetrievedWithPublicKey}`); + * ``` + */ getPair (address: string | Uint8Array): KeyringPair { return this._pairs.get(address); } + /** + * @name getPairs + * @signature getPairs (): Array + * @summary Retrieves all account keyring pairs from the Keyring Pair Dictionary + * @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary. + * @example + *
+ * + * ```javascript + * import testKeyring from '@polkadot/keyring/testing'; + * + * // Create an instance of Keyring that includes test accounts + * const keyring = testingPairs(); + * + * keyring + * .getPairs() + * .forEach((pair) => { + * const address = pair.address(); + * + * keyring.addPair(address, { + * address, + * meta: pair.getMeta() + * }); + * }); + * ``` + * + * Refer to an actual implementation in [Polkadot-JS ui-keyring > loadAll](https://github.com/polkadot-js/apps/blob/master/packages/ui-keyring/src/loadAll.ts) + */ getPairs (): Array { return this._pairs.all(); } + /** + * @name getPublicKeys + * @signature getPublicKeys (): Array + * @summary Retrieves Public Keys of all Keyring Pairs stored in the Keyring Pair Dictionary + * @description Returns an array list of all the public keys associated with each of the keyring pair values that are stored in the keyring pair dictionary. + */ getPublicKeys (): Array { return this._pairs .all() @@ -55,10 +197,28 @@ export default class Keyring implements KeyringInstance { ); } + /** + * @name removePair + * @signature removePair (address: string | Uint8Array): void + * @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary. + * @example + * Refer to an actual implementation in [Polkadot-JS ui-keyring > account > forget](https://github.com/polkadot-js/apps/blob/master/packages/ui-keyring/src/account/forget.ts) + */ removePair (address: string | Uint8Array): void { this._pairs.remove(address); } + /** + * @name toJson + * @signature toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json + * @summary Returns a JSON object associated with the input argument that contains metadata assocated with an account + * @description Returns a JSON object containing the metadata associated with an account + * when valid address or public key and when the account passphrase is provided if the account secret + * is not already unlocked and available in memory. Note that in [Polkadot-JS Apps](https://github.com/polkadot-js/apps) the user + * may backup their account to a JSON file that contains this information. + * @example + * Refer to an actual implementation in [Polkadot-JS ui-keyring > account > save](https://github.com/polkadot-js/apps/blob/master/packages/ui-keyring/src/account/save.ts#L9) + */ toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json { return this._pairs.get(address).toJson(passphrase); } diff --git a/packages/keyring/src/pair/index.ts b/packages/keyring/src/pair/index.ts index e8b488524..d647e9d3d 100644 --- a/packages/keyring/src/pair/index.ts +++ b/packages/keyring/src/pair/index.ts @@ -15,6 +15,38 @@ import getMeta from './getMeta'; import setMeta from './setMeta'; import toJson from './toJson'; +/** + * @name pair + * @signature pair ({ publicKey, secretKey }: KeypairType, meta: KeyringPair$Meta = {}, defaultEncoded?: Uint8Array): KeyringPair + * @summary Creates a keyring pair object + * @description Creates a keyring pair object with provided account public key, metadata, and encoded arguments. + * The keyring pair stores the account state including the encoded address and associated metadata. + * + * It has properties whose values are functions that may be called to perform account actions: + * + * - `address` function retrieves the address associated with the account. + * - `decodedPkcs8` function is called with the account passphrase and account encoded public key. + * It decodes the encoded public key using the passphrase provided to obtain the decoded account public key + * and associated secret key that are then available in memory, and changes the account address stored in the + * state of the pair to correspond to the address of the decoded public key. + * - `encodePkcs8` function when provided with the correct passphrase associated with the account pair + * and when the secret key is in memory (when the account pair is not locked) it returns an encoded + * public key of the account. + * - `getMeta` returns the metadata that is stored in the state of the pair, either when it was originally + * created or set via `setMeta`. + * - `publicKey` returns the public key stored in memory for the pair. + * - `sign` may be used to return a signature by signing a provided message with the secret + * key (if it is in memory) using Nacl. + * - `toJson` calls another `toJson` function and provides the state of the pair, + * it generates arguments to be passed to the other `toJson` function including an encoded public key of the account + * that it generates using the secret key from memory (if it has been made available in memory) + * and the optionally provided passphrase argument. It passes a third boolean argument to `toJson` + * indicating whether the public key has been encoded or not (if a passphrase argument was provided then it is encoded). + * The `toJson` function that it calls returns a JSON object with properties including the `address` + * and `meta` that are assigned with the values stored in the corresponding state variables of the account pair, + * an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding` + * property that indicates whether the public key value of the `encoded` property is encoded or not. + */ export default function pair ({ publicKey, secretKey }: KeypairType, meta: KeyringPair$Meta = {}, defaultEncoded?: Uint8Array): KeyringPair { const state: PairState = { address: encodeAddress(publicKey), diff --git a/packages/keyring/src/testing.ts b/packages/keyring/src/testing.ts index 1c911787a..2469165cf 100644 --- a/packages/keyring/src/testing.ts +++ b/packages/keyring/src/testing.ts @@ -32,6 +32,28 @@ const SEEDS: { [index: string ]: Uint8Array } = { // hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60') }; +/** + * @name testKeyring + * @signature testKeyring (): KeyringInstance + * @summary Create an instance of Keyring pre-populated with locked test accounts + * @description The test accounts (i.e. alice, bob, dave, eve, ferdie) + * are available on the dev chain and each test account is initialised with DOT funds. + * @example + *
+ * + * ```javascript + * import testKeyring from '@polkadot/keyring/testing'; + * + * // Create an instance of Keyring that includes test accounts + * const keyring = testingPairs(); + * + * // Retrieve the address of one of the test accounts + * const addressAlice = keyring.alice.address(); + * + * // Retrieve the public key of one of the test accounts + * const publicKeyAlice = keyring.alice.publicKey(); + * ``` + */ export default function testKeyring (): KeyringInstance { const keyring = new Keyring(); diff --git a/packages/trie-db/README.md b/packages/trie-db/README.md index 63731190e..4653a115c 100644 --- a/packages/trie-db/README.md +++ b/packages/trie-db/README.md @@ -2,4 +2,32 @@ A re-implementation of a Patricia Trie. Unlike other implementations, this allows for the specification of a hash function as well as encoder/decoder and operates in a sync fashion by default. -This is a JavaScript port of the (Python Ethereum Trie)[https://github.com/ethereum/py-trie] with additions to support transactions (checkpoints) and multiple hashing (npot only Keccak, but also Blake2 as found in Polkadot). +This is a JavaScript port of the [Python Ethereum Trie](https://github.com/ethereum/py-trie) with additions to support transactions (checkpoints) and multiple hashing (npot only Keccak, but also Blake2 as found in Polkadot). + +## Usage + +Installation - + +``` +yarn add @polkadot/trie-db +``` + +Classes can be imported as follows: + +```js +import Trie from '@polkadot/trie-db'; // Default export +``` + +## Documentation and Available Utilities + +Below is a list of currently exposed methods published at the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/trie-db/). + +- [trie-db](https://polkadot.js.org/common/trie-db/README.md) + - Classes + - [Trie](https://polkadot.js.org/common/trie-db/classes/_index_.trie.md) + - Functions + - Util + - [is](https://polkadot.js.org/common/trie-db/modules/_util_is_.md) + - [key](https://polkadot.js.org/common/trie-db/modules/_util_key_.md) + - [nibbles](https://polkadot.js.org/common/trie-db/modules/_util_nibbles_.md) + - [node](https://polkadot.js.org/common/trie-db/modules/_util_node_.md) \ No newline at end of file diff --git a/packages/trie-db/package.json b/packages/trie-db/package.json index c6b715691..5950bc69c 100644 --- a/packages/trie-db/package.json +++ b/packages/trie-db/package.json @@ -1,7 +1,7 @@ { "name": "@polkadot/trie-db", "version": "0.32.3", - "description": "This is an implementation of the modified merkle patricia tree as speficed in Ethereum's yellow paper, adpated for Polkadot", + "description": "This is an implementation of the modified merkle patricia tree as specified in Ethereum's yellow paper, adapted for Polkadot", "main": "index.js", "keywords": [ "Polkadot" @@ -29,13 +29,13 @@ "homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-db#readme", "dependencies": { "@babel/runtime": "^7.0.0", + "@polkadot/db": "^0.32.3", "@polkadot/trie-hash": "^0.32.3", "@polkadot/util": "^0.32.3", "@polkadot/util-crypto": "^0.32.3", "@polkadot/util-rlp": "^0.32.3" }, "devDependencies": { - "@polkadot/db": "^0.32.3", "ethereumjs-testing": "1.0.4" } } diff --git a/packages/trie-db/src/ethereum.spec.js b/packages/trie-db/src/ethereum.spec.js index 146e1727b..505fca0d8 100644 --- a/packages/trie-db/src/ethereum.spec.js +++ b/packages/trie-db/src/ethereum.spec.js @@ -46,7 +46,7 @@ describe('official tests', () => { it(name, () => { keys.map((key) => trie.put(toU8a(key), toU8a(input[key])) - ) + ); expect( u8aToHex(trie.getRoot()) diff --git a/packages/trie-db/src/index.spec.js b/packages/trie-db/src/index.spec.js index 8d0f8dc4d..009119444 100644 --- a/packages/trie-db/src/index.spec.js +++ b/packages/trie-db/src/index.spec.js @@ -7,7 +7,7 @@ import toU8a from '@polkadot/util/u8a/toU8a'; import Trie from './index'; -describe('simple save and retrive', () => { +describe('simple save and retrieve', () => { const trie = new Trie(); it('starts with a valid root', () => { @@ -17,7 +17,7 @@ describe('simple save and retrive', () => { new Uint8Array([ 86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, 192, 1, 98, 47, 181, 227, 99, 180, 33 ]) - ) + ); }); it('save a value', () => { @@ -218,9 +218,9 @@ describe('testing deletions cases', () => { const trie = new Trie(); it('should delete from a branch->branch-branch', () => { - trie.put(new Uint8Array([11, 11, 11]), toU8a('first')), - trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')), - trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch')) + trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); + trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); + trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch')); trie.del(new Uint8Array([12, 22, 22])); const value = trie.get(new Uint8Array([12, 22, 22])); @@ -228,11 +228,11 @@ describe('testing deletions cases', () => { expect(null).toEqual(value); }); - it('should delete from a branch->branch-extention', () => { - trie.put(new Uint8Array([11, 11, 11]), toU8a('first')), - trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')), - trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')), - trie.put(new Uint8Array([12, 33, 44]), toU8a('create the last branch')) + it('should delete from a branch->branch-extension', () => { + trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); + trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); + trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); + trie.put(new Uint8Array([12, 33, 44]), toU8a('create the last branch')); trie.del(new Uint8Array([12, 22, 22])); const value = trie.get(new Uint8Array([12, 22, 22])); @@ -240,7 +240,7 @@ describe('testing deletions cases', () => { expect(null).toEqual(value); }); - it('should delete from a extention->branch-extention', () => { + it('should delete from a extension->branch-extension', () => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); @@ -252,7 +252,7 @@ describe('testing deletions cases', () => { expect(null).toEqual(value); }); - it('should delete from a extention->branch-branch', () => { + it('should delete from a extension->branch-branch', () => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); diff --git a/packages/trie-db/src/index.ts b/packages/trie-db/src/index.ts index f68120a54..8a3244098 100644 --- a/packages/trie-db/src/index.ts +++ b/packages/trie-db/src/index.ts @@ -18,6 +18,15 @@ import { EMPTY_HASH, EMPTY_U8A } from './constants'; const l = logger('trie/db'); +/** + * # @polkadot/common/trie-db + * + * ## Overview + * + * @name Trie + * @summary Re-implementation of a Patricia Trie + * @example See [Polkadot-JS Common Trie-DB Examples](https://polkadot.js.org/api/common/examples/trie-db/) + */ export default class Trie implements TrieDb { readonly db: TxDb; private txRoot: Uint8Array; diff --git a/packages/trie-db/src/util/is.ts b/packages/trie-db/src/util/is.ts index 846302704..03eb0d024 100644 --- a/packages/trie-db/src/util/is.ts +++ b/packages/trie-db/src/util/is.ts @@ -8,22 +8,52 @@ import { isNull } from '@polkadot/util/index'; import { getNodeType } from './node'; +/** + * @name isEmptyNode + * @signature isEmptyNode (node: Node): node is NodeEmpty + * @summary Returns true if node is NULL + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export function isEmptyNode (node: Node): node is NodeEmpty { return isNull(node); } +/** + * @name isKvNode + * @signature isKvNode (node: Node): node is NodeKv + * @summary Returns true if node is not empty and contains a single key/value pair + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export function isKvNode (node: Node): node is NodeKv { return !isEmptyNode(node) && node.length === 2; } +/** + * @name isExtensionNode + * @signature isExtensionNode (node: Node): node is NodeKv + * @summary Returns true if node is an Extension 2-item node + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export function isExtensionNode (node: Node): node is NodeKv { return getNodeType(node) === NodeType.EXTENSION; } +/** + * @name isLeafNode + * @signature isLeafNode (node: Node): node is NodeKv + * @summary Returns true if node is an Leaf 2-item node + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export function isLeafNode (node: Node): node is NodeKv { return getNodeType(node) === NodeType.LEAF; } +/** + * @name isBranchNode + * @signature isBranchNode (node: Node): node is NodeKv + * @summary Returns true if node is an Branch 17-item node + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export function isBranchNode (node: Node): node is NodeBranch { return !isEmptyNode(node) && node.length === 17; } diff --git a/packages/trie-hash/README.md b/packages/trie-hash/README.md index 93108e333..0a1ec56a0 100644 --- a/packages/trie-hash/README.md +++ b/packages/trie-hash/README.md @@ -1,17 +1,41 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square) -[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/trie-hash.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/trie-hash) -[![travis](https://img.shields.io/travis/polkadot-js/trie.svg?style=flat-square)](https://travis-ci.org/polkadot-js/trie) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/trie.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/trie/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/trie.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/trie?branch=master) -[![dependency](https://david-dm.org/polkadot-js/trie.svg?style=flat-square&path=packages/trie)](https://david-dm.org/polkadot-js/trie?path=packages/trie-hash) -[![devDependency](https://david-dm.org/polkadot-js/trie/dev-status.svg?style=flat-square&path=packages/trie-hash)](https://david-dm.org/polkadot-js/trie?path=packages/trie-hash#info=devDependencies) - # @polkadot/trie-hash Calculate ordered and unordered [Ethereum Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree) from inputs. -## Available Utilities +## Usage -For a list of currently exposed methods, see the [library documentation](docs/README.md). +Installation - + +``` +yarn add @polkadot/trie-hash +``` + +Functions can be imported as follows: + +```js +import { trieRoot } from '@polkadot/trie-hash'; +``` + +## Documentation and Available Utilities + +Below is a list of currently exposed methods published at the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/trie-hash/). + +- [trie-hash](https://polkadot.js.org/common/trie-hash/README.md) + - Functions + - Encode + - [encode](https://polkadot.js.org/common/trie-hash/modules/_encode_index_.md) + - [encodeAux](https://polkadot.js.org/common/trie-hash/modules/_encode_aux_.md) + - [encodeHexPrefix](https://polkadot.js.org/common/trie-hash/modules/_encode_hexprefix_.md) + - [encodePairs](https://polkadot.js.org/common/trie-hash/modules/_encode_pairs_.md) + - [encodeShared](https://polkadot.js.org/common/trie-hash/modules/_encode_shared_.md) + - [encodeSingle](https://polkadot.js.org/common/trie-hash/modules/_encode_single_.md) + - Trie Root + - [trieRoot](https://polkadot.js.org/common/trie-hash/modules/_root_.md) + - [trieRootOrdered](https://polkadot.js.org/common/trie-hash/modules/_rootordered_.md) + - Util + - [asNibbles](https://polkadot.js.org/common/trie-hash/modules/_util_asnibbles_.md) + - [fromNibbles](https://polkadot.js.org/common/trie-hash/modules/_util_fromnibbles_.md) + - [genRoot](https://polkadot.js.org/common/trie-hash/modules/_util_genroot_.md) + - [getSharedLength](https://polkadot.js.org/common/trie-hash/modules/_util_sharedlength_.md) + - [pairsUniq](https://polkadot.js.org/common/trie-hash/modules/_util_pairsuniq_.md) + - [sharedPrefixLength](https://polkadot.js.org/common/trie-hash/modules/_util_sharedprefixlength_.md) diff --git a/packages/trie-hash/docs/README.md b/packages/trie-hash/docs/README.md deleted file mode 100644 index 00c6649a7..000000000 --- a/packages/trie-hash/docs/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# Available interfaces - -Utility methods to create [Ethereum Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree) - - -# Available methods - -## trieRoot - -Creates a trie hash from the supplied pairs. - -```js -trieRoot (pairs: Trie$Pairs): Uint8Array -``` - - -From an `Array<{k: Uint8Array, v: Uint8Array}>` input, calculate the triehash and return the result as a `Uint8Array`. - -```js -import { stringToU8a } from '@polkadot/util'; -import { trieRoot } from '@polkadot/trie-hash'; - -trieRoot([{ -k: stringToU8a('A'), -v: stringToU8a('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') -}]) // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab -``` - -## trieRootOrdered - -Creates a trie hash from the supplied values. - -```js -trieRootOrdered (values: Array): Uint8Array -``` - - -From an `Array` input, calculate the ordered triehash and return the result as a `Uint8Array`. - -```js -import { stringToU8a } from '@polkadot/util'; -import { trieRootOrdered } from '@polkadot/trie-hash'; - -trieRootOrdered([ -stringToU8a('doe'), -stringToU8a('reindeer') -]) // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3 -``` diff --git a/packages/trie-hash/src/encode/aux.ts b/packages/trie-hash/src/encode/aux.ts index b71b16b58..fac8e271d 100644 --- a/packages/trie-hash/src/encode/aux.ts +++ b/packages/trie-hash/src/encode/aux.ts @@ -9,7 +9,7 @@ import rlpEncode from '@polkadot/util-rlp/encode'; import encode from './index'; -export default function encodeAux (pairs: Trie$Pairs, preLength: number): any { +export default function encodeAux (pairs: Trie$Pairs, preLength: number): Uint8Array | any[] { const encoded = encode(pairs, preLength); const rlped = rlpEncode(encoded); diff --git a/packages/trie-hash/src/encode/index.ts b/packages/trie-hash/src/encode/index.ts index 0ac2029b1..abfdda2aa 100644 --- a/packages/trie-hash/src/encode/index.ts +++ b/packages/trie-hash/src/encode/index.ts @@ -9,6 +9,30 @@ import encodeShared from './shared'; import encodeSingle from './single'; import sharedPrefixLength from '../util/sharedPrefixLength'; +/** + * @name encode + * @signature encode (pairs: Trie$Pairs, preLength: number): Array + * @summary Encodes Trie Pairs depending on a provided Prefix Length and the amount of pairs + * @description + * - `encode` is called and provided arguments including Trie Pairs and Prefix Length. + * - If the Trie Pairs have no length then return an empty array + * - If the Trie Pairs have a length of 1 then we call `encodeSingle` to return a single encoded array with two elements. + * The first element is a u8a calculated from calling `encodeHexPrefix` with arguments including + * a slice up to the Prefix Length of the pair's key (aka nibbles), and whether it's a leaf. + * The second element is the pair's value. + * - If the Trie Pairs have a length > 1 and we calculate that their Shared Prefix Length > Prefix Length + * then we return early with the results of calling `encodeShared` to return a single encoded array + * with two elements. The first element is a u8a calculated as previously with `encodeHexPrefix` and + * whereas second element is calculated from calling `encodeAux`, which recursively calls this function `encode` + * to obtain an encoded value, and then Recursive Length Prefix (RLP) encodes it. If the length of the RLP encoded u8a + * is less than 32 then return the RLP encoded value, otherwise return call the Keccak-256 hash function from [js-sha3](https://www.npmjs.com/package/js-sha3) library + * on the RLP encoded value and return the result. + * - If the Trie Pairs have a length > 1 and the calculated Share Prefix Length <= Prefix Length + * then we return the array result of calling `encodePairs` and push the pair's value onto the end of the array + * if the Prefix Length !== Pair's Key Length. + * + * @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization) + */ export default function encode (pairs: Trie$Pairs, preLength: number): Array { if (pairs.length === 0) { return []; diff --git a/packages/trie-hash/src/root.ts b/packages/trie-hash/src/root.ts index 4c9cb1c78..125e3b22b 100644 --- a/packages/trie-hash/src/root.ts +++ b/packages/trie-hash/src/root.ts @@ -15,13 +15,17 @@ import pairsUniq from './util/pairsUniq'; * @description * From an `Array<{k: Uint8Array, v: Uint8Array}>` input, calculate the triehash and return the result as a `Uint8Array`. * @example - * import { stringToU8a } from '@polkadot/util'; - * import { trieRoot } from '@polkadot/trie-hash'; + *
* - * trieRoot([{ - * k: stringToU8a('A'), - * v: stringToU8a('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') - * }]) // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab + * ```javascript + * import { stringToU8a } from '@polkadot/util'; + * import { trieRoot } from '@polkadot/trie-hash'; + * + * trieRoot([{ + * k: stringToU8a('A'), + * v: stringToU8a('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') + * }]); // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab + * ``` */ export default function trieRoot (pairs: Trie$Pairs): Uint8Array { return genRoot( diff --git a/packages/trie-hash/src/rootOrdered.ts b/packages/trie-hash/src/rootOrdered.ts index 4cbd73f30..e4aa858c3 100644 --- a/packages/trie-hash/src/rootOrdered.ts +++ b/packages/trie-hash/src/rootOrdered.ts @@ -14,13 +14,17 @@ import pairsUniq from './util/pairsUniq'; * @description * From an `Array` input, calculate the ordered triehash and return the result as a `Uint8Array`. * @example - * import { stringToU8a } from '@polkadot/util'; - * import { trieRootOrdered } from '@polkadot/trie-hash'; + *
* - * trieRootOrdered([ - * stringToU8a('doe'), - * stringToU8a('reindeer') - * ]) // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3 + * ```javascript + * import { stringToU8a } from '@polkadot/util'; + * import { trieRootOrdered } from '@polkadot/trie-hash'; + * + * trieRootOrdered([ + * stringToU8a('doe'), + * stringToU8a('reindeer') + * ]); // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3 + * ``` */ export default function trieRootOrdered (values: Array): Uint8Array { return genRoot( diff --git a/packages/trie-hash/src/util/asNibbles.ts b/packages/trie-hash/src/util/asNibbles.ts index e9afaf7df..5866cb220 100644 --- a/packages/trie-hash/src/util/asNibbles.ts +++ b/packages/trie-hash/src/util/asNibbles.ts @@ -9,9 +9,13 @@ * @description * From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input. * @example - * import { asNibbles } from '@polkadot/trie-hash/util'; + *
* - * asNibbles(new Uint8Array([0x41, 0x20]) // => Uint8Array([4, 1, 2, 0]) + * ```javascript + * import { asNibbles } from '@polkadot/trie-hash/util'; + * + * asNibbles(new Uint8Array([0x41, 0x20]); // => Uint8Array([4, 1, 2, 0]) + * ``` */ export default function asNibbles (bytes: Uint8Array | Array | null): Uint8Array { if (bytes === null) { diff --git a/packages/trie-hash/src/util/fromNibbles.ts b/packages/trie-hash/src/util/fromNibbles.ts index cc83e840b..e1a7c7dbd 100644 --- a/packages/trie-hash/src/util/fromNibbles.ts +++ b/packages/trie-hash/src/util/fromNibbles.ts @@ -9,9 +9,13 @@ * @description * From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input. * @example - * import { fromNibbles } from '@polkadot/trie-hash/util'; + *
* - * asNibbles(new Uint8Array([4, 1, 2, 0])) // => Uint8Array([0x41, 0x20] + * ```javascript + * import { fromNibbles } from '@polkadot/trie-hash/util'; + * + * asNibbles(new Uint8Array([4, 1, 2, 0])); // => Uint8Array([0x41, 0x20] + * ``` */ export default function fromNibbles (nibbles: Uint8Array | Array): Uint8Array { const u8a = new Uint8Array(nibbles.length / 2); diff --git a/packages/trie-hash/src/util/genRoot.ts b/packages/trie-hash/src/util/genRoot.ts index 0d3a90b60..f301ed195 100644 --- a/packages/trie-hash/src/util/genRoot.ts +++ b/packages/trie-hash/src/util/genRoot.ts @@ -9,6 +9,11 @@ import rlpEncode from '@polkadot/util-rlp/encode'; import encode from '../encode'; +/** + * @name genRoot + * @signature genRoot (pairs: Trie$Pairs): Uint8Array + * @summary Encodes supplied pairs into u8a output by calculating with RLP. + */ export default function genRoot (pairs: Trie$Pairs): Uint8Array { const encoded = encode(pairs, 0); diff --git a/packages/trie-hash/src/util/pairsUniq.ts b/packages/trie-hash/src/util/pairsUniq.ts index b6a5e9724..34587a91e 100644 --- a/packages/trie-hash/src/util/pairsUniq.ts +++ b/packages/trie-hash/src/util/pairsUniq.ts @@ -10,6 +10,11 @@ type PairMap = { [index: string]: Trie$Pair }; +/** + * @name pairsUniq + * @signature pairsUniq (pairs: Trie$Pairs): Trie$Pairs + * @summary Removes pairs with duplicate keys from the supplied pairs. + */ export default function pairsUniq (pairs: Trie$Pairs): Trie$Pairs { const map = pairs.reduce((result, pair) => { result[u8aToHex(pair.k)] = pair; diff --git a/packages/trie-hash/src/util/sharedLength.ts b/packages/trie-hash/src/util/sharedLength.ts index 55402c6c0..745a74652 100644 --- a/packages/trie-hash/src/util/sharedLength.ts +++ b/packages/trie-hash/src/util/sharedLength.ts @@ -2,6 +2,14 @@ // This software may be modified and distributed under the terms // of the ISC license. See the LICENSE file for details. +/** + * @name getSharedLength + * @signature getSharedLength (a: Uint8Array, b: Uint8Array): number + * @summary Returns the highest shared index of two u8a's where the values in lesser indexes are the same. + * Given two u8a's, it first determines the u8a with the shortest length, + * then iterates through each u8a up to that length. If the value in both u8a's is + * the same for a certain index, it returns that index, otherwise it returns the shortest length. + */ export default function getSharedLength (a: Uint8Array, b: Uint8Array): number { const count = Math.min(a.length, b.length); diff --git a/packages/trie-hash/src/util/sharedPrefixLength.ts b/packages/trie-hash/src/util/sharedPrefixLength.ts index 279f91cd4..92ddb819f 100644 --- a/packages/trie-hash/src/util/sharedPrefixLength.ts +++ b/packages/trie-hash/src/util/sharedPrefixLength.ts @@ -6,6 +6,10 @@ import { Trie$Pairs } from '../types'; import getSharedLength from './sharedLength'; +/** + * @name sharedPrefixLength + * @signature sharedPrefixLength (pairs: Trie$Pairs): number + */ export default function sharedPrefixLength (pairs: Trie$Pairs): number { return pairs.reduce((length, { k }, index) => { if (index === 0) { diff --git a/packages/util-crypto/README.md b/packages/util-crypto/README.md index a9f8d24c1..0d1913851 100644 --- a/packages/util-crypto/README.md +++ b/packages/util-crypto/README.md @@ -1,17 +1,106 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square) -[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/util-crypto.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/util-crypto) -[![travis](https://img.shields.io/travis/polkadot-js/common.svg?style=flat-square)](https://travis-ci.org/polkadot-js/common) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/common.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/common?branch=master) -[![dependency](https://david-dm.org/polkadot-js/common.svg?style=flat-square&path=packages/util)](https://david-dm.org/polkadot-js/common?path=packages/util-crypto) -[![devDependency](https://david-dm.org/polkadot-js/common/dev-status.svg?style=flat-square&path=packages/util-crypto)](https://david-dm.org/polkadot-js/common?path=packages/util-crypto#info=devDependencies) - # @polkadot/util-crypto Various useful cyrpto utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. -## Available Utilities +## Usage -For a list of currently exposed methods, see the [library documentation](docs/README.md). +Installation - + +``` +yarn add @polkadot/util-crypto +``` + +Functions can be imported as follows: + +```js +import { mnemonicGenerate } from '@polkadot/util-crypto'; +``` + +## Documentation and Available Utilities + +Below is a list of currently exposed methods published at the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/util-crypto/). + +- [util-crypto](https://polkadot.js.org/common/util-crypto/README.md) + - Functions + - Blake2b + - [blake2AsHex](https://polkadot.js.org/common/util-crypto/modules/_blake2_ashex_.md) + - [blake2AsU8a](https://polkadot.js.org/common/util-crypto/modules/_blake2_asu8a_.md) + - [blake2bAsHex](https://polkadot.js.org/common/util-crypto/modules/_blake2_blake2b_ashex_.md) + - [blake2bAsU8a](https://polkadot.js.org/common/util-crypto/modules/_blake2_blake2b_asu8a_.md) + - Keccak + - [keccakAsHex](https://polkadot.js.org/common/util-crypto/modules/_keccak_ashex_.md) + - [keccakAsU8a](https://polkadot.js.org/common/util-crypto/modules/_keccak_asu8a_.md) + - Mnemonic + - [mnemonicGenerate](https://polkadot.js.org/common/util-crypto/modules/_mnemonic_generate_.md) + - [mnemonicToSeed](https://polkadot.js.org/common/util-crypto/modules/_mnemonic_toseed_.md) + - [mnemonicValidate](https://polkadot.js.org/common/util-crypto/modules/_mnemonic_validate_.md) + - Nacl + - [naclDecrypt](https://polkadot.js.org/common/util-crypto/modules/_nacl_decrypt_.md) + - [naclEncrypt](https://polkadot.js.org/common/util-crypto/modules/_nacl_encrypt_.md) + - [naclKeypairFromRandom](https://polkadot.js.org/common/util-crypto/modules/_nacl_keypair_fromrandom_.md) + - [naclKeypairFromSecret](https://polkadot.js.org/common/util-crypto/modules/_nacl_keypair_fromsecret_.md) + - [naclKeypairFromSeed](https://polkadot.js.org/common/util-crypto/modules/_nacl_keypair_fromseed_.md) + - [naclKeypairFromString](https://polkadot.js.org/common/util-crypto/modules/_nacl_keypair_fromstring_.md) + - [naclSign](https://polkadot.js.org/common/util-crypto/modules/_nacl_sign_.md) + - [naclVerify](https://polkadot.js.org/common/util-crypto/modules/_nacl_verify_.md) + - Random + - [randomAsHex](https://polkadot.js.org/common/util-crypto/modules/_random_ashex_.md) + - [randomAsNumber](https://polkadot.js.org/common/util-crypto/modules/_random_asnumber_.md) + - [randomAsU8a](https://polkadot.js.org/common/util-crypto/modules/_random_asu8a_.md) + - SHA-512 + - [sha512AsU8a](https://polkadot.js.org/common/util-crypto/modules/_sha512_asu8a_.md) + - xxHash + - [xxhashAsHex](https://polkadot.js.org/common/util-crypto/modules/_xxhash_ashex_.md) + - [xxhashAsU8a](https://polkadot.js.org/common/util-crypto/modules/_xxhash_asu8a_.md) + - [xxhash64AsBn](https://polkadot.js.org/common/util-crypto/modules/_xxhash_xxhash64_asbn_.md) + - [xxhash64AsHex](https://polkadot.js.org/common/util-crypto/modules/_xxhash_xxhash64_ashex_.md) + - [xxhash64AsRaw](https://polkadot.js.org/common/util-crypto/modules/_xxhash_xxhash64_asraw_.md) + - [xxhash64AsValue](https://polkadot.js.org/common/util-crypto/modules/_xxhash_xxhash64_asvalue_.md) + +### Blake2b + +* Creates a blake2b u8a output containing a hash from a u8a input bytes using given bit-length or default bit-length of 256. An optional key u8a of up to 64 bytes may be provided +* Creates a blake2b hex string with optionally specified bit-length from the u8a input or default bit-length used is 256 +* Uses the [Blake2b](https://blake2.net/) hash function of [blakejs](https://www.npmjs.com/package/blakejs) library +* Note: All hashes used in Polkadot-JS are 32 bytes (i.e. 256 / 8) +* Note: BLAKE hash functions are in the Nacl library +* Note: Only handles up to 2**53 bytes of input + +### Keccak + +* Creates a Keccak-256 hex string from the input (such as for conversion from seed phrase) +* Creates a Keccak-256 Uint8Array from the input +* Uses the Keccak-256 hash function from the [js-sha3](https://www.npmjs.com/package/js-sha3) library + +### Mnemonic + +* Generate valid mnemonics (for account seed phrase) using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) +* Converts mnemonics to a valid seed secret with Uint8Array output + +### Nacl + +* Implements [NaCl](http://nacl.cr.yp.to/) secret-key authenticated encryption, public-key authenticated encryption, hashing, and public-key signatures +* Decrypts a message that has been encrypted with a secret key using Nacl +* Encrypts a message with a secret key and generates an associated nonce using Nacl +* Signing a message with a secret key to generate a valid signature using Nacl +* Verifies a signed message by providing the message, signature, and public key (associated with the secret key that signed it) using Nacl + +### Random + +* Returns a sequence of secure random bytes in a variety of formats +* Creates a u8a with a specified (optional) bit-length (default 32) filled with random bytes +* Creates a hex string with a specified (optional) bit-length (default 32) filled with random bytes +* Creates a random number from random secure bytes + +### SHA-512 + +* Implements SHA-512 hashing functions for a variety of input and outputs +* Creates a SHA-512 hash of u8a input +* Uses the SHA-512 hash function of [tweetnacl](https://www.npmjs.com/package/tweetnacl) library + +### xxHash + +* Create xxhash64 values with specified bitlengths +* Creates a xxhash64 u8a from the input with a specified (optional) bit-length (default 64) +* Creates a xxhash64 hex string from the input with a specified (optional) bit-length (default 64) +* Uses [xxHash](http://cyan4973.github.io/xxHash/) to generate values as BN, hex & number output diff --git a/packages/util-crypto/docs/README.md b/packages/util-crypto/docs/README.md deleted file mode 100644 index 118b42ea1..000000000 --- a/packages/util-crypto/docs/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Available interfaces - - - -- [blake2](blake2.md) Create blake2b values with specified bitlengths -- [keccak](keccak.md) Create Keccak256 values as hex & Uint8Array output -- [nacl](nacl.md) Implements [NaCl](http://nacl.cr.yp.to/) secret-key authenticated encryption, public-key authenticated encryption, hashing, and public-key signatures -- [random](random.md) Returns a sequence of secure random bytes in a variety of formats -- [sha512](sha512.md) Implements Sha-512 hashing functions for a variety of input and outputs -- [xxhash](xxhash.md) Create xxhash64 values with specified bitlengths - diff --git a/packages/util-crypto/docs/blake2.md b/packages/util-crypto/docs/blake2.md deleted file mode 100644 index 155d6c236..000000000 --- a/packages/util-crypto/docs/blake2.md +++ /dev/null @@ -1,40 +0,0 @@ -# blake2 - -Create blake2b values with specified bitlengths - -- [blake2AsHex](#blake2ashex) Creates a blake2b hex from the input. -- [blake2AsU8a](#blake2asu8a) Creates a blake2b u8a from the input. - -## blake2AsHex - -Creates a blake2b hex from the input. - -```js -blake2AsHex (data: Uint8Array, bitLenght: number = 256): string -``` - - -From a `Uint8Array` input, create the blake2b and return the result as a hex string with the specified `bitLength`. - -```js -import { blake2AsHex } from '@polkadot/util-crypto'; - -blake2AsHex('abc') // => 0xba80a53f981c4d0d -``` - -## blake2AsU8a - -Creates a blake2b u8a from the input. - -```js -blake2AsU8a (data: Uint8Array, bitLenght: number = 256): Uint8Array -``` - - -From a `Uint8Array` input, create the blake2b and return the result as a u8a with the specified `bitLength`. - -```js -import { blake2AsU8a } from '@polkadot/util-crypto'; - -blake2AsU8a('abc') // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d] -``` \ No newline at end of file diff --git a/packages/util-crypto/docs/keccak.md b/packages/util-crypto/docs/keccak.md deleted file mode 100644 index 967e18c04..000000000 --- a/packages/util-crypto/docs/keccak.md +++ /dev/null @@ -1,40 +0,0 @@ -# keccak - -Create Keccak256 values as hex & Uint8Array output - -- [keccakAsHex](#keccakashex) Creates a keccak hex string from the input. -- [keccakAsU8a](#keccakasu8a) Creates a keccak Uint8Array from the input. - -## keccakAsHex - -Creates a keccak hex string from the input. - -```js -keccakAsHex (value: Buffer | Uint8Array | string): string -``` - - -From either a `string` or a `Buffer` input, create the keccak and return the result as a `0x` prefixed hex string. - -```js -import { keccakAsHex } from '@polkadot/util-crypto'; - -keccakAsHex('123') // => 0x... -``` - -## keccakAsU8a - -Creates a keccak Uint8Array from the input. - -```js -keccakAsU8a (value: Buffer | Uint8Array | string): Uint8Array -``` - - -From either a `string` or a `Buffer` input, create the keccak and return the result as a `Uint8Array`. - -```js -import { keccakAsU8a } from '@polkadot/util-crypto'; - -keccakAsU8a('123') // => Uint8Array -``` \ No newline at end of file diff --git a/packages/util-crypto/docs/nacl.md b/packages/util-crypto/docs/nacl.md deleted file mode 100644 index aa72b1176..000000000 --- a/packages/util-crypto/docs/nacl.md +++ /dev/null @@ -1,76 +0,0 @@ -# nacl - -Implements [NaCl](http://nacl.cr.yp.to/) secret-key authenticated encryption, public-key authenticated encryption, hashing, and public-key signatures - -- [naclDecrypt](#nacldecrypt) Decrypts a message using the supplied secretKey and nonce -- [naclEncrypt](#naclencrypt) Encrypts a message using the supplied secretKey and nonce -- [naclSign](#naclsign) Signs a message using the supplied secretKey -- [naclSign](#naclsign) Verifies the signature on the supplied message. - -## naclDecrypt - -Decrypts a message using the supplied secretKey and nonce - -```js -naclDecrypt (message: Uint8Array, nonce: Uint8Array, secret: Uint8Array): Uint8Array -``` - - -Returns an decrypted message, using the `secret` and `nonce`. - -```js -import { naclDecrypt } from '@polkadot/util-crypto'; - -naclDecrypt([...], [...], [...]) // => [...] -``` - -## naclEncrypt - -Encrypts a message using the supplied secretKey and nonce - -```js -naclEncrypt (message: Uint8Array, secret: Uint8Array, nonce?: Uint8Array): { encrypted: Uint8Array, nonce: Uint8Array } -``` - - -Returns an encrypted message, using the `secretKey` and `nonce`. If the `nonce` was not supplied, a random value is generated. - -```js -import { naclEncrypt } from '@polkadot/util-crypto'; - -naclSign([...], [...]) // => [...] -``` - -## naclSign - -Signs a message using the supplied secretKey - -```js -naclSign (message: Uint8Array, secretKey: Uint8Array): Uint8Array -``` - - -Returns message signature of `message`, using the `secretKey`. - -```js -import { naclSign } from '@polkadot/util-crypto'; - -naclSign([...], [...]) // => [...] -``` - -## naclSign - -Verifies the signature on the supplied message. - -```js -naclVerify (message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean -``` - - -Verifies the `signature` on `message` with the supplied `plublicKey`. Returns `true` on sucess, `false` otherwise. - -```js -import { naclVerify } from '@polkadot/util-crypto'; - -naclVerify([...], [...], [...]) // => true/false -``` \ No newline at end of file diff --git a/packages/util-crypto/docs/random.md b/packages/util-crypto/docs/random.md deleted file mode 100644 index cf491c8e2..000000000 --- a/packages/util-crypto/docs/random.md +++ /dev/null @@ -1,58 +0,0 @@ -# random - -Returns a sequence of secure random bytes in a variety of formats - -- [randomAsHex](#randomashex) Creates a hex string filled with random bytes. -- [randomAsNumber](#randomasnumber) Creates a random number from random bytes. -- [randomAsU8a](#randomasu8a) Creates a Uint8Array filled with random bytes. - -## randomAsHex - -Creates a hex string filled with random bytes. - -```js -randomAsHex (length?: number = 32): string -``` - - -Returns a hex string with the specified (optional) length filled with random bytes. - -```js -import { randomAsHex } from '@polkadot/util-crypto'; - -randomAsHex() // => 0x... -``` - -## randomAsNumber - -Creates a random number from random bytes. - -```js -randomAsNumber (): number -``` - - -Returns a random number generated from the secure bytes. - -```js -import { randomAsNumber } from '@polkadot/util-crypto'; - -randomAsNumber() // => -``` - -## randomAsU8a - -Creates a Uint8Array filled with random bytes. - -```js -randomAsU8a (length?: number = 32): Uint8Array -``` - - -Returns a `Uint8Array` with the specified (optional) length filled with random bytes. - -```js -import { randomAsU8a } from '@polkadot/util-crypto'; - -randomAsU8s() // => Uint8Array([...]) -``` \ No newline at end of file diff --git a/packages/util-crypto/docs/sha512.md b/packages/util-crypto/docs/sha512.md deleted file mode 100644 index 4033d44a6..000000000 --- a/packages/util-crypto/docs/sha512.md +++ /dev/null @@ -1,22 +0,0 @@ -# sha512 - -Implements Sha-512 hashing functions for a variety of input and outputs - -- [sha512AsU8a](#sha512asu8a) Creates sha-512 hash of the input. - -## sha512AsU8a - -Creates sha-512 hash of the input. - -```js -sha512AsU8a (data: Uint8Array): Uint8Array -``` - - -Returns a sha-512 `Uint8Array` from the supplied data. - -```js -import { sha512AsU8a } from '@polkadot/util-crypto'; - -sha512AsU8a(Uint8Array.from([...])) // => Uint8Array([...]) -``` \ No newline at end of file diff --git a/packages/util-crypto/docs/xxhash.md b/packages/util-crypto/docs/xxhash.md deleted file mode 100644 index 4c5a9bf07..000000000 --- a/packages/util-crypto/docs/xxhash.md +++ /dev/null @@ -1,40 +0,0 @@ -# xxhash - -Create xxhash64 values with specified bitlengths - -- [xxhashAsHex](#xxhashashex) Creates a xxhash64 hex from the input. -- [xxhashAsU8a](#xxhashasu8a) Creates a xxhash64 u8a from the input. - -## xxhashAsHex - -Creates a xxhash64 hex from the input. - -```js -xxhashAsHex (data: Buffer | Uint8Array | string, bitLenght: number = 64): string -``` - - -From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a hex string with the specified `bitLength`. - -```js -import { xxhashAsHex } from '@polkadot/util-crypto'; - -xxhashAsHex('abc') // => 0x44bc2cf5ad770999 -``` - -## xxhashAsU8a - -Creates a xxhash64 u8a from the input. - -```js -xxhashAsU8a (data: Buffer | Uint8Array | string, bitLenght: number = 64): Uint8Array -``` - - -From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a `Uint8Array` with the specified `bitLength`. - -```js -import { xxhashAsU8a } from '@polkadot/util-crypto'; - -xxhashAsU8a('abc') // => 0x44bc2cf5ad770999 -``` \ No newline at end of file diff --git a/packages/util-crypto/src/blake2/asHex.ts b/packages/util-crypto/src/blake2/asHex.ts index 0575cb113..9fd710489 100644 --- a/packages/util-crypto/src/blake2/asHex.ts +++ b/packages/util-crypto/src/blake2/asHex.ts @@ -6,14 +6,18 @@ import blake2bAsHex from './blake2b/asHex'; /** * @name blake2AsHex - * @signature blake2AsHex (data: Uint8Array, bitLenght: number = 256): string + * @signature blake2AsHex (data: Uint8Array, bitLength: number = 256): string * @summary Creates a blake2b hex from the input. * @description * From a `Uint8Array` input, create the blake2b and return the result as a hex string with the specified `bitLength`. * @example - * import { blake2AsHex } from '@polkadot/util-crypto'; + *
* - * blake2AsHex('abc') // => 0xba80a53f981c4d0d + * ```javascript + * import { blake2AsHex } from '@polkadot/util-crypto'; + * + * blake2AsHex('abc'); // => 0xba80a53f981c4d0d + * ``` */ export default function blake2AsHex (data: Uint8Array, bitLength: number = 256): string { return blake2bAsHex(data, bitLength); diff --git a/packages/util-crypto/src/blake2/asU8a.ts b/packages/util-crypto/src/blake2/asU8a.ts index a99496af9..acf144c93 100644 --- a/packages/util-crypto/src/blake2/asU8a.ts +++ b/packages/util-crypto/src/blake2/asU8a.ts @@ -6,14 +6,18 @@ import blake2bAsU8a from './blake2b/asU8a'; /** * @name blake2AsU8a - * @signature blake2AsU8a (data: Uint8Array, bitLenght: number = 256): Uint8Array + * @signature blake2AsU8a (data: Uint8Array, bitLength: number = 256): Uint8Array * @summary Creates a blake2b u8a from the input. * @description * From a `Uint8Array` input, create the blake2b and return the result as a u8a with the specified `bitLength`. * @example - * import { blake2AsU8a } from '@polkadot/util-crypto'; + *
* - * blake2AsU8a('abc') // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d] + * ```javascript + * import { blake2AsU8a } from '@polkadot/util-crypto'; + * + * blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d] + * ``` */ export default function blake2AsU8a (data: Uint8Array, bitLength: number = 256, key?: Uint8Array): Uint8Array { return blake2bAsU8a(data, bitLength, key); diff --git a/packages/util-crypto/src/blake2/blake2b/asHex.ts b/packages/util-crypto/src/blake2/blake2b/asHex.ts index 0f2949e3e..234b0bce4 100644 --- a/packages/util-crypto/src/blake2/blake2b/asHex.ts +++ b/packages/util-crypto/src/blake2/blake2b/asHex.ts @@ -13,9 +13,13 @@ import blake2bAsU8a from './asU8a'; * @description * From a `Uint8Array` input, create the blake2b and return the result as a hex string. * @example - * import { blake2bAsHex } from '@polkadot/util-crypto'; + *
* - * blake2bAsHex('abc') // => '0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923' + * ```javascript + * import { blake2bAsHex } from '@polkadot/util-crypto'; + * + * blake2bAsHex('abc'); // => '0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923' + * ``` */ export default function blake2bAsHex (data: Uint8Array, bitLength: number = 512): string { return u8aToHex( diff --git a/packages/util-crypto/src/blake2/blake2b/asU8a.ts b/packages/util-crypto/src/blake2/blake2b/asU8a.ts index b51d4c07d..39679b409 100644 --- a/packages/util-crypto/src/blake2/blake2b/asU8a.ts +++ b/packages/util-crypto/src/blake2/blake2b/asU8a.ts @@ -12,9 +12,13 @@ import blakejs from 'blakejs'; * @description * From a `Uint8Array` input, create the blake2b and return the result as a `Uint8Array`. * @example - * import { blake2bAsU8a } from '@polkadot/util-crypto'; + *
* - * blake2bAsU8a('abc') // => Uint8Array('508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982') + * ```javascript + * import { blake2bAsU8a } from '@polkadot/util-crypto'; + * + * blake2bAsU8a('abc'); // => Uint8Array('508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982') + * ``` */ export default function blake2bAsU8a (data: Uint8Array, bitLength: number = 512, key: Uint8Array | null = null): Uint8Array { return blakejs.blake2b(data, key, bitLength / 8); diff --git a/packages/util-crypto/src/index.ts b/packages/util-crypto/src/index.ts index b58ca205f..aa34f2bcc 100644 --- a/packages/util-crypto/src/index.ts +++ b/packages/util-crypto/src/index.ts @@ -3,6 +3,7 @@ // of the ISC license. See the LICENSE file for details. export * from './blake2'; +export * from './mnemonic'; export * from './keccak'; export * from './mnemonic'; export * from './nacl'; diff --git a/packages/util-crypto/src/keccak/asHex.ts b/packages/util-crypto/src/keccak/asHex.ts index 5baad58c1..99522798b 100644 --- a/packages/util-crypto/src/keccak/asHex.ts +++ b/packages/util-crypto/src/keccak/asHex.ts @@ -13,9 +13,13 @@ import keccakAsU8a from './asU8a'; * @description * From either a `string` or a `Buffer` input, create the keccak and return the result as a `0x` prefixed hex string. * @example - * import { keccakAsHex } from '@polkadot/util-crypto'; + *
* - * keccakAsHex('123') // => 0x... + * ```javascript + * import { keccakAsHex } from '@polkadot/util-crypto'; + * + * keccakAsHex('123'); // => 0x... + * ``` */ export default function keccakAsHex (value: Buffer | Uint8Array | string): string { return u8aToHex( diff --git a/packages/util-crypto/src/keccak/asU8a.ts b/packages/util-crypto/src/keccak/asU8a.ts index d827ad8f9..1a3773ca3 100644 --- a/packages/util-crypto/src/keccak/asU8a.ts +++ b/packages/util-crypto/src/keccak/asU8a.ts @@ -11,9 +11,13 @@ import { keccak256 } from 'js-sha3'; * @description * From either a `string` or a `Buffer` input, create the keccak and return the result as a `Uint8Array`. * @example - * import { keccakAsU8a } from '@polkadot/util-crypto'; + *
* - * keccakAsU8a('123') // => Uint8Array + * ```javascript + * import { keccakAsU8a } from '@polkadot/util-crypto'; + * + * keccakAsU8a('123'); // => Uint8Array + * ``` */ export default function keccakAsU8a (value: Buffer | Uint8Array | string): Uint8Array { return new Uint8Array( diff --git a/packages/util-crypto/src/mnemonic/generate.ts b/packages/util-crypto/src/mnemonic/generate.ts index 85166f216..3ff79fb79 100644 --- a/packages/util-crypto/src/mnemonic/generate.ts +++ b/packages/util-crypto/src/mnemonic/generate.ts @@ -4,6 +4,19 @@ import { generateMnemonic } from 'bip39'; +/** + * @name mnemonicGenerate + * @signature mnemonicGenerate (): string + * @summary Creates a valid mnemonic string using using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). + * @example + *
+ * + * ```javascript + * import { mnemonicGenerate } from '@polkadot/util-crypto'; + * + * const mnemonic = mnemonicGenerate(); // => string + * ``` + */ export default function mnemonicGenerate (): string { return generateMnemonic(); } diff --git a/packages/util-crypto/src/mnemonic/index.ts b/packages/util-crypto/src/mnemonic/index.ts index bdbfbbe6b..5b7bb0ed6 100644 --- a/packages/util-crypto/src/mnemonic/index.ts +++ b/packages/util-crypto/src/mnemonic/index.ts @@ -6,6 +6,9 @@ import mnemonicGenerate from './generate'; import mnemonicToSeed from './toSeed'; import mnemonicValidate from './validate'; +/** + * @summary Create valid mnemonic strings, validate them using BIP39, and convert them to valid seeds + */ export { mnemonicGenerate, mnemonicToSeed, diff --git a/packages/util-crypto/src/mnemonic/toSeed.ts b/packages/util-crypto/src/mnemonic/toSeed.ts index 19808afa5..0b1497eee 100644 --- a/packages/util-crypto/src/mnemonic/toSeed.ts +++ b/packages/util-crypto/src/mnemonic/toSeed.ts @@ -4,6 +4,24 @@ import toSecret from './toSecret'; +/** + * @name toSeed + * @signature toSeed (mnemonic: string): Uint8Array + * @summary Creates a valid seed from a mnemonic input + * @example + *
+ * + * ```javascript + * import { mnemonicGenerate, mnemonicToSeed, mnemonicValidate } from '@polkadot/util-crypto'; + * + * const mnemonic = mnemonicGenerate(); // => string + * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean + * + * if (isValidMnemonic) { + * console.log(`Seed generated from mnemonic: ${mnemonicToSeed(mnemonic)}`); => u8a + * } + * ``` + */ export default function toSeed (mnemonic: string): Uint8Array { return toSecret(mnemonic).subarray(0, 32); } diff --git a/packages/util-crypto/src/mnemonic/validate.ts b/packages/util-crypto/src/mnemonic/validate.ts index b0d85e97e..a97d49445 100644 --- a/packages/util-crypto/src/mnemonic/validate.ts +++ b/packages/util-crypto/src/mnemonic/validate.ts @@ -4,6 +4,20 @@ import { validateMnemonic } from 'bip39'; +/** + * @name mnemonicValidate + * @signature mnemonicValidate (mnemonic: string): boolean + * @summary Validates a mnemonic input using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). + * @example + *
+ * + * ```javascript + * import { mnemonicGenerate, mnemonicValidate } from '@polkadot/util-crypto'; + * + * const mnemonic = mnemonicGenerate(); // => string + * const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean + * ``` + */ export default function mnemonicValidate (mnemonic: string): boolean { return validateMnemonic(mnemonic); } diff --git a/packages/util-crypto/src/nacl/decrypt.ts b/packages/util-crypto/src/nacl/decrypt.ts index 9192b5bde..79f9f23c4 100644 --- a/packages/util-crypto/src/nacl/decrypt.ts +++ b/packages/util-crypto/src/nacl/decrypt.ts @@ -11,9 +11,13 @@ import nacl from 'tweetnacl'; * @description * Returns an decrypted message, using the `secret` and `nonce`. * @example - * import { naclDecrypt } from '@polkadot/util-crypto'; + *
* - * naclDecrypt([...], [...], [...]) // => [...] + * ```javascript + * import { naclDecrypt } from '@polkadot/util-crypto'; + * + * naclDecrypt([...], [...], [...]); // => [...] + * ``` */ export default function naclDecrypt (encrypted: Uint8Array, nonce: Uint8Array, secret: Uint8Array): Uint8Array | null { return nacl.secretbox.open(encrypted, nonce, secret); diff --git a/packages/util-crypto/src/nacl/encrypt.ts b/packages/util-crypto/src/nacl/encrypt.ts index f0c083d6d..4dbda98b2 100644 --- a/packages/util-crypto/src/nacl/encrypt.ts +++ b/packages/util-crypto/src/nacl/encrypt.ts @@ -18,9 +18,13 @@ type Encrypted = { * @description * Returns an encrypted message, using the `secretKey` and `nonce`. If the `nonce` was not supplied, a random value is generated. * @example - * import { naclEncrypt } from '@polkadot/util-crypto'; + *
* - * naclSign([...], [...]) // => [...] + * ```javascript + * import { naclEncrypt } from '@polkadot/util-crypto'; + * + * naclEncrypt([...], [...]); // => [...] + * ``` */ export default function naclEncrypt (message: Uint8Array, secret: Uint8Array, nonce: Uint8Array = randomAsU8a(24)): Encrypted { return { diff --git a/packages/util-crypto/src/nacl/keypair/fromRandom.ts b/packages/util-crypto/src/nacl/keypair/fromRandom.ts index 338d479b5..119ff308d 100644 --- a/packages/util-crypto/src/nacl/keypair/fromRandom.ts +++ b/packages/util-crypto/src/nacl/keypair/fromRandom.ts @@ -7,15 +7,19 @@ import { KeypairType } from '../../types'; import nacl from 'tweetnacl'; /** - * @name naclKeypair + * @name naclKeypairFromRandom * @signature naclKeypairFromRandom (): { secretKey: Uint8Array, publicKey: Uint8Array } * @summary Creates a new public/secret keypair. * @description * Returns a new generate object containing a `publicKey` & `secretKey`. * @example - * import { naclKeypair } from '@polkadot/util-crypto'; + *
* - * naclKeypair() // => { secretKey: [...], publicKey: [...] } + * ```javascript + * import { naclKeypairFromRandom } from '@polkadot/util-crypto'; + * + * naclKeypairFromRandom(); // => { secretKey: [...], publicKey: [...] } + * ``` */ export default function naclKeypairFromRandom (): KeypairType { return nacl.sign.keyPair(); diff --git a/packages/util-crypto/src/nacl/keypair/fromSecret.ts b/packages/util-crypto/src/nacl/keypair/fromSecret.ts index 5642eadd0..6c74258ed 100644 --- a/packages/util-crypto/src/nacl/keypair/fromSecret.ts +++ b/packages/util-crypto/src/nacl/keypair/fromSecret.ts @@ -13,9 +13,13 @@ import nacl from 'tweetnacl'; * @description * Returns a object containing a `publicKey` & `secretKey` generated from the supplied secret. * @example - * import { naclKeypairFromSecret } from '@polkadot/util-crypto'; + *
* - * naclKeypairFromSecret(...) // => { secretKey: [...], publicKey: [...] } + * ```javascript + * import { naclKeypairFromSecret } from '@polkadot/util-crypto'; + * + * naclKeypairFromSecret(...); // => { secretKey: [...], publicKey: [...] } + * ``` */ export default function naclKeypairFromSecret (secret: Uint8Array): KeypairType { return nacl.sign.keyPair.fromSecretKey(secret); diff --git a/packages/util-crypto/src/nacl/keypair/fromSeed.ts b/packages/util-crypto/src/nacl/keypair/fromSeed.ts index b02cf8101..8c1b33000 100644 --- a/packages/util-crypto/src/nacl/keypair/fromSeed.ts +++ b/packages/util-crypto/src/nacl/keypair/fromSeed.ts @@ -13,9 +13,13 @@ import nacl from 'tweetnacl'; * @description * Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed. * @example - * import { naclKeypairFromSeed } from '@polkadot/util-crypto'; + *
* - * naclKeypairFromSeed(...) // => { secretKey: [...], publicKey: [...] } + * ```javascript + * import { naclKeypairFromSeed } from '@polkadot/util-crypto'; + * + * naclKeypairFromSeed(...); // => { secretKey: [...], publicKey: [...] } + * ``` */ export default function naclKeypairFromSeed (seed: Uint8Array): KeypairType { return nacl.sign.keyPair.fromSeed(seed); diff --git a/packages/util-crypto/src/nacl/keypair/fromString.ts b/packages/util-crypto/src/nacl/keypair/fromString.ts index 4321cf7e9..7e73ef652 100644 --- a/packages/util-crypto/src/nacl/keypair/fromString.ts +++ b/packages/util-crypto/src/nacl/keypair/fromString.ts @@ -16,9 +16,13 @@ import fromSeed from './fromSeed'; * @description * Returns a object containing a `publicKey` & `secretKey` generated from the supplied string. The string is hashed and the value used as the input seed. * @example - * import { naclKeypairFromString } from '@polkadot/util-crypto'; + *
* - * naclKeypairFromString('test') // => { secretKey: [...], publicKey: [...] } + * ```javascript + * import { naclKeypairFromString } from '@polkadot/util-crypto'; + * + * naclKeypairFromString('test'); // => { secretKey: [...], publicKey: [...] } + * ``` */ export default function naclKeypairFromString (value: string): KeypairType { return fromSeed( diff --git a/packages/util-crypto/src/nacl/sign.ts b/packages/util-crypto/src/nacl/sign.ts index 20830bd7b..4e794625a 100644 --- a/packages/util-crypto/src/nacl/sign.ts +++ b/packages/util-crypto/src/nacl/sign.ts @@ -11,9 +11,13 @@ import nacl from 'tweetnacl'; * @description * Returns message signature of `message`, using the `secretKey`. * @example - * import { naclSign } from '@polkadot/util-crypto'; + *
* - * naclSign([...], [...]) // => [...] + * ```javascript + * import { naclSign } from '@polkadot/util-crypto'; + * + * naclSign([...], [...]); // => [...] + * ``` */ export default function naclSign (message: Uint8Array, secretKey: Uint8Array): Uint8Array { return nacl.sign.detached(message, secretKey); diff --git a/packages/util-crypto/src/nacl/verify.ts b/packages/util-crypto/src/nacl/verify.ts index f1a0c67d6..d6089bc4e 100644 --- a/packages/util-crypto/src/nacl/verify.ts +++ b/packages/util-crypto/src/nacl/verify.ts @@ -11,9 +11,13 @@ import nacl from 'tweetnacl'; * @description * Verifies the `signature` on `message` with the supplied `plublicKey`. Returns `true` on sucess, `false` otherwise. * @example - * import { naclVerify } from '@polkadot/util-crypto'; + *
* - * naclVerify([...], [...], [...]) // => true/false + * ```javascript + * import { naclVerify } from '@polkadot/util-crypto'; + * + * naclVerify([...], [...], [...]); // => true/false + * ``` */ export default function naclVerify (message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean { return nacl.sign.detached.verify(message, signature, publicKey); diff --git a/packages/util-crypto/src/random/asHex.spec.js b/packages/util-crypto/src/random/asHex.spec.js index 258b8da96..8a72d9f4d 100644 --- a/packages/util-crypto/src/random/asHex.spec.js +++ b/packages/util-crypto/src/random/asHex.spec.js @@ -29,7 +29,7 @@ describe('randomAsBuffer', () => { ).toHaveLength(32 * 2 + 2); }); - it('generates with the suuplied length', () => { + it('generates with the supplied length', () => { expect( randomAsHex(66) ).toHaveLength(66 * 2 + 2); diff --git a/packages/util-crypto/src/random/asHex.ts b/packages/util-crypto/src/random/asHex.ts index 587410105..92733ef58 100644 --- a/packages/util-crypto/src/random/asHex.ts +++ b/packages/util-crypto/src/random/asHex.ts @@ -13,9 +13,13 @@ import randomAsU8a from './asU8a'; * @description * Returns a hex string with the specified (optional) length filled with random bytes. * @example - * import { randomAsHex } from '@polkadot/util-crypto'; + *
* - * randomAsHex() // => 0x... + * ```javascript + * import { randomAsHex } from '@polkadot/util-crypto'; + * + * randomAsHex(); // => 0x... + * ``` */ export default function randomAsHex (length: number = 32): string { return u8aToHex( diff --git a/packages/util-crypto/src/random/asNumber.ts b/packages/util-crypto/src/random/asNumber.ts index b6238ed9e..05dec0614 100644 --- a/packages/util-crypto/src/random/asNumber.ts +++ b/packages/util-crypto/src/random/asNumber.ts @@ -16,9 +16,13 @@ const BN_53 = new BN(0b11111111111111111111111111111111111111111111111111111); * @description * Returns a random number generated from the secure bytes. * @example - * import { randomAsNumber } from '@polkadot/util-crypto'; + *
* - * randomAsNumber() // => + * ```javascript + * import { randomAsNumber } from '@polkadot/util-crypto'; + * + * randomAsNumber(); // => + * ``` */ export default function randomAsNumber (): number { return hexToBn( diff --git a/packages/util-crypto/src/random/asU8a.ts b/packages/util-crypto/src/random/asU8a.ts index 42185a208..83e93623a 100644 --- a/packages/util-crypto/src/random/asU8a.ts +++ b/packages/util-crypto/src/random/asU8a.ts @@ -11,9 +11,13 @@ import nacl from 'tweetnacl'; * @description * Returns a `Uint8Array` with the specified (optional) length filled with random bytes. * @example - * import { randomAsU8a } from '@polkadot/util-crypto'; + *
* - * randomAsU8s() // => Uint8Array([...]) + * ```javascript + * import { randomAsU8a } from '@polkadot/util-crypto'; + * + * randomAsU8a(); // => Uint8Array([...]) + * ``` */ export default function randomAsU8a (length: number = 32): Uint8Array { return nacl.randomBytes(length); diff --git a/packages/util-crypto/src/sha512/asU8a.ts b/packages/util-crypto/src/sha512/asU8a.ts index 2e4bbde3a..c16b51e18 100644 --- a/packages/util-crypto/src/sha512/asU8a.ts +++ b/packages/util-crypto/src/sha512/asU8a.ts @@ -11,9 +11,13 @@ import nacl from 'tweetnacl'; * @description * Returns a sha-512 `Uint8Array` from the supplied data. * @example - * import { sha512AsU8a } from '@polkadot/util-crypto'; + *
* - * sha512AsU8a(Uint8Array.from([...])) // => Uint8Array([...]) + * ```javascript + * import { sha512AsU8a } from '@polkadot/util-crypto'; + * + * sha512AsU8a(Uint8Array.from([...])); // => Uint8Array([...]) + * ``` */ export default function sha512AsU8a (data: Uint8Array): Uint8Array { return nacl.hash(data); diff --git a/packages/util-crypto/src/xxhash/asHex.ts b/packages/util-crypto/src/xxhash/asHex.ts index ec67bf757..d903dca00 100644 --- a/packages/util-crypto/src/xxhash/asHex.ts +++ b/packages/util-crypto/src/xxhash/asHex.ts @@ -8,14 +8,18 @@ import xxhashAsU8a from './asU8a'; /** * @name xxhashAsHex - * @signature xxhashAsHex (data: Buffer | Uint8Array | string, bitLenght: number = 64): string + * @signature xxhashAsHex (data: Buffer | Uint8Array | string, bitLength: number = 64): string * @summary Creates a xxhash64 hex from the input. * @description * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a hex string with the specified `bitLength`. * @example - * import { xxhashAsHex } from '@polkadot/util-crypto'; + *
* - * xxhashAsHex('abc') // => 0x44bc2cf5ad770999 + * ```javascript + * import { xxhashAsHex } from '@polkadot/util-crypto'; + * + * xxhashAsHex('abc'); // => 0x44bc2cf5ad770999 + * ``` */ export default function xxhashAsHex (data: Buffer | Uint8Array | string, bitLength: number = 64): string { return u8aToHex( diff --git a/packages/util-crypto/src/xxhash/asU8a.ts b/packages/util-crypto/src/xxhash/asU8a.ts index 07d295658..5c5f83aeb 100644 --- a/packages/util-crypto/src/xxhash/asU8a.ts +++ b/packages/util-crypto/src/xxhash/asU8a.ts @@ -6,14 +6,18 @@ import xxhash64AsBn from './xxhash64/asBn'; /** * @name xxhashAsU8a - * @signature xxhashAsU8a (data: Buffer | Uint8Array | string, bitLenght: number = 64): Uint8Array + * @signature xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength: number = 64): Uint8Array * @summary Creates a xxhash64 u8a from the input. * @description * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash64 and return the result as a `Uint8Array` with the specified `bitLength`. * @example - * import { xxhashAsU8a } from '@polkadot/util-crypto'; + *
* - * xxhashAsU8a('abc') // => 0x44bc2cf5ad770999 + * ```javascript + * import { xxhashAsU8a } from '@polkadot/util-crypto'; + * + * xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999 + * ``` */ export default function xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength: number = 64): Uint8Array { const byteLength = Math.ceil(bitLength / 8); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asBn.ts b/packages/util-crypto/src/xxhash/xxhash64/asBn.ts index a5f98f36c..6879215cc 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asBn.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asBn.ts @@ -13,9 +13,13 @@ import xxhash64AsRaw from './asRaw'; * @description * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a BN. * @example - * import { xxhash64AsNumber } from '@polkadot/util-crypto'; + *
* - * xxhash64AsBn('abcd', 0xabcd)) // => new BN(0xe29f70f8b8c96df7) + * ```javascript + * import { xxhash64AsNumber } from '@polkadot/util-crypto'; + * + * xxhash64AsBn('abcd', 0xabcd)); // => new BN(0xe29f70f8b8c96df7) + * ``` */ export default function xxhash64AsBn (data: Buffer | Uint8Array | string, seed: number): BN { return new BN( diff --git a/packages/util-crypto/src/xxhash/xxhash64/asHex.ts b/packages/util-crypto/src/xxhash/xxhash64/asHex.ts index b721ef00e..e1586a466 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asHex.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asHex.ts @@ -13,9 +13,13 @@ import xxhash64AsRaw from './asRaw'; * @description * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a hex string. * @example - * import { xxhash64AsHex } from '@polkadot/util-crypto'; + *
* - * xxhash64AsHex('abcd', 0xabcd)) // => 0xe29f70f8b8c96df7 + * ```javascript + * import { xxhash64AsHex } from '@polkadot/util-crypto'; + * + * xxhash64AsHex('abcd', 0xabcd)); // => 0xe29f70f8b8c96df7 + * ``` */ export default function xxhash64AsHex (data: Buffer | Uint8Array | string, seed: number): string { return hexAddPrefix( diff --git a/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts b/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts index bd2d2022a..53788006d 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asRaw.ts @@ -11,9 +11,13 @@ import xxhash64AsValue from './asValue'; * @description * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a non-prefixed hex string. * @example - * import { xxhash64AsRaw } from '@polkadot/util-crypto'; + *
* - * xxhash64AsRaw('abcd', 0xabcd)) // => e29f70f8b8c96df7 + * ```javascript + * import { xxhash64AsRaw } from '@polkadot/util-crypto'; + * + * xxhash64AsRaw('abcd', 0xabcd)); // => e29f70f8b8c96df7 + * ``` */ export default function xxhash64AsRaw (data: Buffer | Uint8Array | string, seed: number): string { return xxhash64AsValue(data, seed).toString(16); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts b/packages/util-crypto/src/xxhash/xxhash64/asValue.ts index c4ae3f7dc..5a88f42c9 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asValue.ts @@ -5,6 +5,21 @@ import xxhashjs from 'xxhashjs'; import { isBuffer, isString, u8aToBuffer } from '@polkadot/util/index'; +/** + * @name xxhash64AsValue + * @signature xxhash64AsValue (data: Buffer | Uint8Array | string, seed: number): number + * @summary Creates a hex number from the input. + * @description + * From either a `string`, `Uint8Array` or a `Buffer` input, create the xxhash and return the result as a hex number + * @example + *
+ * + * ```javascript + * import { xxhash64AsValue } from '@polkadot/util-crypto'; + * + * xxhash64AsValue('abcd', 0xabcd)); // => e29f70f8b8c96df7 + * ``` + */ export default function xxhash64AsValue (data: Buffer | Uint8Array | string, seed: number): number { if (isBuffer(data) || isString(data)) { // @ts-ignore Buffer is ArrayBuffer underlying diff --git a/packages/util-rlp/README.md b/packages/util-rlp/README.md index 797b67dbd..c48f6d98d 100644 --- a/packages/util-rlp/README.md +++ b/packages/util-rlp/README.md @@ -1,17 +1,41 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![mpl-2](https://img.shields.io/badge/license-MPL-lightgrey.svg?style=flat-square) -[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/util-rlp.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/util-rlp) -[![travis](https://img.shields.io/travis/polkadot-js/common.svg?style=flat-square)](https://travis-ci.org/polkadot-js/common) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/common.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/common?branch=master) -[![dependency](https://david-dm.org/polkadot-js/common.svg?style=flat-square&path=packages/util)](https://david-dm.org/polkadot-js/common?path=packages/util-rlp) -[![devDependency](https://david-dm.org/polkadot-js/common/dev-status.svg?style=flat-square&path=packages/util-rlp)](https://david-dm.org/polkadot-js/common?path=packages/util-rlp#info=devDependencies) - # @polkadot/util-rlp -Encoding and decoding for [Ethereum RLP structures](https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP). This is port of the original [EthereumJS RLP](https://github.com/ethereumjs/rlp) to cater for `Uint8Array` outputs (instead of `Buffer`) in addition to typings. +Utility methods for encoding and decoding [Ethereum RLP structures](https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP). This is port adapted from the original [EthereumJS RLP](https://github.com/ethereumjs/rlp/blob/0ce09db81fc303fcee593f7cc094ba44015f9b92/index.js) implementation to cater for `Uint8Array` outputs (instead of `Buffer`) in addition to typings. -## Available Utilities +## Usage -For a list of currently exposed methods, see the [library documentation](docs/README.md). +Installation - + +``` +yarn add @polkadot/util-rlp +``` + +Functions can be imported as follows: + +```js +import { decode } from '@polkadot/util-rlp'; +import { encode } from '@polkadot/util-rlp'; +``` + +## Documentation and Available Utilities + +No methods are exposed in the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/util-rlp/) because RLP will not be included in PoC-3 of Polkadot. + +However, the key functions that are available include: + +- util-rlp + - Functions + - Decoder + - decode + - decodeListLong + - decodeListShort + - decodeNumber + - decodeSingle + - decodeString + - safeParseInt + - Encoder + - encode + - encodeArray + - encodeLength + - encodeU8a + - toU8a \ No newline at end of file diff --git a/packages/util-rlp/docs/README.md b/packages/util-rlp/docs/README.md deleted file mode 100644 index 367df6d59..000000000 --- a/packages/util-rlp/docs/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Available interfaces - -Utility methods to encode and decode [Ethereum RLP](https://github.com/ethereum/wiki/wiki/RLP). Adapted from the [EthereumJS implementation](https://github.com/ethereumjs/rlp/blob/0ce09db81fc303fcee593f7cc094ba44015f9b92/index.js) - - -# Available methods - -## decode - -Decodes the input RLP. - -```js -decoder (input?: Uint8Array): Uint8Array | Array<*> -``` - - -From an input, decod the RLP and return the result as a `Uint8Array` or `Array`. - -```js -import { decode } from '@polkadot/util-rlp'; - -encode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])) // => 'dog' as Uint8Array -``` - -## encode - -Encodes the input value into RLP. - -```js -encode (input: any): Uint8Array -``` - - -From an input, calculate the RLP and return the result as a `Uint8Array`. - -```js -import { encode } from '@polkadot/util-rlp'; - -encode('dog') // => [0x83, 0x64, 0x6f, 0x67] -``` \ No newline at end of file diff --git a/packages/util-rlp/src/decode.ts b/packages/util-rlp/src/decode.ts index c11ba2411..6f2fad61b 100644 --- a/packages/util-rlp/src/decode.ts +++ b/packages/util-rlp/src/decode.ts @@ -4,15 +4,4 @@ import decoder from './decoder'; -/** - * @name decode - * @signature decoder (input?: Uint8Array): Uint8Array | Array<*> - * @summary Decodes the input RLP. - * @description - * From an input, decod the RLP and return the result as a `Uint8Array` or `Array`. - * @example - * import { decode } from '@polkadot/util-rlp'; - * - * encode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])) // => 'dog' as Uint8Array - */ export default decoder; diff --git a/packages/util-rlp/src/decoder/index.ts b/packages/util-rlp/src/decoder/index.ts index 3fa19af77..57916c11d 100644 --- a/packages/util-rlp/src/decoder/index.ts +++ b/packages/util-rlp/src/decoder/index.ts @@ -6,6 +6,21 @@ import { assert, u8aToHex } from '@polkadot/util/index'; import internalDecode from './decode'; +/** + * @name decoder + * @signature decoder (input?: Uint8Array): Uint8Array | Array<*> + * @summary Decodes the input RLP. + * @description + * From an input, decode the RLP and return the result as a `Uint8Array` or `Array`. + * @example + *
+ * + * ```javascript + * import { decode } from '@polkadot/util-rlp'; + * + * decode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])); // => 'dog' as Uint8Array + * ``` + */ export default function decoder (input?: Uint8Array): Uint8Array | Array { try { if (!input || input.length === 0) { diff --git a/packages/util-rlp/src/encode.ts b/packages/util-rlp/src/encode.ts index 8d9de02f9..853ab7cca 100644 --- a/packages/util-rlp/src/encode.ts +++ b/packages/util-rlp/src/encode.ts @@ -4,15 +4,4 @@ import encoder from './encoder'; -/** - * @name encode - * @signature encode (input: any): Uint8Array - * @summary Encodes the input value into RLP. - * @description - * From an input, calculate the RLP and return the result as a `Uint8Array`. - * @example - * import { encode } from '@polkadot/util-rlp'; - * - * encode('dog') // => [0x83, 0x64, 0x6f, 0x67] - */ export default encoder; diff --git a/packages/util-rlp/src/encoder/index.ts b/packages/util-rlp/src/encoder/index.ts index c1173274a..5aaf7d797 100644 --- a/packages/util-rlp/src/encoder/index.ts +++ b/packages/util-rlp/src/encoder/index.ts @@ -6,6 +6,21 @@ import encodeArray from './array'; import toU8a from './toU8a'; import encodeU8a from './u8a'; +/** + * @name encoder + * @signature encoder (input: any): Uint8Array + * @summary Encodes the input value into RLP. + * @description + * From an input, calculate the RLP and return the result as a `Uint8Array`. + * @example + *
+ * + * ```javascript + * import { encode } from '@polkadot/util-rlp'; + * + * encode('dog'); // => [0x83, 0x64, 0x6f, 0x67] + * ``` + */ export default function encoder (input: any): Uint8Array { if (input instanceof Array) { return encodeArray(encoder, input); diff --git a/packages/util/README.md b/packages/util/README.md index 1f0be8b81..e32fad057 100644 --- a/packages/util/README.md +++ b/packages/util/README.md @@ -1,13 +1,3 @@ -[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org) -![isc](https://img.shields.io/badge/license-ISC-lightgrey.svg?style=flat-square) -[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard) -[![npm](https://img.shields.io/npm/v/@polkadot/util.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/util) -[![travis](https://img.shields.io/travis/polkadot-js/common.svg?style=flat-square)](https://travis-ci.org/polkadot-js/common) -[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common/maintainability) -[![coverage](https://img.shields.io/coveralls/polkadot-js/common.svg?style=flat-square)](https://coveralls.io/github/polkadot-js/common?branch=master) -[![dependency](https://david-dm.org/polkadot-js/common.svg?style=flat-square&path=packages/util)](https://david-dm.org/polkadot-js/common?path=packages/util) -[![devDependency](https://david-dm.org/polkadot-js/common/dev-status.svg?style=flat-square&path=packages/util)](https://david-dm.org/polkadot-js/common?path=packages/util#info=devDependencies) - # @polkadot/util Various useful utility functions that are used across all projects in the [@polkadot](https://polkadot.js.org) namespace. It provides utility functions with additional safety checks, allowing not only for consistent coding, but also reducing the general boilerplate. @@ -17,7 +7,7 @@ Various useful utility functions that are used across all projects in the [@polk Installation - ``` -npm install --save @polkadot/util +yarn add @polkadot/util ``` Functions can be imported directly from the package, e.g. @@ -26,6 +16,36 @@ Functions can be imported directly from the package, e.g. import { isHex } from '@polkadot/util'; ``` -## Available Utilities +## Documentation and Available Utilities -For a list of currently exposed methods, see the [library documentation](docs/README.md). +Below is a list of currently exposed methods published at the [Polkadot-JS Common Documentation Portal](https://polkadot.js.org/common/util/). + +Utility methods for this package are split into groups, some of which are included in the list below: + +- [util](https://polkadot.js.org/common/util/README.md) + - Classes + - [Error](https://polkadot.js.org/common/util/classes/_ext_error_.exterror.md) + - Functions + - [arrayFilter](https://polkadot.js.org/common/util/modules/_array_filter_.md) + - [assert](https://polkadot.js.org/common/util/modules/_assert_.md) + - [logger](https://polkadot.js.org/common/util/modules/_logger_.md) + - [promisify](https://polkadot.js.org/common/util/modules/_promisify_.md) + - [syncify](https://polkadot.js.org/common/util/modules/_syncify_.md) + +Below is information about some of the available methods: + +### Assert + +* Checks for a valid test, if not `ExtError` is thrown + +### Logger + +* Creates a consistent log interface for messages that has `.log`, `.error`, `.warn` and `.debug` (controlled with environment `DEBUG=typeA,typeB`) methods. + +### Promisify + +* Wraps a supplied asynchronous callback function into a Promise, passing supplied parameters. When `error` is set, the Promise is rejected, else the Promise resolves with the `result` value. + +### Syncify + +* This is currently for Node environments only. diff --git a/packages/util/src/array/filter.ts b/packages/util/src/array/filter.ts index 99482801b..011465106 100644 --- a/packages/util/src/array/filter.ts +++ b/packages/util/src/array/filter.ts @@ -12,10 +12,14 @@ import isUndefined from '../is/undefined'; * @description * Returns a new array with all `undefined` values removed. Optionally, when `allowNulls = false`, it removes the `null` values as well * @example - * import { arrayFilter } from '@polkadot/util'; + *
* - * arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, ''] - * arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, ''] + * ```javascript + * import { arrayFilter } from '@polkadot/util'; + * + * arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, ''] + * arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, ''] + * ``` */ export default function arrayFilter (array: Array, allowNulls: boolean = true): Array { return array.filter((value) => { diff --git a/packages/util/src/assert.ts b/packages/util/src/assert.ts index c4acc7bdc..c2edac591 100644 --- a/packages/util/src/assert.ts +++ b/packages/util/src/assert.ts @@ -14,11 +14,15 @@ type MessageFn = () => string; * @description * Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an ExtError with the supplied `message` and an optional `code` and `data`. When `test` passes, `true` is returned. * @example - * import assert from '@polkadot/util/assert'; + *
* - * assert(true, 'True should be true'); // true returned - * assert(false, 'False should not be true'); // ExtError thrown - * assert(false, () => 'message'); // ExtError with 'message' + * ```javascript + * const { assert } from '@polkadot/util'; + * + * assert(true, 'True should be true'); // true returned + * assert(false, 'False should not be true'); // ExtError thrown + * assert(false, () => 'message'); // ExtError with 'message' + * ``` */ export default function assert (test: any, message: string | MessageFn, code: number = ExtError.CODES.ASSERT, data?: any): boolean { if (test) { diff --git a/packages/util/src/bn/toBn.ts b/packages/util/src/bn/toBn.ts index 0c20134c5..168bdf53a 100644 --- a/packages/util/src/bn/toBn.ts +++ b/packages/util/src/bn/toBn.ts @@ -11,11 +11,15 @@ import BN from 'bn.js'; * @description * `null` inputs returns a `0x0` result, BN values returns the value, numnbers returns a BN representation. * @example - * import BN from 'bn.js'; - * import { bnToBn } from '@polkadot/util'; + *
* - * bnToBn(0x1234); // => BN(0x1234) - * bnToBn(new BN(0x1234)); // => BN(0x1234) + * ```javascript + * import BN from 'bn.js'; + * import { bnToBn } from '@polkadot/util'; + * + * bnToBn(0x1234); // => BN(0x1234) + * bnToBn(new BN(0x1234)); // => BN(0x1234) + * ``` */ export default function bnToBn (value?: BN | number): BN { if (!value) { diff --git a/packages/util/src/bn/toHex.ts b/packages/util/src/bn/toHex.ts index f9c444350..62d09fadd 100644 --- a/packages/util/src/bn/toHex.ts +++ b/packages/util/src/bn/toHex.ts @@ -16,10 +16,14 @@ const ZERO_STR = '0x00'; * @description * `null` inputs returns a `0x` result, BN values return the actual value as a `0x` prefixed hex value. Anything that is not a BN object throws an error. With `bitLength` set, it fixes the number to the specified length. * @example - * import BN from 'bn.js'; - * import { bnToHex } from '@polkadot/util'; + *
* - * bnToHex(new BN(0x123456)); // => '0x123456' + * ```javascript + * import BN from 'bn.js'; + * import { bnToHex } from '@polkadot/util'; + * + * bnToHex(new BN(0x123456)); // => '0x123456' + * ``` */ export default function bnToHex (value?: BN | number, bitLength: number = -1): string { if (!value) { diff --git a/packages/util/src/bn/toU8a.ts b/packages/util/src/bn/toU8a.ts index 524b98e97..9bbb6c83c 100644 --- a/packages/util/src/bn/toU8a.ts +++ b/packages/util/src/bn/toU8a.ts @@ -15,9 +15,13 @@ import bnToHex from './toHex'; * @description * `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set. * @example - * import { bnToU8a } from '@polkadot/util'; + *
* - * bnToU8a(new BN(0x1234)); // => [0x12, 0x34] + * ```javascript + * import { bnToU8a } from '@polkadot/util'; + * + * bnToU8a(new BN(0x1234)); // => [0x12, 0x34] + * ``` */ export default function bnToU8a (value: BN | number, bitLength: number, isLe: boolean): Uint8Array { const byteLength = Math.ceil(bitLength / 8); diff --git a/packages/util/src/buffer/toU8a.ts b/packages/util/src/buffer/toU8a.ts index 0a76a74e5..0d4da6575 100644 --- a/packages/util/src/buffer/toU8a.ts +++ b/packages/util/src/buffer/toU8a.ts @@ -9,9 +9,13 @@ * @description * `null` inputs returns an empty result, `Buffer` values return the actual value as a `Uint8Array`. Anything that is not a `Buffer` object throws an error. * @example - * import { bufferToU8a } from '@polkadot/util'; + *
* - * bufferToU8a(Buffer.from([1, 2, 3])); + * ```javascript + * import { bufferToU8a } from '@polkadot/util'; + * + * bufferToU8a(Buffer.from([1, 2, 3])); + * ``` */ export default function bufferToU8a (buffer?: Buffer | number[]): Uint8Array { if (!buffer) { diff --git a/packages/util/src/ext/error.ts b/packages/util/src/ext/error.ts index 06d8b9ebf..3aca62c50 100644 --- a/packages/util/src/ext/error.ts +++ b/packages/util/src/ext/error.ts @@ -23,9 +23,13 @@ function extend (that: any, name: string, value: any): void { * @description * The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object. * @example - * const { ExtError } from '@polkadot/util'); + *
* - * throw new ExtError('some message', ExtError.CODES.METHOD_NOT_FOUND); // => error.code = -32601 + * ```javascript + * const { ExtError } from '@polkadot/util'); + * + * throw new ExtError('some message', ExtError.CODES.METHOD_NOT_FOUND); // => error.code = -32601 + * ``` */ export default class ExtError extends Error implements ExtErrorInterface { // @ts-ignore we are assigning it via extend diff --git a/packages/util/src/hex/addPrefix.ts b/packages/util/src/hex/addPrefix.ts index dd689b976..7901e6518 100644 --- a/packages/util/src/hex/addPrefix.ts +++ b/packages/util/src/hex/addPrefix.ts @@ -11,9 +11,13 @@ import hasPrefix from './hasPrefix'; * @description * Returns a `0x` prefixed string from the input value. If the input is already prefixed, it is returned unchanged. * @example - * import { hexAddPrefix } from '@polkadot/util'; + *
* - * console.log('With prefix', hexAddPrefix('0a0b12')) // => 0x0a0b12 + * ```javascript + * import { hexAddPrefix } from '@polkadot/util'; + * + * console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12 + * ``` */ export default function hexAddPrefix (value: string | null | undefined): string { if (value && hasPrefix(value)) { diff --git a/packages/util/src/hex/fixLength.ts b/packages/util/src/hex/fixLength.ts index de93496d5..8249f0927 100644 --- a/packages/util/src/hex/fixLength.ts +++ b/packages/util/src/hex/fixLength.ts @@ -12,11 +12,15 @@ import hexStripPrefix from './stripPrefix'; * @description * Returns a `0x` prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`. * @example - * import { hexFixLength } from '@polkadot/util'; + *
* - * console.log('fixed', hexFixLength('0x12', 16)) // => 0x12 - * console.log('fixed', hexFixLength('0x12', 16, true)) // => 0x0012 - * console.log('fixed', hexFixLength('0x0012', 8)) // => 0x12 + * ```javascript + * import { hexFixLength } from '@polkadot/util'; + * + * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12 + * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012 + * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12 + * ``` */ export default function hexFixLength (value: string, bitLength: number = -1, withPadding: boolean = false): string { const strLength = Math.ceil(bitLength / 4); diff --git a/packages/util/src/hex/hasPrefix.ts b/packages/util/src/hex/hasPrefix.ts index 9a663d077..6a429e890 100644 --- a/packages/util/src/hex/hasPrefix.ts +++ b/packages/util/src/hex/hasPrefix.ts @@ -11,9 +11,13 @@ import isHex from '../is/hex'; * @description * Checks for a valid hex input value and if the start matched `0x` * @example - * import { hexHasPrefix } from '@polkadot/util'; + *
* - * console.log('has prefix', hexHasPrefix('0x1234')); // => true + * ```javascript + * import { hexHasPrefix } from '@polkadot/util'; + * + * console.log('has prefix', hexHasPrefix('0x1234')); // => true + * ``` */ export default function hexHasPrefix (value: string | null | undefined): boolean { return !!(value && isHex(value, -1, true) && value.substr(0, 2) === '0x'); diff --git a/packages/util/src/hex/stripPrefix.ts b/packages/util/src/hex/stripPrefix.ts index 940f354f8..a3f9b33ad 100644 --- a/packages/util/src/hex/stripPrefix.ts +++ b/packages/util/src/hex/stripPrefix.ts @@ -13,9 +13,13 @@ const UNPREFIX_HEX_REGEX = /^[a-fA-F0-9]+$/; * @description * Tests for the existence of a `0x` prefix, and returns the value without the prefix. Un-prefixed values are returned as-is. * @example - * import { hexStripPrefix } from '@polkadot/util'; + *
* - * console.log('stripped', hexStripPrefix('0x1234')); // => 1234 + * ```javascript + * import { hexStripPrefix } from '@polkadot/util'; + * + * console.log('stripped', hexStripPrefix('0x1234')); // => 1234 + * ``` */ export default function hexStripPrefix (value: string | null | undefined): string { if (!value) { diff --git a/packages/util/src/hex/toBn.ts b/packages/util/src/hex/toBn.ts index d00a3bd89..92de85bf9 100644 --- a/packages/util/src/hex/toBn.ts +++ b/packages/util/src/hex/toBn.ts @@ -19,9 +19,13 @@ function reverse (value: string): string { * @description * `null` inputs returns a `BN(0)` result. Hex input values return the actual value converted to a BN. Anything that is not a hex string (including the `0x` prefix) throws an error. * @example - * import { hexToBn } from '@polkadot/util'; + *
* - * hexToBn('0x123480001f'); // => BN(0x123480001f) + * ```javascript + * import { hexToBn } from '@polkadot/util'; + * + * hexToBn('0x123480001f'); // => BN(0x123480001f) + * ``` */ export default function hexToBn (_value?: string, isLe: boolean = false): BN { if (!_value) { diff --git a/packages/util/src/hex/toNumber.ts b/packages/util/src/hex/toNumber.ts index 58475876a..5ce53eb58 100644 --- a/packages/util/src/hex/toNumber.ts +++ b/packages/util/src/hex/toNumber.ts @@ -11,9 +11,13 @@ import hexToBn from './toBn'; * @description * `null` inputs returns an NaN result, `hex` values return the actual value as a `Number`. * @example - * import { hexToNumber } from '@polkadot/util'; + *
* - * hexToNumber('0x1234'); // => 0x1234 + * ```javascript + * import { hexToNumber } from '@polkadot/util'; + * + * hexToNumber('0x1234'); // => 0x1234 + * ``` */ export default function hexToNumber (value?: string): number { if (!value) { diff --git a/packages/util/src/hex/toU8a.ts b/packages/util/src/hex/toU8a.ts index 096d00102..6e8b599b8 100644 --- a/packages/util/src/hex/toU8a.ts +++ b/packages/util/src/hex/toU8a.ts @@ -13,10 +13,14 @@ import hexStripPrefix from './stripPrefix'; * @description * `null` inputs returns an empty `Uint8Array` result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the `0x` prefix) throws an error. * @example - * import { hexToU8a } from '@polkadot/util'; + *
* - * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f]) - * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f]) + * ```javascript + * import { hexToU8a } from '@polkadot/util'; + * + * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f]) + * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f]) + * ``` */ export default function hexToU8a (_value?: string | null, bitLength: number = -1): Uint8Array { if (!_value) { diff --git a/packages/util/src/is/bn.ts b/packages/util/src/is/bn.ts index f89f19e7c..a29b2da5f 100644 --- a/packages/util/src/is/bn.ts +++ b/packages/util/src/is/bn.ts @@ -11,10 +11,14 @@ import BN from 'bn.js'; * @description * Checks to see if the input object is an instance of `BN` (bn.js). * @example - * import BN from 'bn.js'; - * import { isBn } from '@polkadot/util'; + *
* - * console.log('isBn', isBn(new BN(1))); // => true + * ```javascript + * import BN from 'bn.js'; + * import { isBn } from '@polkadot/util'; + * + * console.log('isBn', isBn(new BN(1))); // => true + * ``` */ export default function isBn (value: any): value is BN { return BN.isBN(value); diff --git a/packages/util/src/is/boolean.ts b/packages/util/src/is/boolean.ts index d178f97f6..136c287e2 100644 --- a/packages/util/src/is/boolean.ts +++ b/packages/util/src/is/boolean.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is a JavaScript boolean. * @example - * import { isBoolean } from '@polkadot/util'; + *
* - * isBoolean(false); // => true + * ```javascript + * import { isBoolean } from '@polkadot/util'; + * + * isBoolean(false); // => true + * ``` */ export default function isBoolean (value: any): value is boolean { return typeof value === 'boolean'; diff --git a/packages/util/src/is/buffer.ts b/packages/util/src/is/buffer.ts index fda360900..88db545f7 100644 --- a/packages/util/src/is/buffer.ts +++ b/packages/util/src/is/buffer.ts @@ -11,9 +11,13 @@ import isInstanceOf from './instanceOf'; * @description * Checks to see if the input object is an instance of `Buffer`. * @example - * import { isBuffer } from '@polkadot/util'; + *
* - * console.log('isBuffer', isBuffer(Buffer.from([]))); // => true + * ```javascript + * import { isBuffer } from '@polkadot/util'; + * + * console.log('isBuffer', isBuffer(Buffer.from([]))); // => true + * ``` */ export default function isBuffer (value: any): value is Buffer { return isInstanceOf(value, Buffer); diff --git a/packages/util/src/is/error.ts b/packages/util/src/is/error.ts index 75c82d740..88b732fa9 100644 --- a/packages/util/src/is/error.ts +++ b/packages/util/src/is/error.ts @@ -11,9 +11,13 @@ import isInstanceOf from './instanceOf'; * @description * Checks to see if the input object is an instance of `Error`. * @example - * import { isError } from '@polkadot/util'; + *
* - * console.log('isError', isError(new Error('message'))); // => true + * ```javascript + * import { isError } from '@polkadot/util'; + * + * console.log('isError', isError(new Error('message'))); // => true + * ``` */ export default function isError (value: any): value is Error { return isInstanceOf(value, Error); diff --git a/packages/util/src/is/function.ts b/packages/util/src/is/function.ts index e4fa68b62..1e1525637 100644 --- a/packages/util/src/is/function.ts +++ b/packages/util/src/is/function.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is a JavaScript function. * @example - * import { isFunction } from '@polkadot/util'; + *
* - * isFunction(() => false); // => true + * ```javascript + * import { isFunction } from '@polkadot/util'; + * + * isFunction(() => false); // => true + * ``` */ export default function isFunction (value: any): value is Function { return typeof value === 'function'; diff --git a/packages/util/src/is/hex.ts b/packages/util/src/is/hex.ts index 6bd65dfd3..84f8b3bc2 100644 --- a/packages/util/src/is/hex.ts +++ b/packages/util/src/is/hex.ts @@ -13,10 +13,14 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/; * @description * Checks to see if the input value is a `0x` prefixed hex string. Optionally (`bitLength` !== -1) checks to see if the bitLength is correct. * @example - * import { isHex } from '@polkadot/util'; + *
* - * isHex('0x1234'); // => true - * isHex('0x1234', 8); // => false + * ```javascript + * import { isHex } from '@polkadot/util'; + * + * isHex('0x1234'); // => true + * isHex('0x1234', 8); // => false + * ``` */ export default function isHex (_value: any, bitLength: number = -1, ignoreLength: boolean = false): boolean { const value = (_value as string); diff --git a/packages/util/src/is/instanceOf.ts b/packages/util/src/is/instanceOf.ts index f76119281..775f36ca5 100644 --- a/packages/util/src/is/instanceOf.ts +++ b/packages/util/src/is/instanceOf.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is an instance of the test class. * @example - * import { isInstanceOf } from '@polkadot/util'; + *
* - * console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true + * ```javascript + * import { isInstanceOf } from '@polkadot/util'; + * + * console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true + * ``` */ export default function isInstanceOf (value: any, clazz: any): boolean { return value instanceof clazz; diff --git a/packages/util/src/is/ip.ts b/packages/util/src/is/ip.ts index d84947440..0894b64fd 100644 --- a/packages/util/src/is/ip.ts +++ b/packages/util/src/is/ip.ts @@ -13,12 +13,16 @@ type IpTypes = 'v4' | 'v6'; * @description * Checks to see if the value is a valid IP address. Optionally check for either v4/v6 * @example - * import { isIp } from '@polkadot/util'; + *
* - * isIp('192.168.0.1')); // => true - * isIp('1:2:3:4:5:6:7:8'); // => true - * isIp('192.168.0.1', 'v6')); // => false - * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false + * ```javascript + * import { isIp } from '@polkadot/util'; + * + * isIp('192.168.0.1')); // => true + * isIp('1:2:3:4:5:6:7:8'); // => true + * isIp('192.168.0.1', 'v6')); // => false + * isIp('1:2:3:4:5:6:7:8', 'v4'); // => false + * ``` */ export default function isIp (value: string, type?: IpTypes): boolean { // FIXME @types/ip-regex defintions are outdated diff --git a/packages/util/src/is/null.ts b/packages/util/src/is/null.ts index e18425fcd..ea400a8f1 100644 --- a/packages/util/src/is/null.ts +++ b/packages/util/src/is/null.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is `null`. * @example - * import { isNull } from '@polkadot/util'; + *
* - * console.log('isNull', isNull(null)); // => true + * ```javascript + * import { isNull } from '@polkadot/util'; + * + * console.log('isNull', isNull(null)); // => true + * ``` */ export default function isNull (value: any): value is null { return value === null; diff --git a/packages/util/src/is/number.ts b/packages/util/src/is/number.ts index b4900b1ee..bc31415b1 100644 --- a/packages/util/src/is/number.ts +++ b/packages/util/src/is/number.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is a valid number. * @example - * import { isNumber } from '@polkadot/util'; + *
* - * console.log('isNumber', isNumber(1234)); // => true + * ```javascript + * import { isNumber } from '@polkadot/util'; + * + * console.log('isNumber', isNumber(1234)); // => true + * ``` */ export default function isNumber (value: any): value is number { return typeof value === 'number'; diff --git a/packages/util/src/is/object.ts b/packages/util/src/is/object.ts index 223fcb001..747099421 100644 --- a/packages/util/src/is/object.ts +++ b/packages/util/src/is/object.ts @@ -13,10 +13,14 @@ type ObjectIndexed = { * @description * Checks to see if the input value is a JavaScript object. * @example - * import { isObject } from '@polkadot/util'; + *
* - * isObject({}); // => true - * isObject('something'); // => false + * ```javascript + * import { isObject } from '@polkadot/util'; + * + * isObject({}); // => true + * isObject('something'); // => false + * ``` */ export default function isObject (value: any): value is ObjectIndexed { return typeof value === 'object'; diff --git a/packages/util/src/is/observable.ts b/packages/util/src/is/observable.ts index 3ac8c9834..9b4f9e870 100644 --- a/packages/util/src/is/observable.ts +++ b/packages/util/src/is/observable.ts @@ -16,9 +16,13 @@ type Observable = { * @description * Checks to see if the input object is an instance of `BN` (bn.js). * @example - * import { isObservable } from '@polkadot/util'; + *
* - * console.log('isObservable', isObservable(...)); + * ```javascript + * import { isObservable } from '@polkadot/util'; + * + * console.log('isObservable', isObservable(...)); + * ``` */ export default function isObservable (value: any): value is Observable { return isObject(value) && isFunction((value as Observable).next); diff --git a/packages/util/src/is/string.ts b/packages/util/src/is/string.ts index 51dff83d2..17868cbef 100644 --- a/packages/util/src/is/string.ts +++ b/packages/util/src/is/string.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is a JavaScript string. * @example - * import { isString } from '@polkadot/util'; + *
* - * console.log('isString', isString('test')); // => true + * ```javascript + * import { isString } from '@polkadot/util'; + * + * console.log('isString', isString('test')); // => true + * ``` */ export default function isString (value: any): value is string { return typeof value === 'string'; diff --git a/packages/util/src/is/u8a.ts b/packages/util/src/is/u8a.ts index afa6c89bc..965edf2ff 100644 --- a/packages/util/src/is/u8a.ts +++ b/packages/util/src/is/u8a.ts @@ -11,9 +11,13 @@ import isInstanceOf from './instanceOf'; * @description * Checks to see if the input object is an instance of `Uint8Array`. * @example - * import { isUint8Array } from '@polkadot/util'; + *
* - * console.log('isU8a', isU8a([])); // => false + * ```javascript + * import { isUint8Array } from '@polkadot/util'; + * + * console.log('isU8a', isU8a([])); // => false + * ``` */ export default function isU8a (value: any): value is Uint8Array { return isInstanceOf(value, Uint8Array); diff --git a/packages/util/src/is/undefined.ts b/packages/util/src/is/undefined.ts index 0aa7e3c7b..1e007156e 100644 --- a/packages/util/src/is/undefined.ts +++ b/packages/util/src/is/undefined.ts @@ -9,9 +9,13 @@ * @description * Checks to see if the input value is `undefined`. * @example - * import { isUndefined } from '@polkadot/util'; + *
* - * console.log('isUndefined', isUndefined(void(0))); // => true + * ```javascript + * import { isUndefined } from '@polkadot/util'; + * + * console.log('isUndefined', isUndefined(void(0))); // => true + * ``` */ export default function isUndefined (value: any): value is undefined { return typeof value === 'undefined'; diff --git a/packages/util/src/logger.ts b/packages/util/src/logger.ts index d85294409..db1ddb229 100644 --- a/packages/util/src/logger.ts +++ b/packages/util/src/logger.ts @@ -92,11 +92,15 @@ function apply (log: LogType, type: string, values: Logger$Data): void { * @signature logger (type: string): Logger * @summary Creates a consistent log interface for messages * @description - * Returns a `Logger` that has `.log`, `.error`, `.warn` and `.debug` (constrolled with environment `DEBUG=typeA,typeB`) methods. Logging is done with a consistent prefix (type of logger, date) followed by the actual message using the underlying console. + * Returns a `Logger` that has `.log`, `.error`, `.warn` and `.debug` (controlled with environment `DEBUG=typeA,typeB`) methods. Logging is done with a consistent prefix (type of logger, date) followed by the actual message using the underlying console. * @example - * const l from '@polkadot/util/logger')('test'); + *
* - * l.log('blah'); // TEST: blah + * ```javascript + * const l from '@polkadot/util/logger')('test'); + * + * l.log('blah'); // TEST: blah + * ``` */ export default function logger (_type: string): Logger { const type = ` ${_type.toUpperCase()}:`.slice(-16); diff --git a/packages/util/src/number/toHex.ts b/packages/util/src/number/toHex.ts index c30c0636c..a505cbb01 100644 --- a/packages/util/src/number/toHex.ts +++ b/packages/util/src/number/toHex.ts @@ -13,10 +13,14 @@ import isUndefined from '../is/undefined'; * @description * `null`/`undefined`/`NaN` inputs returns an empty `0x` result. `number` input values return the actual bytes value converted to a `hex`. With `bitLength` set, it converts the number to the equivalent size. * @example - * import { numberToHex } from '@polkadot/util'; + *
* - * numberToHex(0x1234); // => '0x1234' - * numberToHex(0x1234, 32) // => 0x00001234 + * ```javascript + * import { numberToHex } from '@polkadot/util'; + * + * numberToHex(0x1234); // => '0x1234' + * numberToHex(0x1234, 32); // => 0x00001234 + * ``` */ export default function numberToHex (value?: number, bitLength: number = -1): string { if (isUndefined(value) || isNull(value) || isNaN(value)) { diff --git a/packages/util/src/number/toU8a.ts b/packages/util/src/number/toU8a.ts index bf1b1b62e..b029d271c 100644 --- a/packages/util/src/number/toU8a.ts +++ b/packages/util/src/number/toU8a.ts @@ -12,9 +12,13 @@ import numberToHex from './toHex'; * @description * `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `number` input values return the actual bytes value converted to a `Uint8Array`. With `bitLength`, it converts the value to the equivalent size. * @example - * import { numberToU8a } from '@polkadot/util'; + *
* - * numberToU8a(0x1234); // => [0x12, 0x34] + * ```javascript + * import { numberToU8a } from '@polkadot/util'; + * + * numberToU8a(0x1234); // => [0x12, 0x34] + * ``` */ export default function numberToU8a (value?: number, bitLength: number = -1): Uint8Array { if (!value || isNaN(value)) { diff --git a/packages/util/src/promisify.ts b/packages/util/src/promisify.ts index 3636f7503..b6a1201d1 100644 --- a/packages/util/src/promisify.ts +++ b/packages/util/src/promisify.ts @@ -9,10 +9,14 @@ * @description * Wraps the supplied async function `fn` that has a standard JS callback `(error: Error, result: any)` into a `Promise`, passing the supplied parameters. When `error` is set, the Promise is rejected, else the Promise resolves with the `result` value. * @example - * import { promisify } from '@polkadot/util'; + *
* - * await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true` - * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!` + * ```javascript + * const { promisify } from '@polkadot/util'; + * + * await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true` + * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!` + * ``` */ export default function promisify (self: any, fn: Function, ...params: Array): Promise { return new Promise((resolve, reject) => { diff --git a/packages/util/src/string/lowerFirst.ts b/packages/util/src/string/lowerFirst.ts index 8e65ae58f..de9004a91 100644 --- a/packages/util/src/string/lowerFirst.ts +++ b/packages/util/src/string/lowerFirst.ts @@ -12,9 +12,13 @@ import isUndefined from '../is/undefined'; * @description * Lowercase the first letter of a string * @example - * import { stringLowerFirst } from '@polkadot/util'; + *
* - * stringLowerFirst('ABC'); // => 'aBC' + * ```javascript + * import { stringLowerFirst } from '@polkadot/util'; + * + * stringLowerFirst('ABC'); // => 'aBC' + * ``` */ export default function stringLowerFirst (_value: string): string { if (isNull(_value) || isUndefined(_value)) { diff --git a/packages/util/src/string/shorten.ts b/packages/util/src/string/shorten.ts index 3f37f07cd..78af64267 100644 --- a/packages/util/src/string/shorten.ts +++ b/packages/util/src/string/shorten.ts @@ -9,9 +9,13 @@ * @description * Checks the string against the `prefixLength`, if longer than dopuble this, shortens it by placing `..` in the middle of it * @example - * import { stringShorten } from '@polkadot/util'; + *
* - * stringShorten('1234567890', 2); // => 12..90 + * ```javascript + * import { stringShorten } from '@polkadot/util'; + * + * stringShorten('1234567890', 2); // => 12..90 + * ``` */ export default function stringShorten (_value: any, prefixLength: number = 6): string { const value = `${_value}`; diff --git a/packages/util/src/string/toU8a.ts b/packages/util/src/string/toU8a.ts index c6b94b24f..8aca5eb72 100644 --- a/packages/util/src/string/toU8a.ts +++ b/packages/util/src/string/toU8a.ts @@ -13,9 +13,13 @@ const encoder = new TextEncoder(); * @description * String input values return the actual encoded `UInt8Array`. `null` or `undefined` values returns an empty encoded array. * @example - * import { stringToU8a } from '@polkadot/util'; + *
* - * stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f] + * ```javascript + * import { stringToU8a } from '@polkadot/util'; + * + * stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f] + * ``` */ export default function stringToU8a (value?: string): Uint8Array { if (!value) { diff --git a/packages/util/src/string/upperFirst.ts b/packages/util/src/string/upperFirst.ts index e2e81c456..9492ab384 100644 --- a/packages/util/src/string/upperFirst.ts +++ b/packages/util/src/string/upperFirst.ts @@ -12,9 +12,13 @@ import isUndefined from '../is/undefined'; * @description * Lowercase the first letter of a string * @example - * import { stringUpperFirst } from '@polkadot/util'; + *
* - * stringUpperFirst('abc'); // => 'Abc' + * ```javascript + * import { stringUpperFirst } from '@polkadot/util'; + * + * stringUpperFirst('abc'); // => 'Abc' + * ``` */ export default function stringUpperFirst (_value: string): string { if (isNull(_value) || isUndefined(_value)) { diff --git a/packages/util/src/u8a/concat.ts b/packages/util/src/u8a/concat.ts index 57fa8a58a..2992a7241 100644 --- a/packages/util/src/u8a/concat.ts +++ b/packages/util/src/u8a/concat.ts @@ -11,12 +11,16 @@ import u8aToU8a from './toU8a'; * @description * Concatenates the input arrays into a single `UInt8Array`. * @example - * import { u8aConcat } from '@polkadot/util'; + *
* - * u8aConcat( - * new Uint8Array([1, 2, 3]), - * new Uint8Array([4, 5, 6]) - * ); // [1, 2, 3, 4, 5, 6] + * ```javascript + * import { u8aConcat } from '@polkadot/util'; + * + * u8aConcat( + * new Uint8Array([1, 2, 3]), + * new Uint8Array([4, 5, 6]) + * ); // [1, 2, 3, 4, 5, 6] + * ``` */ export default function u8aConcat (..._list: Array): Uint8Array { const list: Array = _list.map(u8aToU8a); diff --git a/packages/util/src/u8a/fixLength.ts b/packages/util/src/u8a/fixLength.ts index 1e5b69945..bd55e3f9a 100644 --- a/packages/util/src/u8a/fixLength.ts +++ b/packages/util/src/u8a/fixLength.ts @@ -9,11 +9,15 @@ * @description * Returns a uint8Array with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. * @example - * import { u8aFixLength } from '@polkadot/util'; + *
* - * u8aFixLength('0x12') // => 0x12 - * u8aFixLength('0x12', 16) // => 0x0012 - * u8aFixLength('0x1234', 8) // => 0x12 + * ```javascript + * import { u8aFixLength } from '@polkadot/util'; + * + * u8aFixLength('0x12') // => 0x12 + * u8aFixLength('0x12', 16) // => 0x0012 + * u8aFixLength('0x1234', 8) // => 0x12 + * ``` */ export default function u8aFixLength (value: Uint8Array, bitLength: number = -1, atStart: boolean = false): Uint8Array { const byteLength = Math.ceil(bitLength / 8); diff --git a/packages/util/src/u8a/toBn.ts b/packages/util/src/u8a/toBn.ts index 626402017..e7715545a 100644 --- a/packages/util/src/u8a/toBn.ts +++ b/packages/util/src/u8a/toBn.ts @@ -14,9 +14,13 @@ import u8aToHex from './toHex'; * @description * `UInt8Array` input values return the actual BN. `null` or `undefined` values returns an `0x0` value. * @example - * import { u8aToBn } from '@polkadot/util'; + *
* - * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f + * ```javascript + * import { u8aToBn } from '@polkadot/util'; + * + * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f + * ``` */ export default function u8aToBn (value: Uint8Array, isLe: boolean): BN { return hexToBn( diff --git a/packages/util/src/u8a/toBuffer.ts b/packages/util/src/u8a/toBuffer.ts index 377a028aa..2a5e4d499 100644 --- a/packages/util/src/u8a/toBuffer.ts +++ b/packages/util/src/u8a/toBuffer.ts @@ -9,9 +9,13 @@ * @description * `null` inputs returns an empty `Buffer` result. `UInt8Array` input values return the actual bytes value converted to a `Buffer`. Anything that is not a `UInt8Array` throws an error. * @example - * import { u8aToBuffer } from '@polkadot/util'; + *
* - * console.log('Buffer', u8aToBuffer('0x123480001f')); + * ```javascript + * import { u8aToBuffer } from '@polkadot/util'; + * + * console.log('Buffer', u8aToBuffer('0x123480001f')); + * ``` */ export default function u8aToBuffer (value?: Uint8Array): Buffer { if (!value) { diff --git a/packages/util/src/u8a/toHex.ts b/packages/util/src/u8a/toHex.ts index e9dc13018..90b1eab3e 100644 --- a/packages/util/src/u8a/toHex.ts +++ b/packages/util/src/u8a/toHex.ts @@ -9,9 +9,13 @@ * @description * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string. * @example - * import { u8aToHex } from '@polkadot/util'; + *
* - * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f + * ```javascript + * import { u8aToHex } from '@polkadot/util'; + * + * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f + * ``` */ export default function u8aToHex (value?: Uint8Array | null, bitLength: number = -1, isPrefixed: boolean = true): string { const prefix = isPrefixed diff --git a/packages/util/src/u8a/toString.ts b/packages/util/src/u8a/toString.ts index 658b62bb5..689710e8e 100644 --- a/packages/util/src/u8a/toString.ts +++ b/packages/util/src/u8a/toString.ts @@ -13,9 +13,13 @@ const decoder = new TextDecoder('utf-8'); * @description * `UInt8Array` input values return the actual decoded utf-8 string. `null` or `undefined` values returns an empty string. * @example - * import { u8aToString } from '@polkadot/util'; + *
* - * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello + * ```javascript + * import { u8aToString } from '@polkadot/util'; + * + * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello + * ``` */ export default function u8aToString (value?: Uint8Array): string { if (!value || !value.length) { diff --git a/packages/util/src/u8a/toU8a.ts b/packages/util/src/u8a/toU8a.ts index 564edd211..68817a21e 100644 --- a/packages/util/src/u8a/toU8a.ts +++ b/packages/util/src/u8a/toU8a.ts @@ -16,10 +16,14 @@ import stringToU8a from '../string/toU8a'; * @description * `null` inputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation. * @example - * import { u8aToU8a } from '@polkadot/util'; + *
* - * u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34]) - * u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34]) + * ```javascript + * import { u8aToU8a } from '@polkadot/util'; + * + * u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34]) + * u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34]) + * ``` */ export default function u8aToU8a (value?: Array | Buffer | Uint8Array | string | null): Uint8Array { if (!value) { diff --git a/tsconfig.json b/tsconfig.json index 7db06df88..a327bc6e7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,11 +4,11 @@ "baseUrl": ".", "paths": { "@polkadot/db/*": [ "packages/db/src/*" ], + "@polkadot/keyring/*": [ "packages/keyring/src/*" ], "@polkadot/trie-db-old/*": [ "packages/trie-db-old/src/*" ], "@polkadot/trie-db/*": [ "packages/trie-db/src/*" ], "@polkadot/trie-hash/*": [ "packages/trie-hash/src/*" ], "@polkadot/util-crypto/*": [ "packages/util-crypto/src/*" ], - "@polkadot/util-keyring/*": [ "packages/util-keyring/src/*" ], "@polkadot/util-rlp/*": [ "packages/util-rlp/src/*" ], "@polkadot/util/*": [ "packages/util/src/*" ] }, diff --git a/typedoc.js b/typedoc.js new file mode 100644 index 000000000..6bd8b7674 --- /dev/null +++ b/typedoc.js @@ -0,0 +1,16 @@ +module.exports = { + name: 'Polkadot JS Common', + exclude: [], + excludeExternals: true, + excludeNotExported: true, + excludeProtected: true, + excludePrivate: true, + hideGenerator: true, + includeDeclarations: false, + out: 'docs', + module: 'commonjs', + moduleResolution: 'node', + mdEngine: 'gitbook', + stripInternal: 'true', + theme: 'markdown' +};