Compare commits

..
256 Commits
Author SHA1 Message Date
Github Actions cc8639565d [CI Skip] release/stable 2.12.2
skip-checks: true
2020-06-02 08:31:51 +00:00
Jaco Greeff b77d2e6860 Linting 2020-06-02 10:28:25 +02:00
Jaco Greeff e1fbd8ff9f 2.12.2 2020-06-02 10:22:30 +02:00
Github Actions f56dd32b4a [CI Skip] release/stable 2.12.1
skip-checks: true
2020-06-01 16:09:53 +00:00
Jaco Greeff 6077bef570 2.12 (#609) 2020-06-01 18:05:55 +02:00
Github Actions 377d83d4ed [CI Skip] release/beta 2.12.0-beta.2
skip-checks: true
2020-06-01 08:31:12 +00:00
Jaco Greeff bdb14f91a8 Pre-checks on verify input lengths (#608)
* Pre-checks on verify input lengths

* Small cleanup

* Update error signatures
2020-06-01 10:27:08 +02:00
Github Actions cc5b7ed0ad [CI Skip] release/beta 2.12.0-beta.1
skip-checks: true
2020-06-01 07:33:27 +00:00
Jaco Greeff d4491aeb7f Small cleanups, u8aConcat optimization (#607)
* Small cleanups, u8aConcat oprimizations

* Cleanup

* Pre-allocate arrays

* Don't recreate PREFIX
2020-06-01 09:29:44 +02:00
Github Actions 0f6e996799 [CI Skip] release/beta 2.12.0-beta.0
skip-checks: true
2020-05-31 12:22:47 +00:00
Jaco Greeff 1f3dd60a8d {address,u8a}Eq functions (#606)
* {addres,u8a}Eq functions

* Remove mnemonicToSeed
2020-05-31 14:19:10 +02:00
Github Actions 3351fb1cba [CI Skip] 2.11.1
skip-checks: true
2020-05-26 07:00:59 +00:00
Jaco Greeff 32d176e424 2.11 (#604) 2020-05-26 08:57:31 +02:00
Github Actions aec1e26cb9 [CI Skip] 2.11.0-beta.2
skip-checks: true
2020-05-24 17:08:04 +00:00
Jaco Greeff 7d529b6c93 Type adjustments for meta 2020-05-24 19:04:15 +02:00
Github Actions e22b39ae01 [CI Skip] 2.11.0-beta.1
skip-checks: true
2020-05-23 12:26:33 +00:00
Jaco Greeff 18a202c460 Bump dev w/ eslint (#603)
* Bump dev w/ eslint

* Mop-up remaining lint issues

* Update stringShorten expectation
2020-05-23 14:23:13 +02:00
Github Actions fd9ce319a5 [CI Skip] 2.11.0-beta.0
skip-checks: true
2020-05-15 10:37:46 +00:00
Jaco Greeff a04c0a5e82 Bump deps (#601) 2020-05-15 12:34:22 +02:00
Github Actions 06cb5e57a0 [CI Skip] 2.10.1
skip-checks: true
2020-05-14 05:42:04 +00:00
Jaco Greeff 103ea045bf 2.10 (#599) 2020-05-14 07:38:43 +02:00
Github Actions 4315c76814 [CI Skip] 2.10.0-beta.5
skip-checks: true
2020-05-11 12:01:35 +00:00
Jaco Greeff 6de6b871cd Adjust DeriveJunction (types & BigInt) (#598) 2020-05-11 13:57:59 +02:00
Github Actions 82e5d76821 [CI Skip] 2.10.0-beta.4
skip-checks: true
2020-05-11 09:58:13 +00:00
Jaco Greeff d9a18a4acf Bump berry (#597) 2020-05-11 11:54:45 +02:00
Github Actions 2d1d4f808e [CI Skip] 2.10.0-beta.3
skip-checks: true
2020-05-11 08:00:19 +00:00
Jaco Greeff d1de30907f TextEncoder allows non-Uint8Array Buffers (#596)
* TextEncoder allows non-Uint8Array Buffers

* Add eslintrc to eslintignore
2020-05-11 09:57:00 +02:00
Github Actions d3583dc432 [CI Skip] 2.10.0-beta.2
skip-checks: true
2020-05-08 18:15:33 +00:00
Wei Tang bb04fa28f7 ss58: add Kulupu prefix to the list (#595) 2020-05-08 20:12:17 +02:00
Github Actions bd8e862b62 [CI Skip] 2.10.0-beta.1
skip-checks: true
2020-04-30 06:06:24 +00:00
Jaco Greeff 0f45b7fbf3 Bump deps (#594) 2020-04-30 08:03:20 +02:00
Github Actions 03eb72f128 [CI Skip] 2.10.0-beta.0
skip-checks: true
2020-04-30 05:31:32 +00:00
Jaco Greeff f76a4a98be beta bump (#593) 2020-04-30 07:28:35 +02:00
Github Actions c2b91ad8c2 [CI Skip] 2.9.1
skip-checks: true
2020-04-29 22:42:23 +00:00
Jaco Greeff ffc6b0323b 2.9.1 2020-04-30 00:38:59 +02:00
Github Actions b666db2721 [CI Skip] 2.9.0-beta.4
skip-checks: true
2020-04-29 22:37:08 +00:00
Jaco Greeff b00d49564f Update CHANGELOG.md 2020-04-30 00:34:31 +02:00
Alexander Krupenkin 34380caf1f Added ECDSA keypair support (#589)
* Added ECDSA signature verification

* Add ECDSA keypair, sign, key derivation, fromSeed and tests

* keyring: added ECDSA keypair

* Fix lint errors
2020-04-30 00:33:10 +02:00
Github Actions 277cc2b5a8 [CI Skip] 2.9.0-beta.3
skip-checks: true
2020-04-26 20:26:19 +00:00
joe petrowski 733e9e2729 Add example for multisig address creation (#590)
* add multisig example

* typo

* lint fix

* sort addresses

* make linter happy

* clean up sorting with ss58 param
2020-04-26 22:23:15 +02:00
Github Actions 482264c615 [CI Skip] 2.9.0-beta.2
skip-checks: true
2020-04-26 12:36:41 +00:00
Jaco Greeff 5d0abef952 Sort with ss58 prefix (#591) 2020-04-26 14:33:45 +02:00
Github Actions 2397e1c5d7 [CI Skip] 2.9.0-beta.1
skip-checks: true
2020-04-24 17:18:36 +00:00
Jaco Greeff 62ebe257a6 u8aSorted & sortAddresses (#588) 2020-04-24 19:15:43 +02:00
Github Actions a2844a449c [CI Skip] 2.9.0-beta.0
skip-checks: true
2020-04-24 13:38:04 +00:00
Jaco Greeff 60a9866abe Create createKeyMulti & createKeySub for utility (util-crypto) (#587)
* Create keyMulti & keysub for utility

* Bumps
2020-04-24 15:34:47 +02:00
Github Actions b196158125 [CI Skip] 2.8.1
skip-checks: true
2020-04-09 13:12:53 +00:00
Jaco Greeff 6b1caacfb9 2.8 (#586)
* 2.8

* Typos
2020-04-09 15:10:23 +02:00
Github Actions a7679fb07c [CI Skip] 2.8.0-beta.7
skip-checks: true
2020-04-07 19:51:29 +00:00
Jaco Greeff c4acca6c7c eslint update 2020-04-07 21:48:07 +02:00
Github Actions 5012792693 [CI Skip] 2.8.0-beta.6
skip-checks: true
2020-04-07 19:26:31 +00:00
Jaco Greeff d40d6c65f7 isDevelopment regex 2020-04-07 21:23:20 +02:00
Github Actions 2c0d8e4b59 [CI Skip] 2.8.0-beta.5
skip-checks: true
2020-04-06 10:25:18 +00:00
Jaco Greeff d3d8caa0df Use bundled node (#585) 2020-04-06 12:22:31 +02:00
Github Actions a8f8525c9d [CI Skip] 2.8.0-beta.4
skip-checks: true
2020-04-05 07:55:56 +00:00
Jaco Greeff caa5a8b9e6 Bump deps (#584) 2020-04-05 09:52:59 +02:00
Github Actions ce6187f378 [CI Skip] 2.8.0-beta.3
skip-checks: true
2020-04-04 08:45:26 +00:00
Jaco Greeff fe9c7a8a80 Bump deps (#583) 2020-04-04 10:42:21 +02:00
Github Actions d5584c1837 [CI Skip] 2.8.0-beta.2
skip-checks: true
2020-04-02 06:45:50 +00:00
Jaco Greeff adb1c1fea4 Rewrite yarn.lock (#580) 2020-04-02 08:42:32 +02:00
Github Actions c87c228ab1 [CI Skip] 2.8.0-beta.1
skip-checks: true
2020-04-01 19:23:33 +00:00
Jaco Greeff cbec4add88 Bump dev (incl. lint fixes) (#579)
* Bump dev (incl. lint fixes)

* Fix failures
2020-04-01 21:20:50 +02:00
Github Actions 6429cc307c [CI Skip] 2.8.0-beta.0
skip-checks: true
2020-04-01 18:47:32 +00:00
h4x3rotab c98e994777 Throws an error when signing with a locked keypair (#578)
* Throws an error when signing with a locked keypair

Fixes #576

* Fix lint errors

* Switch to `assert` and fix nits
2020-04-01 20:44:40 +02:00
Github Actions 697a452ba6 [CI Skip] 2.7.1
skip-checks: true
2020-03-31 11:56:12 +00:00
Jaco Greeff f68294c4e7 2.7 (#575) 2020-03-31 13:53:10 +02:00
Github Actions 0130d18945 [CI Skip] 2.7.0-beta.8
skip-checks: true
2020-03-24 06:29:44 +00:00
Jaco Greeff 15c9904c96 Add bnSqrt (#574)
* Add bnSqrt function

* Bumps

* CHANGELOG

* Add extra case
2020-03-24 07:25:53 +01:00
Github Actions add2749967 [CI Skip] 2.7.0-beta.7
skip-checks: true
2020-03-24 05:58:23 +00:00
Jaco Greeff fe2f054389 wasm-crypto initNone (#573)
* wasm-crypto initNone

* noWasm to replace @polkadot/wasm-crypto interface
2020-03-24 06:55:07 +01:00
Github Actions bb1c117727 [CI Skip] 2.7.0-beta.6
skip-checks: true
2020-03-21 09:15:30 +00:00
Jaco Greeff 27c474bd78 Bump deps (#572)
* Bump deps

* @types/jest
2020-03-21 10:12:17 +01:00
Github Actions 039b5ec932 [CI Skip] 2.7.0-beta.5
skip-checks: true
2020-03-16 14:35:40 +00:00
Jaco Greeff 9eea21e0c4 Add yarn matrix (#570)
* Add yarn matrix

* Update pr-any.yml
2020-03-16 15:32:59 +01:00
Github Actions aab533f92e [CI Skip] 2.7.0-beta.4
skip-checks: true
2020-03-16 13:36:21 +00:00
Jaco Greeff 2159270d80 Remove actions matrix (#569)
* Remove actions matrix

* Bumps
2020-03-16 14:33:27 +01:00
Github Actions f1b09eb2e5 [CI Skip] 2.7.0-beta.3
skip-checks: true
2020-03-15 07:21:01 +00:00
Jaco Greeff d08cf8b5fe Remove non-working CI cache (#567) 2020-03-15 08:18:04 +01:00
Github Actions 941618b830 [CI Skip] 2.7.0-beta.2
skip-checks: true
2020-03-14 08:31:56 +00:00
Jaco Greeff 983ca718ec Bump deps (#566) 2020-03-14 09:28:16 +01:00
Github Actions 41ebdd5c59 [CI Skip] 2.7.0-beta.1
skip-checks: true
2020-03-11 06:46:07 +00:00
Jaco Greeff 8971c89081 Back to preminor (#565) 2020-03-11 07:42:45 +01:00
Github Actions d1934060e0 [CI Skip] 2.6.2
skip-checks: true
2020-03-11 06:39:27 +00:00
Jaco Greeff 6d9da39d8b Bump dev, fix publish 2020-03-11 07:35:48 +01:00
Jaco Greeff 4ed096024e typeof __dirname !== 'undefined' before using (#564)
* typeof __dirname !== 'undefined' before using

* Use as patch

* yarn.lock

* Rewrite yarn.lock

* Shorten __dirname check
2020-03-11 07:18:52 +01:00
Github Actions ae36d58802 [CI Skip] 2.6.1
skip-checks: true
2020-02-29 17:48:10 +00:00
Jaco Greeff c8100dbe43 2.6 (#560)
* 2.6

* Update CHANGELOG
2020-02-29 18:44:50 +01:00
Github Actions 28d2ce38bd [CI Skip] 2.6.0-beta.8
skip-checks: true
2020-02-29 12:57:21 +00:00
Jaco Greeff afce99ed1a Minify yarn plugins (#559) 2020-02-29 13:53:57 +01:00
Github Actions 29d13ab19c [CI Skip] 2.6.0-beta.7
skip-checks: true
2020-02-29 11:30:10 +00:00
Jaco Greeff 68a8bcb7db Remove yarn version plugin, bump dev (#558) 2020-02-29 12:27:02 +01:00
Github Actions d2ecf1730a [CI Skip] 2.6.0-beta.6
skip-checks: true
2020-02-29 10:53:59 +00:00
Jaco Greeff af56c10278 Add cryptoIsReady (#557)
* Add cryptoIsReady

* Bump yarn
2020-02-29 11:51:17 +01:00
Github Actions 42f318fcb5 [CI Skip] 2.6.0-beta.5
skip-checks: true
2020-02-29 09:29:29 +00:00
Jaco Greeff 336df0d76d yarn --immutable on CI (#556)
* yarn --immutable on CI

* dev bump
2020-02-29 10:26:32 +01:00
Github Actions d85cedf5a0 [CI Skip] 2.6.0-beta.4
skip-checks: true
2020-02-28 12:19:35 +00:00
Jaco Greeff a59187bce6 Bump dev 2020-02-28 13:16:23 +01:00
Github Actions f9a5b75e10 [CI Skip] 2.6.0-beta.3
skip-checks: true
2020-02-28 12:06:20 +00:00
Jaco Greeff 87228149d4 Explicit gh-pages dep 2020-02-28 13:03:03 +01:00
Github Actions 67f36f6a13 [CI Skip] 2.6.0-beta.2
skip-checks: true
2020-02-28 11:32:49 +00:00
Jaco Greeff 75a9898daf Update to yarn 2 (#555) 2020-02-28 12:29:25 +01:00
Jaco Greeff 0f726ce777 Small formatting cleanups (#554)
* Small formatting cleanups

* Cleanup typos
2020-02-28 12:27:27 +01:00
Github Actions 765f9baf44 [CI Skip] 2.6.0-beta.1
skip-checks: true
2020-02-24 21:25:28 +00:00
Jaco Greeff 2d181df360 Bump wasm to 1.1 (#553)
* Bump wasm to 1.1

* typo
2020-02-24 22:23:48 +01:00
Github Actions 77ff703a08 [CI Skip] 2.6.0-beta.0
skip-checks: true
2020-02-24 10:56:56 +00:00
Jaco Greeff 804ed13d0a Add signatureVerify (#552)
* Add signatureVerify

* addressOrPublicKey typo

* Flatten verify, allow extra types

* Add signatureVerify tests

* De-dup address checksum checks
2020-02-24 11:55:15 +01:00
Jaco Greeff 341a6b0c08 Add TS 3.8 breaking feature in CHANGELOG (missed) (#551) 2020-02-24 09:08:16 +01:00
Jaco Greeff 614985b8ac Remove gh-pages script (in dev) (#549) 2020-02-22 16:56:24 +01:00
Github Actions d5bfa8c3c4 [CI Skip] 2.5.1
skip-checks: true
2020-02-22 15:34:36 +00:00
Jaco Greeff 359981d2ef Add pages refresh script (#548) 2020-02-22 16:32:41 +01:00
Jaco Greeff b0ee79f90c 2.5 (#547) 2020-02-22 15:57:33 +01:00
Github Actions c2d595fb3f [CI Skip] 2.5.0-beta.3
skip-checks: true
2020-02-22 14:23:29 +00:00
Jaco Greeff f837200a73 Fix isChildClass with correct is assertion (#546)
* Fix isChildClass with correct is assertion

* Remove stray any, allow never
2020-02-22 15:21:24 +01:00
Github Actions ea7dd553a2 [CI Skip] 2.5.0-beta.2
skip-checks: true
2020-02-22 13:46:55 +00:00
Jaco Greeff 7c1ca3a5c9 Use #<varname> instead of private _<varname> (#545)
* Use #<varname> insead of private _<varname>

* Update key extraction paths
2020-02-22 14:45:31 +01:00
Github Actions 75cd547b49 [CI Skip] 2.5.0-beta.1
skip-checks: true
2020-02-22 12:27:44 +00:00
Jaco Greeff 91c4c407a9 Add isChildClass (#544)
* Add isChildClass

* isChildClass is return

* Cleanup doc example
2020-02-22 13:26:12 +01:00
Github Actions 20b46a65fa [CI Skip] 2.5.0-beta.0
skip-checks: true
2020-02-21 15:56:13 +00:00
Jaco Greeff c60459e303 Add isBigInt & bnToBn support for (#542)
* Add isBigInt & bnToBn support for

* All BN inputs allow BigInt
2020-02-21 16:54:33 +01:00
Jaco Greeff 92ab4699b3 Re-add code build 2020-02-20 20:56:31 +01:00
Jaco Greeff 932f4c25f5 Docs rebuild 2020-02-20 20:52:19 +01:00
Jaco Greeff aaa35a8198 trigger docs 2020-02-20 17:45:57 +01:00
Github Actions 9708131620 [CI Skip] 2.4.1
skip-checks: true
2020-02-18 08:02:01 +00:00
Jaco Greeff c539430a0b 2.4 (#539) 2020-02-18 09:00:08 +01:00
Github Actions 8defc792a9 [CI Skip] 2.4.0-beta.2
skip-checks: true
2020-02-17 15:25:48 +00:00
Jaco Greeff 76a0daeed6 Use ss58 format on keyring for the keyring only (#538)
* Use ss58 format on keyring for the keyring only

* Cleanup args

* Cleanup failures

* Remove deprecated addressPrefix

* Update CHANGELOG
2020-02-17 16:24:03 +01:00
Github Actions e236fdc396 [CI Skip] 2.4.0-beta.1
skip-checks: true
2020-02-17 14:07:53 +00:00
Jaco Greeff e30dd7c0d9 Add GH actions yarn cache (#537) 2020-02-17 15:06:00 +01:00
Github Actions f3ac6b2674 [CI Skip] 2.4.0-beta.0
skip-checks: true
2020-02-17 11:18:01 +00:00
Jaco Greeff 171015fbba formatBalance adjustments (#536)
* formatBalance extensions

* Fly-by any removals

* isBn updates

* Remove unneeded ()'s
2020-02-17 12:16:02 +01:00
Github Actions dca36e41fd [CI Skip] 2.3.1
skip-checks: true
2020-02-15 11:00:43 +00:00
Jaco Greeff a602b0409c 2.3 (#535) 2020-02-15 11:59:04 +01:00
Github Actions 04d79da155 [CI Skip] 2.3.0-beta.9
skip-checks: true
2020-02-15 10:26:00 +00:00
Jaco Greeff 81a31519db Move date formatter to format (#534)
* Move date formatter to format

* Cleanup padding
2020-02-15 11:24:16 +01:00
Github Actions 78e39dcf34 [CI Skip] 2.3.0-beta.8
skip-checks: true
2020-02-15 10:09:19 +00:00
Jaco Greeff 6194660b3b Bump @polkadot/wasm to 1.0 (#533) 2020-02-15 11:07:33 +01:00
AndreasGassmannandJaco Greeff 2e08018718 feat(dependencies): remove moment.js (#530)
* feat(dependencies): remove moment.js

* fix(dependencies): remove yarn from yarn.lock

* feat(log-date-formatting): rename function

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-02-15 11:06:45 +01:00
Github Actions b0d6ccdbd4 [CI Skip] 2.3.0-beta.7
skip-checks: true
2020-02-15 09:27:10 +00:00
Jaco Greeff 48b753b8ac CHANGELOG update (#532) 2020-02-15 10:25:23 +01:00
Github Actions 506bc59f86 [CI Skip] 2.3.0-beta.6
skip-checks: true
2020-02-14 11:33:24 +00:00
AndreasGassmann f86fcc6044 feat(dependencies): move types to dev dependencies (#531) 2020-02-14 12:31:29 +01:00
Github Actions e8d2a439d5 [CI Skip] 2.3.0-beta.5
skip-checks: true
2020-02-14 08:43:15 +00:00
Jaco Greeff 9fa6b5bffa Bump dev, CI scripts (#529) 2020-02-14 09:41:29 +01:00
Github Actions 932ef41aae [CI Skip] 2.3.0-beta.4
skip-checks: true
2020-02-14 07:41:39 +00:00
Jaco Greeff 3910853ba1 Bump dev (#528) 2020-02-14 08:39:58 +01:00
Github Actions 6956e88708 [CI Skip] 2.3.0-beta.3
skip-checks: true
2020-02-14 07:11:09 +00:00
Jaco Greeff 3769b99cd2 Bump dev (#527)
* Bump dev

* Bumps
2020-02-14 08:09:29 +01:00
Github Actions ee17054b38 [CI Skip] 2.3.0-beta.2
skip-checks: true
2020-02-13 21:50:26 +00:00
Jaco Greeff 72cfbddd4a Bump dev (#526)
* Bump dev

* Bumps

* Bump

* Bump
2020-02-13 22:48:36 +01:00
Github Actions cffb23728d [CI Skip] 2.3.0-beta.1
skip-checks: true
2020-02-13 13:57:56 +00:00
Jaco Greeff a69dc01c78 Bump dev (#525) 2020-02-13 14:56:10 +01:00
Github Actions d889c71056 [CI Skip] 2.3.0-beta.0
skip-checks: true
2020-02-12 15:20:17 +00:00
Jaco Greeff 8eef3f9989 Cleanup explicit deps & bump deps (#523) 2020-02-12 16:18:21 +01:00
Github Actions 3112e43715 [CI Skip] 2.2.1
skip-checks: true
2020-02-06 14:46:00 +00:00
Jaco Greeff fc9a5ac25f 2.2 (#520) 2020-02-06 15:44:11 +01:00
Github Actions 242b107752 [CI Skip] 2.2.0-beta.0
skip-checks: true
2020-02-06 13:51:56 +00:00
Jaco Greeff bf5ba0f405 Add resolver for jest (#519) 2020-02-06 14:49:55 +01:00
Github Actions e4de3a1339 [CI Skip] 2.1.1
skip-checks: true
2020-02-04 12:53:47 +00:00
Jaco Greeff 69279f1b81 2.1 (#518) 2020-02-04 13:51:51 +01:00
Github Actions 303c822d48 [CI Skip] 2.1.0-beta.1
skip-checks: true
2020-02-04 10:39:58 +00:00
Jaco Greeff 90ca8a0d78 Backwards compat. on detctPackage (#517) 2020-02-04 11:38:00 +01:00
Github Actions 94bbc6f2ee [CI Skip] 2.1.0-beta.0
skip-checks: true
2020-02-03 12:23:51 +00:00
Jaco Greeff f4be1fe52e Multiple versions with __dirname (#515)
* Multiple versions with __dirname

* Fallback for __dirname

* Update path

* Flatten versions extracted

* Expand display for versions
2020-02-03 13:21:46 +01:00
Github Actions d3f6f3621b [CI Skip] 2.0.1
skip-checks: true
2020-01-30 15:10:33 +00:00
Jaco Greeff ea9ad6f389 2.0 (#514) 2020-01-30 16:08:33 +01:00
Github Actions b03ce51a31 [CI Skip] 2.0.0-beta.10
skip-checks: true
2020-01-29 09:25:20 +00:00
Jaco Greeff b8411bb0ea Bump deps (#513)
* Bump deps

* Linting
2020-01-29 10:23:27 +01:00
Github Actions 36b53c5a8e [CI Skip] 2.0.0-beta.9
skip-checks: true
2020-01-28 17:42:32 +00:00
Jaco Greeff e60bbbeb59 Trigger (#510) 2020-01-28 18:40:19 +01:00
Jaco Greeff eb90564260 Trigger (#509) 2020-01-28 18:34:38 +01:00
Github Actions 1c151ca04a [CI Skip] 2.0.0-beta.8
skip-checks: true
2020-01-28 17:32:16 +00:00
Jaco Greeff 249919502a Package.json alias 2020-01-28 18:30:12 +01:00
Github Actions a2f9614ce8 [CI Skip] 2.0.0-beta.7
skip-checks: true
2020-01-28 16:15:04 +00:00
Jaco Greeff 98bdc9950a Introduce detectPackage (with versioning) (#508)
* Introduce detectPackage (with versioning)

* Update expectation
2020-01-28 17:13:02 +01:00
Github Actions 1387839696 [CI Skip] 2.0.0-beta.6
skip-checks: true
2020-01-25 11:12:06 +00:00
Jaco Greeff 4e8cb2af2f Bump deps (#507)
* Bump deps

* Remove mdEngine

* Re-add mdEngine (SUMMARY.md to be generated)

* Update dev

* Remove mdEngine
2020-01-25 12:10:09 +01:00
Github Actions dd0de55638 [CI Skip] 2.0.0-beta.5
skip-checks: true
2020-01-23 15:09:25 +00:00
Jaco Greeff e09d0ca5ca Allow with expanded SI unit (m -> milli) (#505) 2020-01-23 16:07:01 +01:00
Github Actions 41f024d0fc [CI Skip] 2.0.0-beta.4
skip-checks: true
2020-01-15 11:29:28 +00:00
Jaco Greeff 4ce452b40a Remove client-only packages (#503) 2020-01-15 12:27:12 +01:00
Github Actions 0a8ab20744 [CI Skip] 2.0.0-beta.3
skip-checks: true
2020-01-15 11:20:32 +00:00
Jaco Greeff d108970d09 Small function cleanups (#502) 2020-01-15 12:17:38 +01:00
Github Actions 7fb1adb94e [CI Skip] 2.0.0-beta.2
skip-checks: true
2020-01-14 10:17:06 +00:00
Jaco Greeff b7635d7e2b Remove alice_session testing account (#501)
* Remove alice_session testing account

* Remove session check
2020-01-14 11:14:10 +01:00
Github Actions 2273ce8bd3 [CI Skip] 2.0.0-beta.1
skip-checks: true
2020-01-13 16:02:49 +00:00
Jaco Greeff cfdf629b49 Bump to 2.0-beta (#500)
* Bump to 2.0-beta

* Bump wasm
2020-01-13 17:00:00 +01:00
Github Actions f5f35ee3bf [CI Skip] 1.8.1
skip-checks: true
2020-01-09 10:08:27 +00:00
Jaco Greeff c776f0d815 1.8 (#499) 2020-01-09 11:05:30 +01:00
Github Actions c1a23937bd [CI Skip] 1.8.0-beta.3
skip-checks: true
2020-01-06 12:46:24 +00:00
Jaco Greeff 241febb707 Bump deps (#497) 2020-01-06 13:43:49 +01:00
Github Actions 357c7368d2 [CI Skip] 1.8.0-beta.2
skip-checks: true
2019-12-17 10:14:45 +00:00
Hyungsuk Kang 4e4ff5de4b Add cross client Encryption/Decryption (#496)
* chore: add a test

* Add KDF case for double ratchet

* chore: add .idea in .gitignore

* chore: add .vscode to .gitignore

* Remove comma-dangle
2019-12-17 11:12:06 +01:00
Github Actions 8d80bf869b [CI Skip] 1.8.0-beta.1
skip-checks: true
2019-12-07 13:01:32 +00:00
Jaco Greeff 337c67ff30 Bump deps (#495) 2019-12-07 13:58:41 +01:00
Github Actions 66573f6234 [CI Skip] 1.8.0-beta.0
skip-checks: true
2019-12-05 09:31:19 +00:00
Jaco Greeff 408129d5ca Bump deps (#494)
* Bump deps

* Linting
2019-12-05 10:28:40 +01:00
Github Actions efa6661817 [CI Skip] 1.7.1
skip-checks: true
2019-11-27 18:51:43 +00:00
Jaco Greeff c988d5011c 1.7 (#493) 2019-11-27 19:49:06 +01:00
Github Actions f173bb3d2a [CI Skip] 1.7.0-beta.8
skip-checks: true
2019-11-26 10:54:25 +00:00
Jaco Greeff 1f0368061f Bump deps (#492)
* Bump deps

* Add dummy skip step
2019-11-26 11:51:36 +01:00
Github Actions 45ef924862 [CI Skip] 1.7.0-beta.7
skip-checks: true
2019-11-13 09:20:15 +00:00
Jaco Greeff dec88b6ab7 Bump deps (#490) 2019-11-13 10:17:40 +01:00
Github Actions ed402341dc [CI Skip] 1.7.0-beta.6 2019-11-11 08:46:16 +00:00
Jaco Greeff 76a9f2787c assert does asserts conditions (TS 3.7) (#489)
* assert does asserts conditions (TS 3.7)

* Throw in condition

* Fix cleanup
2019-11-11 09:43:05 +01:00
Github Actions 5b1c9b8ccb [CI Skip] 1.7.0-beta.5 2019-11-06 21:21:52 +00:00
Jaco Greeff af751c6c89 Bump deps (#488) 2019-11-06 22:18:57 +01:00
Github Actions 4ab8dd70bd [CI Skip] 1.7.0-beta.4 2019-11-06 14:25:04 +00:00
Jaco Greeff a5f59ca926 Derive operation on keypair (#487)
* Derive operation on keypair

* nobody -> derive

* Derivation tests
2019-11-06 15:22:12 +01:00
Github Actions 71f26aac8d [CI Skip] 1.7.0-beta.3 2019-11-05 13:23:00 +00:00
Github Actions cc7d6a2e01 [CI Skip] 1.7.0-beta.2 2019-11-05 13:18:06 +00:00
Jaco Greeff e29f0a3920 Update .123trigger 2019-11-05 14:14:44 +01:00
Jaco Greeff f38975d126 Allow forcing of units in formatBalance (#486) 2019-11-05 13:53:49 +01:00
Github Actions dc4b59bb0c [CI Skip] 1.7.0-beta.1 2019-10-31 17:22:55 +00:00
Keith Ingram 2f5df085b6 move SiDef type (#485) 2019-10-31 19:19:56 +02:00
Github Actions 225ca1de00 [CI Skip] 1.7.0-beta.0 2019-10-28 16:19:21 +00:00
Jaco Greeff aeb500e804 Use GH_PAT is checkout action 2019-10-28 17:15:38 +01:00
Github Actions e9dd6f1efc [CI Skip] 1.6.1 2019-10-24 11:44:24 +00:00
Jaco Greeff 563dbbf7e4 1.6 (#484) 2019-10-24 13:41:06 +02:00
Github Actions 5a5bc7da0b [CI Skip] 1.6.0-beta.13 2019-10-24 10:13:28 +00:00
Jaco Greeff fb2c51a49b Extend sign(message, options?) with withType (#483) 2019-10-24 12:10:11 +02:00
Github Actions 568e3b7840 [CI Skip] 1.6.0-beta.12 2019-10-22 13:13:03 +00:00
Jaco Greeff 87d69d7098 Excl. tsconfig build (#482) 2019-10-22 15:09:33 +02:00
Github Actions 255cd93bf4 [CI Skip] 1.6.0-beta.11 2019-10-22 09:19:34 +00:00
Jaco Greeff ef5780996e Bump deps (#481) 2019-10-22 11:15:59 +02:00
Github Actions 5155ae8d2b [CI Skip] 1.6.0-beta.10 2019-10-12 13:09:06 +00:00
Jaco Greeff f1447ffcbc Update build (#479) 2019-10-12 15:06:11 +02:00
Jaco Greeff 64e9ec5044 [CI Skip] 1.6.0-beta.9 2019-10-09 12:53:09 +00:00
Jaco Greeff 05986f6d64 Bumps, fix GH pages deploy 2019-10-09 14:48:31 +02:00
Jaco Greeff caca69525a [CI Skip] 1.6.0-beta.8 2019-10-09 12:32:18 +00:00
Jaco Greeff 845398846c Alias GH_TOKEN 2019-10-09 14:27:56 +02:00
Jaco Greeff 412ca6ccd7 [CI Skip] 1.6.0-beta.7 2019-10-09 12:22:40 +00:00
Jaco Greeff 9232fd5a91 [CI Skip] 1.6.0-beta.6 2019-10-09 12:18:00 +00:00
Jaco Greeff 49174d181e [CI Skip] 1.6.0-beta.5 2019-10-09 12:13:41 +00:00
Jaco Greeff c5bc09fde7 Swap CI to GH actions (#477) 2019-10-09 14:08:27 +02:00
Travis CI 1a436906f5 [CI Skip] 1.6.0-beta.4 2019-10-08 12:32:21 +00:00
Jaco Greeff d7bb55c003 Bump deps (#476)
* Bump deps

* Rewrite yarn.lock
2019-10-08 14:15:52 +02:00
Jaco Greeff 50f015a713 Rename push.yml to pr.yml 2019-10-07 16:16:01 +02:00
Travis CI 1c94508d61 [CI Skip] 1.6.0-beta.3 2019-10-07 13:34:01 +00:00
Jaco Greeff ddb007de7b Action only on PR 2019-10-07 15:23:12 +02:00
Travis CI 8bee7d5d6b [CI Skip] 1.6.0-beta.2 2019-10-07 11:34:46 +00:00
Jaco Greeff 253eea9249 Run action on PR 2019-10-07 13:07:33 +02:00
Travis CI 502fdc1e32 [CI Skip] 1.6.0-beta.1 2019-10-04 09:37:00 +00:00
Jaco Greeff f3aaaede25 Split GH actions build (docs & code) (#475)
* Split GH actions build (docs & code)

* Rename action
2019-10-04 11:25:25 +02:00
Travis CI 309d691938 [CI Skip] 1.6.0-beta.0 2019-10-04 07:41:28 +00:00
Jaco Greeff 4d6438c3e7 Add GH actions (#474) 2019-10-04 09:21:03 +02:00
Travis CI 19817b213b [CI Skip] 1.5.1 2019-09-25 10:53:30 +00:00
Jaco Greeff 20d4457483 1.5.0 2019-09-25 12:46:43 +02:00
Travis CI a2d0f2b1a3 [CI Skip] 1.5.0-beta.1 2019-09-25 10:44:39 +00:00
Jaco Greeff a512766bfb 1.5 (#473) 2019-09-25 12:37:59 +02:00
Travis CI b11b42e2b6 [CI Skip] 1.5.0-beta.0 2019-09-19 09:15:51 +00:00
Jaco Greeff c13c2022ca Proper ss58Format check (allows 0) (#472) 2019-09-19 11:09:17 +02:00
Travis CI bf1c187969 [CI Skip] 1.4.1 2019-09-12 12:05:38 +00:00
Jaco Greeff 16d077c87d ss58Format option for Keyring (#471)
* ss58Format option  for Keyring

* Expose setSS58Format everywhere

* Remove setAddressPrefix

* 1.4.0
2019-09-12 13:59:03 +02:00
Jaco Greeff 00374effc5 string <-> hex conversion utilities (#470)
* string <-> hex conversion utilities

* Add tests
2019-09-12 13:48:06 +02:00
Travis CI 891a855fb8 [CI Skip] 1.4.0-beta.0 2019-09-11 10:33:22 +00:00
Jaco Greeff 854cb56621 Bump deps (#469) 2019-09-11 12:25:47 +02:00
457 changed files with 22532 additions and 19612 deletions
+2 -1
View File
@@ -1 +1,2 @@
1
5
2.6.22.12.2
-21
View File
@@ -1,21 +0,0 @@
version: 2
jobs:
build:
working_directory: ~/polkadot-js
docker:
- image: circleci/node:10
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
- run:
name: install-deps
command: yarn install --frozen-lockfile
- save_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
paths:
- ./node_modules
- ~/.cache/yarn
- run:
name: build
command: yarn polkadot-dev-circleci-build
+1
View File
@@ -1,3 +1,4 @@
.eslintrc.js
**/build/*
**/coverage/*
**/node_modules/*
+1 -1
View File
@@ -5,7 +5,7 @@ module.exports = {
parserOptions: {
...base.parserOptions,
project: [
'./tsconfig.eslint.json'
'./tsconfig.json'
]
}
};
+18
View File
@@ -0,0 +1,18 @@
name: PR
on: [pull_request]
jobs:
pr:
strategy:
matrix:
step: ['lint', 'test', 'build', 'docs']
name: ${{ matrix.step }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: ${{ matrix.step }}
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
+35
View File
@@ -0,0 +1,35 @@
name: Master
on:
push:
branches:
- master
jobs:
master:
strategy:
matrix:
step: ['build:release', 'docs:release']
name: ${{ matrix.step }}
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
with:
token: ${{ secrets.GH_PAT }}
- name: ${{ matrix.step }}
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAGES_SRC: build-docs
GH_PAT: ${{ secrets.GH_PAT }}
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
dummy:
runs-on: ubuntu-latest
steps:
- name: dummy
run: |
echo "Dummy skip step"
+6
View File
@@ -12,6 +12,10 @@ tmp/
.env.test.local
.env.production.local
.npmrc
.yarn/*
!.yarn/releases
!.yarn/plugins
.pnp.*
cc-test-reporter
lerna-debug.log*
npm-debug.log*
@@ -20,3 +24,5 @@ yarn-debug.log*
yarn-error.log*
store.db
store.db.compacted
.idea
.vscode
-28
View File
@@ -1,28 +0,0 @@
language: node_js
node_js:
- "10"
env:
global:
- CC_TEST_REPORTER_ID=27a299582eb7fd9580e27897a6ecda1c82a1cd24bcfe2f2ebda1ca70238509b4
- GH_PAGES_SRC="build-docs"
cache:
yarn: true
directories:
- node_modules
before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- export PATH=$HOME/.yarn/bin:$(yarn global bin):$PATH
before_script:
- ./cc-test-reporter before-build
script:
- yarn polkadot-dev-travis-build
after_script:
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
deploy:
skip_cleanup: true
provider: script
script: yarn polkadot-dev-travis-deploy
on:
branch: master
File diff suppressed because one or more lines are too long
Vendored Executable
+56
View File
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
enableImmutableInstalls: false
enableProgressBars: false
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
spec: "@yarnpkg/plugin-interactive-tools"
yarnPath: .yarn/releases/yarn-rc.js
+203 -21
View File
@@ -1,22 +1,140 @@
# 1.3.1
# CHANGELOG
- Remove the `ExtError` class, always prefer the standard JS `Error` object for errors. This would bre a breaking change for any appliactions using `ExtError`
## 2.12.2 Jun 1, 2020
# 1.2.1
- Fix `isFunction` signature to assert `Function`
## 2.12.1 Jun 1, 2020
- **Important** Removed `mnemonicToSeed`, it is only for bip39, use `mnemonicToMiniSecret` for the Substrate variant
- Added `u8aEq` to compare two Uint8Array or hex values for an exact match
- Added `addressEq` to compare two addresses (ss58, Uint8array or hex) for an exact match
- Throw error on `{nacl,schnorrkel}Verify` on invalid input lengths
- Performance optimizations in `u8aToHex` & `u8aConcat`
## 2.11.1 May 26, 2020
- Internal cleanups on typings
- Support for latest TypeScript, eslint & typescript-eslint
## 2.10.1 May 14, 2020
- Add Kulupu ss58 prefix as an allowed value (Thanks to https://github.com/sorpaas)
- Make the `TextEncoder` polyfill handle non-compliant Buffer implementations (newer versions of Jest)
- `DeriveJunction` now also allows for BigInt values (aligning with number types elsewhere)
- Small code-flow optimizations
## 2.9.1 Apr 30, 2020
- Add support for ECDSA keypairs (Thanks to https://github.com/akru)
- Added `createKeyMulti` & `createKeySub` to create utility sub & multi keys
- Added `u8aSorted` to sort `Uint8Arrays`
- Added `sortAddresses` to sort addresses based on their internal representation
## 2.8.1 Apr 9, 2020
- Keypair will now throw an error when attempting to sign/derive using a locked pair (Thanks to https://github.com/h4x3rotab)
- Cleanup `isDevelopment` regex to cater for chains such as `Westend Development`
## 2.7.1 Mar 31, 2020
- Add `bnSqrt` to calculate the integer sqrt via Newton iteration
- Allow for optional wasm-crypto, specifically via `@polkadot/util-crypto/noWasm`
- Misc. CI infrastructure cleanups
## 2.6.1 Feb 29, 2020
- **Breaking change** Following on the 2.0 release, `@polkadot/wasm` was updated to 1.1+. sr25510 now only verifies 0.8+ signatures, closing the loop on dropping Substrate 1.x-era support
- Add `signatureVerify (message: Uint8Array | string, signature: Uint8Array | string, addressOrPublicKey: Uint8Array | string): VerifyResult` to verify any signature, regardless of type. Returns validity & detected crypto type.
- Add `cryptoIsReady (): boolean` function to check status of initialization
- Add `addressCheckChecksum (decoded: Uint8Array)` as an helper to extract and verify the ss58 checksum
- Swap to yarn 2, allow use in yarn 2 projects
## 2.5.1 Feb 22, 2020
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features, `#private`, which is not usable in older versions
- Add `isBigInt(value)` to allow `BigInt` checks. Also add support in `bnToBn` as well as number conversion utils
- Add `isChildClass(Parent, Child?)` to check if a class extends the parent, asserting Child is Parent
- (internal) Use `#<field>` instead of `private _<field>` for private class variables
## 2.4.1 Feb 18, 2020
- Ensure that `formatBalance` does not apply unit overrides apply when no SI is applicable
- Adjust `formatBalance(<balance>, <options>)` to take expanded `withUnit: string | boolean` option where string is an actual unit, e.g. `KSM`
- The `decimals` option to `formatBalance` should now be passed as part of the `options` (previous last-param deprecated)
- The `.setSS58Format` on keyring will now just operate on pairs created on the keyring, not globally. The global `setSS58Format` in `@polkadot/util-crypto` will be deprecated.
- The deprecated `addressPrefix` option to keyring has been belatedly removed (Use `ss58Format` rather)
## 2.3.1 Feb 15, 2020
- Remove dependency on moment.js with `formatDate` function (Thanks to https://github.com/AndreasGassmann)
- Move TypeScript `@types/*` to dev deps (Thanks to https://github.com/AndreasGassmann)
- Update to `@polkadot/wasm-crypto` 1.0
- Cleanup dependencies to pave the way for using yarn 2 (Explicit instead of implicit)
## 2.2.1 Feb 06, 2020
- Add resolver for jest requires (tests from src)
## 2.1.1 Feb 04, 2020
- Update `detectPackage(<package.json>, __dirname?)` with calling folder
## 2.0.1 Jan 30, 2020
- Update w3f/schnorrkel to 0.8.5 (Full Substrate 2.x support, no 1.x support)
- Remove Alice session (ed2551) account from testing keyring (not applicable to Substrate 2.x)
- Remove `chainspec`, `db`, `trie-codec`, `trie-db` and `trie-hash` packages (moved to client)
- Renamed `assertSingletonPackage` to `detectPackage` with inclusion of version listing
- Swap to elliptic library for secp2561 recovery (No node bindings)
## 1.8.1 Jan 09, 2020
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)
## 1.7.1 Nov 27, 2019
- `formatBalance` signature now allows to force unit displays
- Keypair now allows for derive on a pair, with `pair.derive(...)`
- `assert` now acts like a real asserts, with no return - signature adapted for new TS 3.7
## 1.6.1 Oct 24, 2019
- `pair.sign(message)` now takes an optional second `options?: SignOptions` parameter, where `SignOptions` is currently defined as `{ withType: boolean }`. Here `withType` instructs the signing to prepend the type of signature (ed2551, sr25519 or ecdsa). This is used for the new Polkadot/Substrate MultiSignature format.
## 1.5.1 Sep 25, 2019
- Fix typings on the Keyring-exposed encode & decodeAddress
- Allow ss58Format = 0 as a valid value
- Loosen type definitions for allowed ss58format values (still checked against allowed array)
## 1.4.1 Sep 12, 2019
- **Breaking change** To set the `ss58Format`, you should now use `setSS58Format` as opposed to the old `setAddressPrefix`
- Renamed `keyring.setAddressPrefix` to `keyring.setSS58Format`
- Deprecated `addressPrefix` on the keyring options, added the `ss58Format` as a replacement (aligning with chain properties - the old version is still accepted)
- Added `stringToHex` and `hexToString` conversion utilities to `@polkadot/util`
- Swap to [Babel 7.6.0](https://babeljs.io/) for all compilation, for latest improvements in code generation
## 1.3.1 Sep 10, 2019
- Remove the `ExtError` class, always prefer the standard JS `Error` object for errors. This would bre a breaking change for any applications using `ExtError`
## 1.2.1 Sep 09, 2019
- Keyring `addFromAddress` can now be used to store external accounts, for example those provided by external signers
- Maintainability updates
# 1.1.1
## 1.1.1 Aug 09, 2019
- `assertSingletonPackage` now warns via console.warn, but does not throw. This does allow the info to come accross while still allowing the app developers using multiple libraries time to fix.
# 1.0.1
## 1.0.1 Aug 02, 2019
- `formatBalance` now allows for `Compact` inputs
- `formaBalance` now allows correct formatting of very large decimals
# 0.94.1
### 0.94.1 Jul 20, 2019
- Add `checkAddress(address, prefix)` to `@polkadot/util-crypto` that validates an ss-58 address
- Add support for the Kusama network (as a valid checked prefix)
@@ -24,7 +142,7 @@
- The ed25519 key for Alice (representing the session), now appears in the test keyrings
- Fix missing dependencies for keyring (after address moves in 0.93.1)
# 0.93.1
### 0.93.1 Jun 14, 2019
- Breaking: External pair interface for keyring has been changed. Instead of
- `getMeta` use the `meta` getter, i.e. `console.log(pair.meta.name)`
@@ -32,69 +150,133 @@
- `publicKey` use the `publicKey` getter, i.e. `console.log(pair.publicKey)`
- `Move decodeAddress`, `encodeAddress` & `setAddressPrefix` functions into `@polkadot/util-crypto` from `@polkadot/keyring`. External interfaces should not be affected at this point since it is also (still) exported and exposed on keyring
# 0.92.1
### 0.92.1 Jun 04, 2019
- Only allow integer input values into `formatBalance`
- Allow `formatBalance`, `formatDecimal` & `formatNumber` to cater for negative numbers
- Add 'Bob//stash' to testing keyring, joining the existing 'Alice//stash'
# 0.91.1
### 0.91.1 May 22, 2019
- ed25519/sr25519 sign & verify functions can now take the message input as Uint8Array/string/hex and verify allows for the signature/publicKey to be specified as Uint8Array/hex
- Update `@polkadot/wasm` to include a maintenance bump for the `w3f/schnorrkel` libraries
# 0.90.1
### 0.90.1 May 08, 2019
- Moving towards 1.0
- Added bnMin & bnMax functions
# 0.76.1
### 0.76.1 Apr 03, 2019
- Fix `addFromMnemonic` to generate using new-style derivation.
- Pull in `formatBalance`, `formatDecimal`, `formatElapsed`, `formatNumber`, `calcSi`, `findSi` & `isTestChain` utility functions from the originals in `@polkadot/ui-util`
- Swap out `wasm-schnorrkel` & `wasm-ed25519` for combined version with `wasm-crypto`
- Swap DB interfaces to optional LRU, removing `transactionAsync` (client-only changes)
# 0.75.1
### 0.75.1 Mar 29, 2019
- Start journey to 1.0
# 0.42.1
### 0.42.1 Mar 28, 2019
- Add `assertSingletonPackage` to util
- Ensure that only a single keyring instance is loaded (uses above)
# 0.41.1
### 0.41.1 Mar 25, 2019
- Extensions to the client-specific database interfaces (non-breaking for API and util users)
# 0.40.1
### 0.40.1 Mar 23, 2019
- Add additional derivation path extraction mechanisms to util-crypto
- Add createFromUri function to keypair (creates keypair, does not add it)
- Allow all crypto hashing & ed25519 to use WASM (as available, JS fallbacks)
# 0.39.1
### 0.39.1 Mar 20, 2019
- Pull in bip39 generation functions from `@poladkot/wasm-crypto` with a fallback to the pure JS versions
# 0.38.1
### 0.38.1 Mar 18, 2019
- Align with current substrate master for sr25519 keys and hard/soft derivation
- Swap default dev keys to derived (sr25519)
# 0.37.1
### 0.37.1 Mar 14, 2019
- Swap to publishing -beta.x on merge (non-breaking testing)
# 0.36.1
### 0.36.1 Mar 13, 2019
- Add `fromUri` to keyring along with hard & soft key derivation.
# 0.35.1
### 0.35.1 Mar 04, 2019
- Remove NodeJs-only `syncify` function, not exported by the package (with binary dependency for Node)
# 0.34.1
### 0.34.1 Feb 13, 2019
- Keyring now allows for ed25519 and sr25519 instances. Upon creation, you need to pass the `ed25519`or `sr25519` string to denote the type, i.e. `new Keyring({ type: 'sr25519' })`
### 0.33.1 Nov 22, 2018
### 0.32.1 Oct 18, 2018
### 0.31.1 Oct 12, 2018
### 0.30.1 Sep 11, 2018
### 0.29.1 Sep 01, 2018
### 0.28.1 Aug 11, 2018
### 0.27.1 Aug 06, 2018
### 0.26.1 Jun 27, 2018
### 0.25.1 Jun 26, 2018
### 0.24.1 Jun 22, 2018
### 0.23.1 Jun 21, 2018
### 0.22.1 May 24, 2018
### 0.21.1 May 17, 2018
### 0.20.1 May 16, 2018
### 0.19.1 Apr 19, 2018
### 0.18.1 Mar 20, 2018
### 0.17.1 Mar0 8, 2018
### 0.16.1 Feb 23, 2018
### 0.15.1 Feb 15, 2018
### 0.14.1 Feb 07, 2018
### 0.13.1 Jan 25, 2018
### 0.12.1 Jan 11, 2018
### 0.11.1 Dec 30, 2017
### 0.10.1 Dec 17, 2017
### 0.9.1 Dec 14, 2017
### 0.8.1 Dec 12, 2017
### 0.7.1 Dec 11, 2017
### 0.6.1 Nov 30, 2017
### 0.5.1 Nov 20, 2017
### 0.4.1 Nov 19, 2017
### 0.3.1 Nov 19, 2017
### 0.2.1 Nov 18, 2017
-7
View File
@@ -16,13 +16,6 @@ This repository 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-rlp](packages/util-rlp/) RLP encoding & decoding
Various useful trie and database interfaces -
- [db](packages/db/) Sync memory and disk database interfaces
- [trie-db](packages/trie-db/) Merkle Patricia Tree implementation adapted for Polkadot
- [trie-hash](packages/trie-hash/) Calculate hashes (either ordered or unordered) from a set of inputs
## development
+5 -3
View File
@@ -1,3 +1,5 @@
module.exports = {
extends: '@polkadot/dev/config/babel'
};
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
module.exports = require('@polkadot/dev/config/babel');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
// Import Keyring class and utility function
const Keyring = require('@polkadot/keyring').default;
const stringToU8a = require('@polkadot/util/string/toU8a').default;
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
// Import Keyring class and utility function
const Keyring = require('@polkadot/keyring').default;
const stringToU8a = require('@polkadot/util/string/toU8a').default;
@@ -1,12 +1,18 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const { encodeAddress, decodeAddress } = require('@polkadot/keyring');
const { isHex, hexToU8a } = require('@polkadot/util');
/* eslint-disable header/header */
const { decodeAddress, encodeAddress } = require('@polkadot/keyring');
const { hexToU8a, isHex } = require('@polkadot/util');
const address = '5GrpknVvGGrGH3EFuURXeMrWHvbpj3VfER1oX5jFtuGbfzCE';
const isValidAddressPolkadotAddress = () => {
try {
encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));
encodeAddress(
isHex(address)
? hexToU8a(address)
: decodeAddress(address)
);
return true;
} catch (error) {
return false;
@@ -1,7 +1,8 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
const { naclEncrypt, naclDecrypt } = require('@polkadot/util-crypto');
const { naclDecrypt, naclEncrypt } = require('@polkadot/util-crypto');
async function main () {
const secret = new Uint8Array(32);
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
const { stringToU8a, u8aToHex } = require('@polkadot/util');
const { naclEncrypt, naclKeypairFromSeed, naclSign, naclVerify, randomAsU8a } = require('@polkadot/util-crypto');
@@ -9,7 +10,7 @@ async function main () {
const seedAlice = 'Alice'.padEnd(32, ' ');
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(stringToU8a(seedAlice));
const { publicKey, secretKey } = naclKeypairFromSeed(stringToU8a(seedAlice));
// Encrypt message. Create Uint8Array's filled with random bytes of specified length
const secret = randomAsU8a(32);
@@ -1,6 +1,8 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-var-requires,@typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
const { mnemonicGenerate, mnemonicToSeed, mnemonicValidate, naclKeypairFromSeed } = require('@polkadot/util-crypto');
async function main () {
@@ -19,7 +21,7 @@ async function main () {
const seedAlice = mnemonicToSeed(mnemonicAlice);
// Generate new public/secret keypair for Alice from the supplied seed
const { secretKey, publicKey } = naclKeypairFromSeed(seedAlice);
const { publicKey, secretKey } = naclKeypairFromSeed(seedAlice);
// Encrypt, Sign and Validate the message. See Example 'Sign & Verify Message'
}
@@ -0,0 +1,5 @@
# Generate a Multisig Account
Substrate provides a multisig dispatch function in its
[Utility pallet](https://crates.parity.io/pallet_utility/index.html). This example generates the
address that would correspond to a set of addresses and threshold.
@@ -0,0 +1,40 @@
/* eslint-disable header/header */
import { createKeyMulti, encodeAddress, sortAddresses } from '@polkadot/util-crypto';
const SS58Prefix = 0;
// Input the addresses that will make up the multisig account.
const addresses = [
'1nUC7afqmo7zwRFWxDjrUQu9skk6fk99pafb4SiyGSRc8z3',
'1ZX2XntfLEHrBPy73DpfQp9rG7pbLyvrFjEpi7mNKQgyga5',
'14b1kB7CrqzRUeMsKc26FJ73f8FCpxAX6sNieu9gfYSfJuoL'
];
// The number of accounts that must approve. Must be greater than 0 and less than
// or equal to the total number of addresses.
const threshold = 2;
// The address (as index in `addresses`) that will submit a transaction.
const index = 0;
function main () {
// Address as a byte array.
const multiAddress = createKeyMulti(addresses, threshold);
// Convert byte array to SS58 encoding.
const Ss58Address = encodeAddress(multiAddress, SS58Prefix);
console.log(`\nMultisig Address: ${Ss58Address}`);
// Take addresses and remove the sender.
const otherSignatories = addresses.filter((who) => who !== addresses[index]);
// Sort them by public key.
const otherSignatoriesSorted = sortAddresses(otherSignatories, SS58Prefix);
console.log(`\nOther Signatories: ${otherSignatoriesSorted}\n`);
process.exit();
}
main();
@@ -0,0 +1,14 @@
{
"name": "04_generate_multisig_address",
"version": "0.1.0",
"description": "Example showing how to generate a multisig address for Substrate's Utility pallet",
"main": "index.js",
"author": "joepetrowski",
"license": "MIT",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@polkadot/util-crypto": "^2.9.0-beta.1"
}
}
+9 -13
View File
@@ -1,24 +1,20 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const config = require('@polkadot/dev/config/jest');
module.exports = Object.assign({}, config, {
moduleNameMapper: {
'@polkadot/chainspec(.*)$': '<rootDir>/packages/chainspec/src/$1',
'@polkadot/db(.*)$': '<rootDir>/packages/db/src/$1',
'@polkadot/keyring(.*)$': '<rootDir>/packages/keyring/src/$1',
'@polkadot/trie-(codec|db|hash)(.*)$': '<rootDir>/packages/trie-$1/src/$2',
'@polkadot/util-(crypto|rlp)(.*)$': '<rootDir>/packages/util-$1/src/$2',
'@polkadot/util-(crypto)(.*)$': '<rootDir>/packages/util-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/db/build',
'<rootDir>/packages/chainspec/build',
'<rootDir>/packages/keyring/build',
'<rootDir>/packages/trie-codec/build',
'<rootDir>/packages/trie-db/build',
'<rootDir>/packages/trie-hash/build',
'<rootDir>/packages/util/build',
'<rootDir>/packages/util-crypto/build',
'<rootDir>/packages/util-rlp/build'
]
'<rootDir>/packages/util-crypto/build'
],
resolver: './jest.resolver.js'
});
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const path = require('path');
module.exports = function resolver (file, config) {
return file.includes('package.json')
? path.join(config.basedir.replace('/src', '/'), file)
: config.defaultResolver(file, config);
};
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.3.1"
"version": "2.12.2"
}
+17 -16
View File
@@ -1,29 +1,30 @@
{
"version": "1.3.1",
"repository": "https://github.com/polkadot-js/common",
"author": "Jaco Greeff <jacogr@gmail.com>",
"license": "Apache-2",
"private": true,
"engines": {
"yarn": "^1.10.1"
},
"workspaces": [
"packages/*"
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.6.2"
"babel-core": "^7.0.0-bridge.0"
},
"scripts": {
"build": "polkadot-dev-build-ts && polkadot-dev-build-docs",
"check": "yarn lint",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"build": "polkadot-dev-build-ts",
"build:release": "polkadot-ci-ghact-build",
"docs": "polkadot-dev-build-docs",
"docs:release": "polkadot-ci-ghact-docs",
"lint": "polkadot-dev-run-lint",
"clean": "polkadot-dev-clean-build",
"postinstall": "polkadot-dev-yarn-only",
"test": "jest --coverage --runInBand",
"test:one": "jest"
"test": "polkadot-dev-run-test --coverage --runInBand",
"test:one": "polkadot-dev-run-test"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@polkadot/dev": "^0.31.0-beta.7",
"@polkadot/ts": "^0.1.71",
"gh-pages": "^2.1.1"
}
"@babel/core": "^7.9.6",
"@polkadot/dev": "^0.55.6",
"@polkadot/ts": "^0.3.25",
"@types/jest": "^25.2.3"
},
"version": "2.12.2"
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-7
View File
@@ -1,7 +0,0 @@
# @polkadot/chainspec
Chainspecs for known chains
## Utilities
[Utilities](SUMMARY.md)
-31
View File
@@ -1,31 +0,0 @@
{
"name": "@polkadot/chainspec",
"version": "1.3.1",
"description": "Contains chain specifications for known chains",
"main": "index.js",
"keywords": [
"Polkadot"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/common.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/chainspec#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.3.1"
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-6
View File
@@ -1,6 +0,0 @@
// Copyright 2017-2019 @polkadot/chainspec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as alexander } from './alexander';
export { default as driedDanta } from './dried-danta';
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2017-2019 @polkadot/chainspec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export type Telemetry = [string, number];
export interface Chainspec {
bootNodes: string[];
id: string;
genesis: {
raw: Record<string, string>;
};
genesisRoot?: string;
name: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
properties: null | Record<string, any>;
protocolId: string | null;
telemetryUrl?: string | null;
telemetryEndpoints?: Telemetry[];
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-24
View File
@@ -1,24 +0,0 @@
# @polkadot/db
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';
```
## Utilities
[Utilities](SUMMARY.md)
-33
View File
@@ -1,33 +0,0 @@
{
"name": "@polkadot/db",
"version": "1.3.1",
"description": "Implementation of a basic sync in-memory and on-disk databases with overlays",
"main": "index.js",
"keywords": [
"Polkadot"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/common.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/db#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/trie-hash": "^1.3.1",
"@polkadot/util": "^1.3.1",
"lru_map": "^0.3.3"
}
}
-68
View File
@@ -1,68 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
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
* <BR>
*
* ```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((): void => {
* 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 {
public constructor () {
super(new MemoryDb());
}
}
-63
View File
@@ -1,63 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import LruDb from './LruDb';
import MemoryDb from './MemoryDb';
describe('LruDb', (): void => {
const memory = new MemoryDb();
const db = new LruDb(memory);
it('retrieves an item from the backing when not available (caching it)', (): void => {
const key = toU8a('test1');
const value = toU8a('value1');
memory.put(key, value);
expect(db.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('replaces an item (caching and backing)', (): void => {
const key = toU8a('test1');
const value = toU8a('test');
db.put(key, value);
expect(db.get(key)).toEqual(value);
expect(memory.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('retrieves item from LRU when available', (): void => {
const key = toU8a('test1');
const value = toU8a('test');
memory.del(key);
expect(db.get(key)).toEqual(value);
});
it('puts item both in LRU and backing', (): void => {
const key = toU8a('test0');
const value = toU8a('value0');
db.put(key, value);
expect(memory.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('deletes an item from both backing and db', (): void => {
const key = toU8a('test0');
db.del(key);
expect(memory.get(key)).toEqual(null);
expect(db._getLru(key)).toEqual({ value: null });
expect(db.get(key)).toEqual(null);
});
});
-116
View File
@@ -1,116 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, ProgressCb } from '../types';
import { LRUMap } from 'lru_map';
import { logger } from '@polkadot/util';
interface CachedValue {
value: Uint8Array | null;
}
const DEFAULT_ITEM_COUNT = 4096;
const l = logger('db/lru');
export default class LruDb implements BaseDb {
private backing: BaseDb;
private lru: LRUMap<string, CachedValue>;
public constructor (backing: BaseDb, itemCount: number = DEFAULT_ITEM_COUNT) {
this.backing = backing;
this.lru = new LRUMap(itemCount);
}
public close (): void {
l.debug((): string[] => ['close']);
this.lru.clear();
this.backing.close();
}
public open (): void {
l.debug((): string[] => ['open']);
this.lru.clear();
this.backing.open();
}
public drop (): void {
this.backing.drop();
}
public empty (): void {
l.debug((): string[] => ['empty']);
this.lru.clear();
this.backing.empty();
}
public rename (base: string, file: string): void {
this.backing.rename(base, file);
}
public maintain (fn: ProgressCb): void {
this.backing.maintain(fn);
}
public size (): number {
return this.backing.size();
}
public del (key: Uint8Array): void {
const keyStr = key.toString();
this.backing.del(key);
this.lru.set(keyStr, { value: null });
}
public get (key: Uint8Array): Uint8Array | null {
const keyStr = key.toString();
const cached = this.lru.get(keyStr);
if (cached) {
return cached.value;
}
const value = this.backing.get(key);
this.lru.set(keyStr, { value });
return value;
}
// Convenience methods used in tests
public _getLru (key: Uint8Array): CachedValue | undefined {
return this.lru.get(key.toString());
}
public put (key: Uint8Array, value: Uint8Array): void {
const keyStr = key.toString();
this.backing.put(key, value);
this.lru.set(keyStr, { value });
}
public txCommit (): void {
if (this.backing.txCommit) {
this.backing.txCommit();
}
}
public txRevert (): void {
if (this.backing.txRevert) {
this.backing.txRevert();
}
}
public txStart (): void {
if (this.backing.txStart) {
this.backing.txStart();
}
}
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import MemoryDb from './MemoryDb';
describe('MemoryDb', (): void => {
const memory = new MemoryDb();
it('gets the combioned size of the entry values', (): void => {
memory.put(new Uint8Array([1]), new Uint8Array([1, 2, 3]));
memory.put(new Uint8Array([2]), new Uint8Array([1, 2, 3]));
memory.put(new Uint8Array([3]), new Uint8Array([1, 2, 3]));
expect(memory.size()).toEqual(9);
});
it('does not throw on the stubs', (done): void => {
memory.close();
memory.open();
memory.drop();
memory.empty();
memory.rename('foo', 'bar');
memory.maintain((): void => done());
});
});
-70
View File
@@ -1,70 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, ProgressCb } from '../types';
import { logger } from '@polkadot/util';
const l = logger('db/memory');
export default class MemoryDb implements BaseDb {
private _storage: Map<string, Uint8Array> = new Map();
public close (): void {
this.empty();
}
public open (): void {
this.empty();
}
public drop (): void {
this.empty();
}
public empty (): void {
this._storage.clear();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public rename (base: string, file: string): void {
l.warn('rename() is not implemented');
}
public maintain (fn: ProgressCb): void {
fn({
isCompleted: true,
keys: this._storage.size,
percent: 100
});
}
public size (): number {
let size = 0;
this._storage.forEach((value): void => {
size += value.length;
});
return size;
}
public del (key: Uint8Array): void {
// l.debug(() => ['del', { key }]);
this._storage.delete(key.toString());
}
public get (key: Uint8Array): Uint8Array | null {
// l.debug(() => ['get', { key }]);
return this._storage.get(key.toString()) || null;
}
public put (key: Uint8Array, value: Uint8Array): void {
// l.debug(() => ['put', { key, value }]);
this._storage.set(key.toString(), value);
}
}
@@ -1,93 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/string/toU8a';
import MemoryDb from './MemoryDb';
import TransactionDb from './TransactionDb';
describe('TransactionDb', (): void => {
const memory = new MemoryDb();
const db = new TransactionDb(memory);
it('passed through values immediately when not in transaction', (): void => {
const key = toU8a('test0');
const value = toU8a('value0');
db.put(key, value);
expect(memory.get(key)).toEqual(value);
});
it('commits when transaction passes (result = true, put)', (): void => {
const key = toU8a('test1');
const value = toU8a('value1');
expect(
db.transaction((): boolean => {
db.put(key, value);
return true;
})
).toEqual(true);
expect(memory.get(key)).toEqual(value);
});
it('commits when transaction passes (result = true, del)', (): void => {
const key = toU8a('test0');
expect(
db.transaction((): boolean => {
db.del(key);
return true;
})
).toEqual(true);
expect(memory.get(key)).toEqual(null);
});
it('does not commit when transaction fails (result = false)', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
expect(
db.transaction((): boolean => {
db.put(key, value);
return false;
})
).toEqual(false);
expect(memory.get(key)).toEqual(null);
});
it('does not commit when transaction throws', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
expect(
(): void => {
db.transaction((): void => {
db.put(key, value);
throw new Error('test');
});
}
).toThrow(/test/);
expect(memory.get(key)).toEqual(null);
});
it('inside the transaction, the value is set', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
db.transaction((): boolean => {
db.put(key, value);
expect(db.get(key)).toEqual(value);
return false;
});
expect(memory.get(key)).toEqual(null);
});
});
-157
View File
@@ -1,157 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, TxDb, ProgressCb } from '../types';
import { assert, isNull, logger } from '@polkadot/util';
interface OverlayItem {
key: Uint8Array;
value: Uint8Array | null;
}
const l = logger('db/transact');
export default class TransactionDb implements TxDb {
private backing: BaseDb;
private txOverlay: Map<string, OverlayItem> = new Map();
private txStarted: boolean;
public constructor (backing: BaseDb) {
this.backing = backing;
this.txStarted = false;
}
public transaction<T> (fn: () => T): T {
l.debug((): string[] => ['transaction']);
try {
this.createTx();
const result = fn();
if (result) {
this.commitTx();
} else {
this.revertTx();
}
return result;
} catch (error) {
this.revertTx();
throw error;
}
}
public close (): void {
this.backing.close();
}
public open (): void {
this.backing.open();
}
public drop (): void {
this.backing.drop();
}
public empty (): void {
this.backing.empty();
}
public rename (base: string, file: string): void {
this.backing.rename(base, file);
}
public maintain (fn: ProgressCb): void {
assert(this.txStarted === false, 'Cannot maintain inside an open transaction');
this.backing.maintain(fn);
}
public size (): number {
return this.backing.size();
}
public del (key: Uint8Array): void {
if (this.txStarted) {
this.txOverlay.set(key.toString(), { key, value: null });
return;
}
this.backing.del(key);
}
public get (key: Uint8Array): Uint8Array | null {
// l.debug(() => ['get', u8aToHex(key)]);
if (this.txStarted) {
const value = this.txOverlay.get(key.toString());
if (value) {
return value.value;
}
}
return this.backing.get(key);
}
public put (key: Uint8Array, value: Uint8Array): void {
// l.debug(() => ['put', u8aToHex(key), u8aToHex(value)]);
if (this.txStarted) {
this.txOverlay.set(key.toString(), { key, value });
return;
}
return this.backing.put(key, value);
}
private createTx (): void {
l.debug((): string[] => ['createTx']);
assert(!this.txStarted, 'Cannot create a transaction when one is already active');
this.txOverlay.clear();
this.txStarted = true;
}
private commitTx (): void {
l.debug((): [string, number, string] => ['commitTx', Object.keys(this.txOverlay).length, 'keys']);
assert(this.txStarted, 'Cannot commit when not in transaction');
if (this.backing.txStart) {
this.backing.txStart();
}
this.txOverlay.forEach(({ key, value }): void => {
if (isNull(value)) {
this.backing.del(key);
} else {
this.backing.put(key, value);
}
});
if (this.backing.txCommit) {
this.backing.txCommit();
}
this.txOverlay.clear();
this.txStarted = false;
}
private revertTx (): void {
l.debug((): string[] => ['revertTx']);
assert(this.txStarted, 'Cannot revert when not in transaction');
this.txOverlay.clear();
this.txStarted = false;
}
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface ProgressValue {
isCompleted?: boolean;
keys: number;
percent: number;
}
export type ProgressCb = (progress: ProgressValue) => void;
export interface BaseDbOptions {
isCompressed?: boolean;
isLru?: boolean;
isNative?: boolean;
}
export interface BaseDb {
close (): void;
open (): void;
drop (): void;
empty (): void;
maintain (fn: ProgressCb): void;
rename (base: string, file: string): void;
size (): number;
txCommit?: () => void;
txRevert?: () => void;
txStart?: () => void;
del (key: Uint8Array): void;
get (key: Uint8Array): Uint8Array | null;
put (key: Uint8Array, value: Uint8Array): void;
}
export interface TxDb extends BaseDb {
transaction <T> (fn: () => T): T;
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "1.3.1",
"version": "2.12.2",
"description": "Keyring management",
"main": "index.js",
"publishConfig": {
@@ -27,8 +27,8 @@
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.3.1",
"@polkadot/util-crypto": "^1.3.1"
"@babel/runtime": "^7.9.6",
"@polkadot/util": "2.12.2",
"@polkadot/util-crypto": "2.12.2"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+96 -29
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { cryptoWaitReady, setAddressPrefix } from '@polkadot/util-crypto';
import { cryptoWaitReady, setSS58Format, encodeAddress } from '@polkadot/util-crypto';
import Keyring from '.';
@@ -17,53 +17,55 @@ describe('keypair', (): void => {
const publicKeyTwo = new Uint8Array([215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26]);
const seedOne = stringToU8a('12345678901234567890123456789012');
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
let keyring: Keyring;
beforeEach((): void => {
keypair = new Keyring({ type: 'ed25519' });
keyring = new Keyring({ ss58Format: 42, type: 'ed25519' });
keypair.addFromSeed(seedOne, {});
keyring.addFromSeed(seedOne, {});
});
it('adds the pair', (): void => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey
keyring.addFromSeed(seedTwo, {}).publicKey
).toEqual(publicKeyTwo);
});
it('creates a ed25519 pair via mnemonicToSeed', (): void => {
expect(
keypair.addFromUri(
keyring.addFromUri(
'seed sock milk update focus rotate barely fade car face mechanic mercy'
).address
).toEqual('5DkQP32jP4DVJLWWBRBoZF2tpWjqFrcrTBo6H5NcSk7MxKCC');
});
it('adds from a mnemonic', (): void => {
setAddressPrefix(68);
it('adds from a mnemonic, with correct ss58', (): void => {
setSS58Format(20); // this would not be used
keyring.setSS58Format(68); // this would be used
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
const pair = keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {});
expect(pair.address).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
expect(encodeAddress(pair.publicKey)).toEqual('35cDYtPsdG1HUa2n2MaARgJyRz1WKMBZK1DL6c5cX7nugQh1');
});
it('allows publicKeys retrieval', (): void => {
keypair.addFromSeed(seedTwo, {});
keyring.addFromSeed(seedTwo, {});
expect(
keypair.getPublicKeys()
keyring.getPublicKeys()
).toEqual([publicKeyOne, publicKeyTwo]);
});
it('allows retrieval of a specific item', (): void => {
expect(
keypair.getPair(publicKeyOne).publicKey
keyring.getPair(publicKeyOne).publicKey
).toEqual(publicKeyOne);
});
it('allows adding from JSON', (): void => {
expect(
keypair.addFromJson(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
).publicKey
).toEqual(
@@ -73,7 +75,7 @@ describe('keypair', (): void => {
it('signs and verifies', (): void => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const pair = keyring.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
@@ -85,51 +87,51 @@ describe('keypair', (): void => {
const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f');
const seedOne = stringToU8a('12345678901234567890123456789012');
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
let keyring: Keyring;
beforeEach((): void => {
keypair = new Keyring({ type: 'sr25519' });
keyring = new Keyring({ ss58Format: 42, type: 'sr25519' });
keypair.addFromSeed(seedOne, {});
keyring.addFromSeed(seedOne, {});
});
it('creates with dev phrase when only path specified', (): void => {
expect(
keypair.createFromUri('//Alice').address
keyring.createFromUri('//Alice').address
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
it('adds the pair', (): void => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey
keyring.addFromSeed(seedTwo, {}).publicKey
).toEqual(publicKeyTwo);
});
it('adds from a mnemonic', (): void => {
setAddressPrefix(68);
keyring.setSS58Format(68);
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ');
});
it('allows publicKeys retrieval', (): void => {
keypair.addFromSeed(seedTwo, {});
keyring.addFromSeed(seedTwo, {});
expect(
keypair.getPublicKeys()
keyring.getPublicKeys()
).toEqual([publicKeyOne, publicKeyTwo]);
});
it('allows retrieval of a specific item', (): void => {
expect(
keypair.getPair(publicKeyOne).publicKey
keyring.getPair(publicKeyOne).publicKey
).toEqual(publicKeyOne);
});
it('allows adding from JSON', (): void => {
expect(
keypair.addFromJson(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
).publicKey
).toEqual(
@@ -139,7 +141,72 @@ describe('keypair', (): void => {
it('signs and verifies', (): void => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const pair = keyring.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
});
});
describe('ecdsa', (): void => {
const seedOne = 'potato act energy ahead stone taxi receive fame gossip equip chest round';
const seedTwo = hexToU8a('0x3c74be003bd9a876be439949ccf2b292bd966c94959a689173b295b326cd6da7');
const publicKeyOne = hexToU8a('0x02c6b6c664db5ef505477bba1cf2f1789c98796b9bb5fa21abd0ac4589bed980e7');
const publicKeyTwo = hexToU8a('0x021da683b913fb28c979ba3e5f1881415cef4b1f58a5d05ed3610a2995e7b4943c');
const addressKeyOne = hexToU8a('0x0cfd0dd2c59a9987b9848919163931b6a42283ffd3d91e92c98b522525a7038f');
let keyring: Keyring;
beforeEach((): void => {
keyring = new Keyring({ ss58Format: 42, type: 'ecdsa' });
keyring.addFromMnemonic(seedOne, {});
});
it('creates with dev phrase when only path specified', (): void => {
expect(
keyring.createFromUri('//Alice').address
).toEqual('5C7C2Z5sWbytvHpuLTvzKunnnRwQxft1jiqrLD5rhucQ5S9X');
});
it('adds the pair', (): void => {
expect(
keyring.addFromSeed(seedTwo, {}).publicKey
).toEqual(publicKeyTwo);
});
it('adds from a mnemonic', (): void => {
keyring.setSS58Format(68);
expect(
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card').address
).toEqual('7ooxHV3mz4nnWbK8v7Mxcb71QMpof268eL1A2VrYWUNWJk8P');
});
it('allows publicKeys retrieval', (): void => {
keyring.addFromSeed(seedTwo, {});
expect(
keyring.getPublicKeys()
).toEqual([publicKeyOne, publicKeyTwo]);
});
it('allows retrieval of a specific item', (): void => {
expect(
keyring.getPair(addressKeyOne).publicKey
).toEqual(publicKeyOne);
});
it('allows adding from JSON', (): void => {
expect(
keyring.addFromJson(
JSON.parse('{"address":"5DzMsaYFhmpRdErWrP6K6PD7UXzYoeETToSBUrZSvxasqWRz","encoded":"0xa192d39b42bc1601bf61df31039a554228593fadf870bc837b658a5114627aca199fff596260c95fe8994c66a47636cf0270aa08f402ba5541038753960d00e6c3af5e239ec58fb1eef3db7d6bc266f4853bdfe4ed17122d9092d879014d53980d2ee57f6f55a88c38836447d8645008e8815379626addc8f81f80cd49a2","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"2"},"meta":{}}')
).address
).toEqual('5DzMsaYFhmpRdErWrP6K6PD7UXzYoeETToSBUrZSvxasqWRz');
});
it('signs and verifies', (): void => {
const MESSAGE = stringToU8a('this is a message');
const pair = keyring.getPair(addressKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
+6 -5
View File
@@ -1,13 +1,14 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { assertSingletonPackage } from '@polkadot/util';
import { decodeAddress, encodeAddress, setAddressPrefix } from '@polkadot/util-crypto';
import { detectPackage } from '@polkadot/util';
import { decodeAddress, encodeAddress, setSS58Format } from '@polkadot/util-crypto';
import Keyring from './keyring';
assertSingletonPackage('@polkadot/keyring');
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), typeof __dirname !== 'undefined' && __dirname);
export default Keyring;
@@ -15,5 +16,5 @@ export {
Keyring,
decodeAddress,
encodeAddress,
setAddressPrefix
setSS58Format
};
+54 -37
View File
@@ -1,12 +1,12 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeypairType } from '@polkadot/util-crypto/types';
import { KeypairType, Keypair } from '@polkadot/util-crypto/types';
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions } from './types';
import { assert, hexToU8a, isNumber, isHex, stringToU8a } from '@polkadot/util';
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret, setAddressPrefix } from '@polkadot/util-crypto';
import { assert, hexToU8a, isHex, stringToU8a } from '@polkadot/util';
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, secp256k1KeypairFromSeed as secp256k1FromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
import createPair from './pair';
@@ -29,25 +29,22 @@ import Pairs from './pairs';
* an account may be obtained using `toJson` accompanied by the account passphrase.
*/
export default class Keyring implements KeyringInstance {
private _pairs: Pairs;
readonly #pairs: Pairs;
private _type: KeypairType;
readonly #type: KeypairType;
#ss58?: number;
public decodeAddress = decodeAddress;
public encodeAddress = encodeAddress;
public setAddressPrefix = setAddressPrefix;
public constructor (options: KeyringOptions = {}) {
constructor (options: KeyringOptions = {}) {
options.type = options.type || 'ed25519';
assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`);
assert(options && ['ecdsa', 'ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519', 'sr25519' or 'ecdsa', found '${options.type}`);
this._pairs = new Pairs();
this._type = options.type;
setAddressPrefix(isNumber(options.addressPrefix) ? options.addressPrefix : 42);
this.#pairs = new Pairs();
this.#ss58 = options.ss58Format;
this.#type = options.type;
}
/**
@@ -65,10 +62,10 @@ export default class Keyring implements KeyringInstance {
}
/**
* @description Returns the type of the keyring, either ed25519 of sr25519
* @description Returns the type of the keyring, ed25519, sr25519 or ecdsa
*/
public get type (): KeypairType {
return this._type;
return this.#type;
}
/**
@@ -76,7 +73,7 @@ export default class Keyring implements KeyringInstance {
* @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary
*/
public addPair (pair: KeyringPair): KeyringPair {
return this._pairs.add(pair);
return this.#pairs.add(pair);
}
/**
@@ -90,7 +87,7 @@ export default class Keyring implements KeyringInstance {
public addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair {
const publicKey = this.decodeAddress(address, ignoreChecksum);
return this.addPair(createPair(type, { publicKey, secretKey: new Uint8Array(64) }, meta, encoded));
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, { publicKey, secretKey: new Uint8Array() }, meta, encoded));
}
/**
@@ -128,11 +125,13 @@ export default class Keyring implements KeyringInstance {
* `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.
*/
public addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
const keypair = type === 'sr25519'
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
const keypair = {
ecdsa: (): Keypair => secp256k1FromSeed(seed),
ed25519: (): Keypair => naclFromSeed(seed),
sr25519: (): Keypair => schnorrkelFromSeed(seed)
}[type]();
return this.addPair(createPair(type, keypair, meta, null));
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, keypair, meta, null));
}
/**
@@ -148,7 +147,7 @@ export default class Keyring implements KeyringInstance {
/**
* @name createFromUri
* @summry Creates a Keypair from an suri
* @summary Creates a Keypair from an suri
* @description This creates a pair from the suri, but does not add it to the keyring
*/
public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
@@ -156,8 +155,8 @@ export default class Keyring implements KeyringInstance {
const suri = _suri.startsWith('//')
? `${DEV_PHRASE}${_suri}`
: _suri;
const { password, phrase, path } = keyExtractSuri(suri);
let seed;
const { password, path, phrase } = keyExtractSuri(suri);
let seed: Uint8Array;
if (isHex(phrase, 256)) {
seed = hexToU8a(phrase);
@@ -178,12 +177,22 @@ export default class Keyring implements KeyringInstance {
}
}
const keypair = type === 'sr25519'
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
const derived = keyFromPath(keypair, path, type);
const keypair = {
ecdsa: (): Keypair => secp256k1FromSeed(seed),
ed25519: (): Keypair => naclFromSeed(seed),
sr25519: (): Keypair => schnorrkelFromSeed(seed)
};
const derived = keyFromPath(keypair[type](), path, type);
return createPair(type, derived, meta, null);
return createPair({ toSS58: this.encodeAddress, type }, derived, meta, null);
}
/**
* @name encodeAddress
* @description Encodes the input into an ss58 representation
*/
public encodeAddress = (address: Uint8Array | string, ss58Format?: number): string => {
return encodeAddress(address, ss58Format || this.#ss58);
}
/**
@@ -193,7 +202,7 @@ export default class Keyring implements KeyringInstance {
* a key lookup using the provided account address or public key (after decoding it).
*/
public getPair (address: string | Uint8Array): KeyringPair {
return this._pairs.get(address);
return this.#pairs.get(address);
}
/**
@@ -202,7 +211,7 @@ export default class Keyring implements KeyringInstance {
* @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary.
*/
public getPairs (): KeyringPair[] {
return this._pairs.all();
return this.#pairs.all();
}
/**
@@ -211,7 +220,7 @@ export default class Keyring implements KeyringInstance {
* @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.
*/
public getPublicKeys (): Uint8Array[] {
return this._pairs
return this.#pairs
.all()
.map(({ publicKey }): Uint8Array =>
publicKey
@@ -223,7 +232,15 @@ export default class Keyring implements KeyringInstance {
* @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary.
*/
public removePair (address: string | Uint8Array): void {
this._pairs.remove(address);
this.#pairs.remove(address);
}
/**
* @name setSS58Format;
* @description Sets the ss58 format for the keyring
*/
public setSS58Format (ss58: number): void {
this.#ss58 = ss58;
}
/**
@@ -235,6 +252,6 @@ export default class Keyring implements KeyringInstance {
* may backup their account to a JSON file that contains this information.
*/
public toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json {
return this._pairs.get(address).toJson(passphrase);
return this.#pairs.get(address).toJson(passphrase);
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+18 -15
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,20 +14,7 @@ type DecodeResult = PairInfo & {
secretKey: Uint8Array;
};
export default function decode (passphrase?: string, _encrypted?: Uint8Array | null): DecodeResult {
assert(_encrypted, 'No encrypted data available to decode');
const encrypted = (_encrypted as Uint8Array);
const encoded = passphrase
? (naclDecrypt(
encrypted.subarray(NONCE_LENGTH),
encrypted.subarray(0, NONCE_LENGTH),
u8aFixLength(stringToU8a(passphrase), 256, true)
) as Uint8Array)
: encrypted;
assert(encoded, 'Unable to unencrypt using the supplied passphrase');
function decodePkcs8 (encoded: Uint8Array): DecodeResult {
const header = encoded.subarray(0, PKCS8_HEADER.length);
assert(header.toString() === PKCS8_HEADER.toString(), 'Invalid Pkcs8 header found in body');
@@ -53,3 +40,19 @@ export default function decode (passphrase?: string, _encrypted?: Uint8Array | n
secretKey
};
}
export default function decode (passphrase?: string, encrypted?: Uint8Array | null): DecodeResult {
assert(encrypted, 'No encrypted data available to decode');
const encoded = passphrase
? naclDecrypt(
encrypted.subarray(NONCE_LENGTH),
encrypted.subarray(0, NONCE_LENGTH),
u8aFixLength(stringToU8a(passphrase), 256, true)
)
: encrypted;
assert(encoded, 'Unable to unencrypt using the supplied passphrase');
return decodePkcs8(encoded);
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,7 +14,7 @@ export default function encode ({ publicKey, secretKey }: PairInfo, passphrase?:
const encoded = u8aConcat(
PKCS8_HEADER,
secretKey as Uint8Array,
secretKey,
PKCS8_DIVIDER,
publicKey
);
+30 -4
View File
@@ -1,15 +1,20 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { setAddressPrefix } from '@polkadot/util-crypto';
import { cryptoWaitReady, encodeAddress as toSS58, setSS58Format } from '@polkadot/util-crypto';
import { PAIRS } from '../testing';
import testingPairs from '../testingPairs';
import createPair from '.';
const keyring = testingPairs({ type: 'ed25519' }, false);
describe('pair', (): void => {
beforeEach(async (): Promise<void> => {
await cryptoWaitReady();
});
const SIGNATURE = new Uint8Array([80, 191, 198, 147, 225, 207, 75, 88, 126, 39, 129, 109, 191, 38, 72, 181, 75, 254, 81, 143, 244, 79, 237, 38, 236, 141, 28, 252, 134, 26, 169, 234, 79, 33, 153, 158, 151, 34, 175, 188, 235, 20, 35, 135, 83, 120, 139, 211, 233, 130, 1, 208, 201, 215, 73, 80, 56, 98, 185, 196, 11, 8, 193, 14]);
it('has a publicKey', (): void => {
@@ -61,20 +66,41 @@ describe('pair', (): void => {
'5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'
);
setAddressPrefix(68);
setSS58Format(68);
expect(keyring.alice.address).toEqual(
'7sGUeMak588SPY2YMmmuKUuLz7u2WQpf74F9dCFtSLB2td9d'
);
setSS58Format(42);
});
it('allows getting public key after decoding', (): void => {
const PASS = 'testing';
const encoded = keyring.alice.encodePkcs8(PASS);
const pair = createPair('sr25519', { publicKey: keyring.alice.publicKey });
const pair = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.alice.publicKey });
pair.decodePkcs8(PASS, encoded);
expect(pair.isLocked).toEqual(false);
});
it('allows derivation on the pair', (): void => {
const alice = createPair({ toSS58, type: 'sr25519' }, { publicKey: PAIRS[0].publicKey, secretKey: PAIRS[0].secretKey }, {});
const stash = alice.derive('//stash');
const soft = alice.derive('//funding/0');
expect(stash.publicKey).toEqual(PAIRS[1].publicKey);
expect(soft.address).toEqual('5ECQNn7UueWHPFda5qUi4fTmTtyCnPvGnuoyVVSj5CboJh9J');
});
it('fails to sign when locked', (): void => {
const pair = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.alice.publicKey });
expect(pair.isLocked).toEqual(true);
expect((): Uint8Array =>
pair.sign(new Uint8Array([0]))
).toThrow('Cannot sign with a locked key pair');
});
});
+93 -32
View File
@@ -1,38 +1,85 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Keypair, KeypairType } from '@polkadot/util-crypto/types';
import { KeyringPair, KeyringPair$Json, KeyringPair$Meta } from '../types';
import { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types';
import { PairInfo } from './types';
import { encodeAddress, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
import { assert, u8aConcat } from '@polkadot/util';
import { keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify, secp256k1KeypairFromSeed as secp256k1FromSeed, secp256k1Sign, secp256k1Verify, blake2AsU8a } from '@polkadot/util-crypto';
import decode from './decode';
import encode from './encode';
import toJson from './toJson';
interface Setup {
toSS58: (publicKey: Uint8Array) => string;
type: KeypairType;
}
const SIG_TYPE_NONE = new Uint8Array();
const SIG_TYPE_ED25519 = new Uint8Array([0]);
const SIG_TYPE_SR25519 = new Uint8Array([1]);
const SIG_TYPE_ECDSA = new Uint8Array([2]);
function isEmpty (u8a: Uint8Array): boolean {
return u8a.reduce((count, u8): number => count + u8, 0) === 0;
}
const isSr25519 = (type: KeypairType): boolean =>
type === 'sr25519';
function fromSeed (type: KeypairType, seed: Uint8Array): Keypair {
return {
ecdsa: (): Keypair => secp256k1FromSeed(seed),
ed25519: (): Keypair => naclFromSeed(seed),
sr25519: (): Keypair => schnorrkelFromSeed(seed)
}[type]();
}
const fromSeed = (type: KeypairType, seed: Uint8Array): Keypair =>
isSr25519(type)
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
function multiSignaturePrefix (type: KeypairType): Uint8Array {
return {
ecdsa: SIG_TYPE_ECDSA,
ed25519: SIG_TYPE_ED25519,
sr25519: SIG_TYPE_SR25519
}[type];
}
const sign = (type: KeypairType, message: Uint8Array, pair: Partial<Keypair>): Uint8Array =>
isSr25519(type)
? schnorrkelSign(message, pair)
: naclSign(message, pair);
function sign (type: KeypairType, message: Uint8Array, pair: Partial<Keypair>, { withType = false }: SignOptions = {}): Uint8Array {
const signature = {
ecdsa: (): Uint8Array => secp256k1Sign(message, pair),
ed25519: (): Uint8Array => naclSign(message, pair),
sr25519: (): Uint8Array => schnorrkelSign(message, pair)
}[type]();
const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean =>
isSr25519(type)
? schnorrkelVerify(message, signature, publicKey)
: naclVerify(message, signature, publicKey);
return u8aConcat(
// for multi-signatures, i.e. with indicator, append the signature type as per
// the MultiSignature enum
withType
? multiSignaturePrefix(type)
: SIG_TYPE_NONE,
signature
);
}
function verify (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean {
return {
ecdsa: (): boolean => secp256k1Verify(message, signature, blake2AsU8a(publicKey, 256)),
ed25519: (): boolean => naclVerify(message, signature, publicKey),
sr25519: (): boolean => schnorrkelVerify(message, signature, publicKey)
}[type]();
}
function getAddress (type: KeypairType, publicKey: Uint8Array): Uint8Array {
if (type === 'ecdsa' && publicKey.length > 32) {
return blake2AsU8a(publicKey, 256);
} else {
return publicKey;
}
}
// Not 100% correct, since it can be a Uint8Array, but an invalid one - just say "undefined" is anything non-valid
function isLocked (secretKey?: Uint8Array): secretKey is undefined {
return !secretKey || secretKey.length === 0 || isEmpty(secretKey);
}
/**
* @name pair
@@ -65,12 +112,24 @@ const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, p
* 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 createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
export default function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
return {
type,
get address (): string {
return encodeAddress(publicKey);
return toSS58(getAddress(type, publicKey));
},
get isLocked (): boolean {
return isLocked(secretKey);
},
get meta (): KeyringPair$Meta {
return meta;
},
get publicKey (): Uint8Array {
return publicKey;
},
get type (): KeypairType {
return type;
},
// eslint-disable-next-line sort-keys
decodePkcs8: (passphrase?: string, _encoded?: Uint8Array | null): void => {
const decoded = decode(passphrase, _encoded || encoded);
@@ -84,27 +143,29 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }:
secretKey = pair.secretKey;
}
},
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair => {
assert(!isLocked(secretKey), 'Cannot derive on a locked keypair');
const { path } = keyExtractPath(suri);
const derived = keyFromPath({ publicKey, secretKey }, path, type);
return createPair({ toSS58, type }, derived, meta, null);
},
encodePkcs8: (passphrase?: string): Uint8Array =>
encode({ publicKey, secretKey }, passphrase),
get meta (): KeyringPair$Meta {
return meta;
},
get isLocked (): boolean {
return !secretKey || secretKey.length === 0 || isEmpty(secretKey);
},
lock: (): void => {
secretKey = new Uint8Array(0);
},
get publicKey (): Uint8Array {
return publicKey;
},
setMeta: (additional: KeyringPair$Meta): void => {
meta = { ...meta, ...additional };
},
sign: (message: Uint8Array): Uint8Array =>
sign(type, message, { publicKey, secretKey }),
sign: (message: Uint8Array, options?: SignOptions): Uint8Array => {
assert(!isLocked(secretKey), 'Cannot sign with a locked key pair');
return sign(type, message, { publicKey, secretKey }, options);
},
toJson: (passphrase?: string): KeyringPair$Json =>
toJson(type, { meta, publicKey }, encode({ publicKey, secretKey }, passphrase), !!passphrase),
toJson(type, { address: toSS58(getAddress(type, publicKey)), meta }, encode({ publicKey, secretKey }, passphrase), !!passphrase),
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
verify(type, message, signature, publicKey)
};
+9 -4
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -24,20 +24,22 @@ const json: KeyringPair$Json = {
};
export default function everybody (): KeyringPair {
return {
type: 'ed25519',
const pair: KeyringPair = {
address,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void =>
undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair =>
pair,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encodePkcs8: (passphrase?: string): Uint8Array =>
new Uint8Array(0),
meta,
isLocked: true,
lock: (): void => {
// no locking, it is always locked
},
meta,
publicKey,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMeta: (meta: KeyringPair$Meta): void =>
@@ -48,8 +50,11 @@ export default function everybody (): KeyringPair {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
toJson: (passphrase?: string): KeyringPair$Json =>
json,
type: 'ed25519',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false
};
return pair;
}
+3 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -19,8 +19,8 @@ describe('toJson', (): void => {
version: '2'
},
meta: {
name: 'alice',
isTesting: true
isTesting: true,
name: 'alice'
}
});
});
+7 -7
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -6,15 +6,15 @@ import { KeypairType } from '@polkadot/util-crypto/types';
import { KeyringPair$Json, KeyringPair$Meta } from '../types';
import { u8aToHex } from '@polkadot/util';
import { encodeAddress } from '@polkadot/util-crypto';
type PairStateJson = KeyringPair$Meta & {
publicKey: Uint8Array;
};
interface PairStateJson {
address: string;
meta: KeyringPair$Meta;
}
export default function toJson (type: KeypairType, { publicKey, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
export default function toJson (type: KeypairType, { address, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json {
return {
address: encodeAddress(publicKey),
address,
encoded: u8aToHex(encoded),
encoding: {
content: ['pkcs8', type],
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+6 -10
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -10,24 +10,20 @@ import { decodeAddress } from '@polkadot/util-crypto';
type KeyringPairMap = Record<string, KeyringPair>;
export default class Pairs implements KeyringPairs {
private _map: KeyringPairMap;
public constructor () {
this._map = {};
}
readonly #map: KeyringPairMap = {};
public add (pair: KeyringPair): KeyringPair {
this._map[pair.publicKey.toString()] = pair;
this.#map[decodeAddress(pair.address).toString()] = pair;
return pair;
}
public all (): KeyringPair[] {
return Object.values(this._map);
return Object.values(this.#map);
}
public get (address: string | Uint8Array): KeyringPair {
const pair = this._map[decodeAddress(address).toString()];
const pair = this.#map[decodeAddress(address).toString()];
assert(pair, (): string => {
const formatted: string = isU8a(address) || isHex(address)
@@ -41,6 +37,6 @@ export default class Pairs implements KeyringPairs {
}
public remove (address: string | Uint8Array): void {
delete this._map[decodeAddress(address).toString()];
delete this.#map[decodeAddress(address).toString()];
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+20 -27
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -21,53 +21,46 @@ interface PairDef {
// keyring is for testing - what happens is that in most cases the keyring is initialises
// before anything else. Since the sr25519 crypto is async, this creates problems with
// adding the keys when only the keyring is used.
const PAIRS: PairDef[] = [
export const PAIRS: PairDef[] = [
{
seed: 'Alice',
publicKey: hexToU8a('0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d'),
secretKey: hexToU8a('0x98319d4ff8a9508c4bb0cf0b5a78d760a0b2082c02775e6e82370816fedfff48925a225d97aa00682d6a59b95b18780c10d7032336e88f3442b42361f4a66011'),
publicKey: hexToU8a('0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d')
seed: 'Alice'
},
{
seed: 'Alice//stash',
publicKey: hexToU8a('0xbe5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f'),
secretKey: hexToU8a('0xe8da6c9d810e020f5e3c7f5af2dea314cbeaa0d72bc6421e92c0808a0c584a6046ab28e97c3ffc77fe12b5a4d37e8cd4afbfebbf2391ffc7cb07c0f38c023efd'),
publicKey: hexToU8a('0xbe5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f')
seed: 'Alice//stash'
},
{
name: 'alice_session',
type: 'ed25519',
seed: 'Alice',
secretKey: hexToU8a('0xabf8e5bdbe30c65656c0a3cbd181ff8a56294a69dfedd27982aace4a7690911588dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee'),
publicKey: hexToU8a('0x88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee')
},
{
seed: 'Bob',
publicKey: hexToU8a('0x8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48'),
secretKey: hexToU8a('0x081ff694633e255136bdb456c20a5fc8fed21f8b964c11bb17ff534ce80ebd5941ae88f85d0c1bfc37be41c904e1dfc01de8c8067b0d6d5df25dd1ac0894a325'),
publicKey: hexToU8a('0x8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48')
seed: 'Bob'
},
{
seed: 'Bob//stash',
publicKey: hexToU8a('0xfe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e'),
secretKey: hexToU8a('0xc006507cdfc267a21532394c49ca9b754ca71de21e15a1cdf807c7ceab6d0b6c3ed408d9d35311540dcd54931933e67cf1ea10d46f75408f82b789d9bd212fde'),
publicKey: hexToU8a('0xfe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e')
seed: 'Bob//stash'
},
{
seed: 'Charlie',
publicKey: hexToU8a('0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22'),
secretKey: hexToU8a('0xa8f2d83016052e5d6d77b2f6fd5d59418922a09024cda701b3c34369ec43a7668faf12ff39cd4e5d92bb773972f41a7a5279ebc2ed92264bed8f47d344f8f18c'),
publicKey: hexToU8a('0x90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22')
seed: 'Charlie'
},
{
seed: 'Dave',
publicKey: hexToU8a('0x306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20'),
secretKey: hexToU8a('0x20e05482ca4677e0edbc58ae9a3a59f6ed3b1a9484ba17e64d6fe8688b2b7b5d108c4487b9323b98b11fe36cb301b084e920f7b7895536809a6d62a451b25568'),
publicKey: hexToU8a('0x306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20')
seed: 'Dave'
},
{
seed: 'Eve',
publicKey: hexToU8a('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e'),
secretKey: hexToU8a('0x683576abfd5dc35273e4264c23095a1bf21c14517bece57c7f0cc5c0ed4ce06a3dbf386b7828f348abe15d76973a72009e6ef86a5c91db2990cb36bb657c6587'),
publicKey: hexToU8a('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e')
seed: 'Eve'
},
{
seed: 'Ferdie',
publicKey: hexToU8a('0x1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c'),
secretKey: hexToU8a('0xb835c20f450079cf4f513900ae9faf8df06ad86c681884122c752a4b2bf74d4303e4f21bc6cc62bb4eeed5a9cce642c25e2d2ac1464093b50f6196d78e3a7426'),
publicKey: hexToU8a('0x1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c')
seed: 'Ferdie'
}
];
@@ -80,7 +73,7 @@ const PAIRS: PairDef[] = [
export default function testKeyring (options: KeyringOptions = {}, isDerived = true): KeyringInstance {
const keyring = new Keyring(options);
PAIRS.forEach(({ name, publicKey, secretKey, seed, type }): void => {
PAIRS.forEach(({ name, publicKey, secretKey, seed, type = 'sr25519' }): void => {
const meta = {
isTesting: true,
name: name || seed.replace('//', '_').toLowerCase()
@@ -89,7 +82,7 @@ export default function testKeyring (options: KeyringOptions = {}, isDerived = t
const pair = !isDerived && !name
? keyring.addFromUri(seed, meta, options.type)
: keyring.addPair(
createPair(type || 'sr25519', { publicKey, secretKey }, meta)
createPair({ toSS58: keyring.encodeAddress, type }, { publicKey, secretKey }, meta)
);
pair.lock = (): void => {
+2 -8
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,7 +14,7 @@ describe('testingPairs', (): void => {
it('creates without failing', (): void => {
expect(
Object.keys(testingPairs())
).toHaveLength(2 + 1 + 7);
).toHaveLength(2 + 0 + 7); // stash, session, pairs
});
it('has the correct address for Alice (non-HDKD)', (): void => {
@@ -28,10 +28,4 @@ describe('testingPairs', (): void => {
testingPairs({ type: 'ed25519' }).alice.address
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
it('has the correct address for Alice_session (HDKD)', (): void => {
expect(
testingPairs({ type: 'ed25519' }).alice_session.address
).toEqual('5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu');
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+16 -15
View File
@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/class-name-casing */
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -7,14 +6,11 @@ import { Prefix } from '@polkadot/util-crypto/address/types';
import { KeypairType } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
addressPrefix?: Prefix;
ss58Format?: Prefix;
type?: KeypairType;
}
export interface KeyringPair$Meta {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
export type KeyringPair$Meta = Record<string, unknown>;
export type KeyringPair$JsonVersion = '0' | '1' | '2';
@@ -31,18 +27,23 @@ export interface KeyringPair$Json {
meta: KeyringPair$Meta;
}
export interface SignOptions {
withType?: boolean;
}
export interface KeyringPair {
readonly address: string;
readonly meta: KeyringPair$Meta;
readonly isLocked: boolean;
readonly publicKey: Uint8Array;
readonly type: KeypairType;
address: string;
decodePkcs8: (passphrase?: string, encoded?: Uint8Array) => void;
derive: (suri: string, meta?: KeyringPair$Meta) => KeyringPair;
encodePkcs8: (passphrase?: string) => Uint8Array;
meta: KeyringPair$Meta;
isLocked: boolean;
lock: () => void;
publicKey: Uint8Array;
setMeta: (meta: KeyringPair$Meta) => void;
sign (message: Uint8Array): Uint8Array;
sign (message: Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
verify (message: Uint8Array, signature: Uint8Array): boolean;
}
@@ -59,9 +60,9 @@ export interface KeyringInstance {
readonly publicKeys: Uint8Array[];
readonly type: KeypairType;
decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array;
encodeAddress (key: Uint8Array | string): string;
setAddressPrefix (prefix: Prefix): void;
decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean, ss58Format?: Prefix): Uint8Array;
encodeAddress (key: Uint8Array | string, ss58Format?: Prefix): string;
setSS58Format (ss58Format: Prefix): void;
addPair (pair: KeyringPair): KeyringPair;
addFromAddress (address: string | Uint8Array, meta?: KeyringPair$Meta, encoded?: Uint8Array | null, type?: KeypairType, ignoreChecksum?: boolean): KeyringPair;
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-7
View File
@@ -1,7 +0,0 @@
# @polkadot/trie-codec
Implementation of the Substrate-specific codec for a Trie
## Utilities
[Utilities](SUMMARY.md)
-31
View File
@@ -1,31 +0,0 @@
{
"name": "@polkadot/trie-codec",
"version": "1.3.1",
"description": "This is an implementation of the codec for Substrate Trie",
"main": "index.js",
"keywords": [
"Polkadot"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/common.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-codec#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.3.1"
}
}
-135
View File
@@ -1,135 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { decodeNibbles, isNibblesTerminated } from '@polkadot/trie-codec/nibbles';
import { BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE, EMPTY_TRIE, EXTENSION_NODE_BIG, EXTENSION_NODE_OFFSET, EXTENSION_NODE_SMALL_MAX, EXTENSION_NODE_THRESHOLD, LEAF_NODE_BIG, LEAF_NODE_OFFSET, LEAF_NODE_SMALL_MAX, LEAF_NODE_THRESHOLD, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
// FIXME These are not actually extending from types, we may want to bring
// that in if the dependency imports can be sorted out
type NodeType = 0 | 1 | 2 | 3;
export type Null = null;
export type BranchHeader = boolean;
export type NibbleHeader = number;
export type ExtensionHeader = NibbleHeader;
export type LeafHeader = NibbleHeader;
export default class NodeHeader {
private _nodeType: NodeType;
private _value: Null | BranchHeader | ExtensionHeader | LeafHeader;
public constructor (input?: null | Uint8Array | (null | Uint8Array)[]) {
const [nodeType, value] = Array.isArray(input)
? NodeHeader.decodeNodeHeaderArray(input)
: NodeHeader.decodeNodeHeaderU8a(input);
this._nodeType = nodeType;
this._value = value;
}
private static decodeNodeHeaderArray (input: (null | Uint8Array)[]): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] {
if (input.length === 0) {
return [NODE_TYPE_NULL, null];
} else if (input.length === 2) {
const nibbles = decodeNibbles(input[0]);
const isTerminated = isNibblesTerminated(nibbles);
return isTerminated
? [NODE_TYPE_LEAF, nibbles.length - 1]
: [NODE_TYPE_EXT, nibbles.length];
} else if (input.length === 17) {
return [NODE_TYPE_BRANCH, !!input[16]];
}
throw new Error('Unreachable');
}
private static decodeNodeHeaderU8a (input?: null | Uint8Array): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] {
const firstByte = input
? input[0]
: EMPTY_TRIE;
if (!input || firstByte === EMPTY_TRIE) {
return [NODE_TYPE_NULL, null];
} else if (firstByte === BRANCH_NODE_NO_VALUE) {
return [NODE_TYPE_BRANCH, false];
} else if (firstByte === BRANCH_NODE_WITH_VALUE) {
return [NODE_TYPE_BRANCH, true];
} else if (firstByte >= EXTENSION_NODE_OFFSET && firstByte <= EXTENSION_NODE_SMALL_MAX) {
return [NODE_TYPE_EXT, firstByte - EXTENSION_NODE_OFFSET];
} else if (firstByte === EXTENSION_NODE_BIG) {
return [NODE_TYPE_EXT, input[1] + EXTENSION_NODE_THRESHOLD];
} else if (firstByte >= LEAF_NODE_OFFSET && firstByte <= LEAF_NODE_SMALL_MAX) {
return [NODE_TYPE_LEAF, firstByte - LEAF_NODE_OFFSET];
} else if (firstByte === LEAF_NODE_BIG) {
return [NODE_TYPE_LEAF, input[1] + LEAF_NODE_THRESHOLD];
}
throw new Error('Unreachable');
}
public get encodedLength (): number {
switch (this.nodeType) {
case NODE_TYPE_NULL:
case NODE_TYPE_BRANCH:
return 1;
case NODE_TYPE_EXT:
return (this.value as ExtensionHeader) < EXTENSION_NODE_THRESHOLD
? 1
: 2;
case NODE_TYPE_LEAF:
return (this.value as LeafHeader) < LEAF_NODE_THRESHOLD
? 1
: 2;
default:
throw new Error('Unreachable');
}
}
public get nodeType (): number {
return this._nodeType;
}
public get value (): Null | BranchHeader | ExtensionHeader | LeafHeader {
return this._value;
}
public toU8a (): Uint8Array {
switch (this.nodeType) {
case NODE_TYPE_NULL:
return new Uint8Array([EMPTY_TRIE]);
case NODE_TYPE_BRANCH:
return new Uint8Array([
this.value as BranchHeader
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE
]);
case NODE_TYPE_EXT: {
const nibbleCount = this.value as ExtensionHeader;
return (nibbleCount < EXTENSION_NODE_THRESHOLD)
? new Uint8Array([EXTENSION_NODE_OFFSET + nibbleCount])
: new Uint8Array([EXTENSION_NODE_BIG, nibbleCount - EXTENSION_NODE_THRESHOLD]);
}
case NODE_TYPE_LEAF: {
const nibbleCount = this.value as LeafHeader;
return (nibbleCount < LEAF_NODE_THRESHOLD)
? new Uint8Array([LEAF_NODE_OFFSET + nibbleCount])
: new Uint8Array([LEAF_NODE_BIG, nibbleCount - LEAF_NODE_THRESHOLD]);
}
default:
throw new Error('Unreachable');
}
}
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export const BITMAP = [
1 << 0,
1 << 1,
1 << 2,
1 << 3,
1 << 4,
1 << 5,
1 << 6,
1 << 7,
1 << 8,
1 << 9,
1 << 10,
1 << 11,
1 << 12,
1 << 13,
1 << 14,
1 << 15
];
export const EMPTY_TRIE = 0;
export const LEAF_NODE_OFFSET = 1;
export const LEAF_NODE_BIG = 127;
export const EXTENSION_NODE_OFFSET = 128;
export const EXTENSION_NODE_BIG = 253;
export const BRANCH_NODE_NO_VALUE = 254;
export const BRANCH_NODE_WITH_VALUE = 255;
export const LEAF_NODE_THRESHOLD = LEAF_NODE_BIG - LEAF_NODE_OFFSET;
export const EXTENSION_NODE_THRESHOLD = EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET; // 125
export const LEAF_NODE_SMALL_MAX = LEAF_NODE_BIG - 1;
export const EXTENSION_NODE_SMALL_MAX = EXTENSION_NODE_BIG - 1;
export const NODE_TYPE_NULL = 0;
export const NODE_TYPE_BRANCH = 1;
export const NODE_TYPE_EXT = 2;
export const NODE_TYPE_LEAF = 3;
-74
View File
@@ -1,74 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a } from '@polkadot/util';
import decode from './decode';
describe('decode', (): void => {
it('decodes a leaf', (): void => {
expect(
decode(Uint8Array.from([
0x05, 0x48, 0x19, 0x04, 0xfe
]))
).toEqual([
Uint8Array.from([0x20, 0x48, 0x19]),
Uint8Array.from([0xfe])
]);
});
it('decodes a branch', (): void => {
expect(
decode(Uint8Array.from([
0xfe, 0x00, 0x0c, 0x48, 0x81, 0x0a, 0x3c, 0xff, 0x00, 0x0c, 0x04, 0xa0, 0x10, 0x02, 0x0a, 0x04,
0xaa, 0x10, 0x02, 0x0b, 0x04, 0xab, 0x10, 0x02, 0x0b, 0x04, 0xb0
]))
).toEqual([
null, null, null, null, null, null, null, null, null, null,
[
Uint8Array.from([26]),
Uint8Array.from([255, 0, 12, 4, 160, 16, 2, 10, 4, 170, 16, 2, 11, 4, 171])
],
[
Uint8Array.from([59]),
Uint8Array.from([176])
],
null, null, null, null, null
]);
});
it('decodes a complex branch', (): void => {
expect(
decode(hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
))
).toEqual([
null,
null,
[
hexToU8a('0x37b3872d47181b4a2dc15f0da43e7026'),
hexToU8a('0xe803000000000000')
],
Uint8Array.from([
23, 13, 50, 42, 196, 157, 135, 8, 241, 81, 52, 108, 104, 217, 229, 132, 82, 216, 58, 157, 59, 113, 14, 30, 173, 53, 235, 50, 105, 171, 35, 83
]),
null,
null,
null,
[
hexToU8a('0x3935e46f94f24b82716c0142e2271de9'),
hexToU8a('0x0087000000000000')
],
null,
null,
null,
null,
null,
null,
null,
null,
null
]);
});
});
-97
View File
@@ -1,97 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactStripLength, logger } from '@polkadot/util';
import NodeHeader, { BranchHeader, NibbleHeader } from './NodeHeader';
import { BITMAP, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
import { addNibblesTerminator, encodeNibbles } from './nibbles';
import { toNibbles } from './util';
const EMPTY_BRANCH: (Uint8Array | null)[] = [
null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null, null
];
const l = logger('trie/codec');
l.noop();
function _decodeBranch (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] {
let offset = header.encodedLength;
const branch = header.value as BranchHeader;
const bitmap = input[offset] + (input[offset + 1] << 8);
let value: null | Uint8Array;
offset += 2;
if (branch === true) {
const [length, bytes] = compactStripLength(input.subarray(offset));
value = bytes;
offset += length;
} else {
value = null;
}
return EMPTY_BRANCH.concat(value).map((value, index): null | Uint8Array | [Uint8Array, Uint8Array] => {
let result: null | Uint8Array | [Uint8Array, Uint8Array] = value;
if ((index < 16) && (bitmap & BITMAP[index])) {
const [length, bytes] = compactStripLength(input.subarray(offset));
result = bytes.length === 32
? bytes
// eslint-disable-next-line @typescript-eslint/no-use-before-define
: decode(bytes) as Uint8Array;
offset += length;
}
return result;
});
}
function _decodeKv (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] {
const offset = header.encodedLength;
const nibbleCount = (header.value as NibbleHeader);
const nibbleLength = (nibbleCount + 1) >> 1;
const nibbleData = input.subarray(offset, offset + nibbleLength);
// for odd, ignore the first nibble, data starts at offset 1
const nibbles = toNibbles(nibbleData).subarray(nibbleCount % 2);
const [, value] = compactStripLength(input.subarray(offset + nibbleData.length));
return [
encodeNibbles(
header.nodeType === NODE_TYPE_LEAF
? addNibblesTerminator(nibbles)
: nibbles
),
value
];
}
export default function decode (input: null | Uint8Array): Uint8Array | null | (null | Uint8Array | [Uint8Array, Uint8Array])[] {
const header = new NodeHeader(input);
const nodeType = header.nodeType;
if (!input || nodeType === NODE_TYPE_NULL) {
return input;
} else if (nodeType === NODE_TYPE_BRANCH) {
return _decodeBranch(header, input);
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
return _decodeKv(header, input);
}
throw new Error('Unreachable');
}
// export default function decode (input: null | Uint8Array): Uint8Array | null | Array<null | Uint8Array | Array<null | Uint8Array>> {
// const decoded = _decode(input);
// // l.debug(() => ['decode', { input, decoded }]);
// return decoded;
// }
-107
View File
@@ -1,107 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a } from '@polkadot/util';
import encode from './encode';
describe('encoding', (): void => {
it('encode a small sub-tree', (): void => {
expect(
encode([
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
[
Uint8Array.from([58]),
Uint8Array.from([170])
],
null,
null,
null,
null,
null,
Uint8Array.from([160])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(Uint8Array.from([
255, 0, 4, 4, 160, 16, 2, 10, 4, 170
]));
});
it('encodes a sub-tree', (): void => {
expect(
encode([
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
[
Uint8Array.from([58]),
Uint8Array.from([170])
],
[
Uint8Array.from([59]),
Uint8Array.from([171])
],
null,
null,
null,
null,
Uint8Array.from([160])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(Uint8Array.from([
255, 0, 12, 4, 160, 16, 2, 10, 4, 170, 16, 2, 11, 4, 171
]));
});
it('encodes a complex tree (with hash)', (): void => {
expect(
encode([
null,
null,
[
hexToU8a('0x37b3872d47181b4a2dc15f0da43e7026'),
hexToU8a('0xe803000000000000')
],
Uint8Array.from([
23, 13, 50, 42, 196, 157, 135, 8, 241, 81, 52, 108, 104, 217, 229, 132, 82, 216, 58, 157, 59, 113, 14, 30, 173, 53, 235, 50, 105, 171, 35, 83
]),
null,
null,
null,
[
hexToU8a('0x3935e46f94f24b82716c0142e2271de9'),
hexToU8a('0x0087000000000000')
],
null,
null,
null,
null,
null,
null,
null,
null,
null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
));
});
});
-100
View File
@@ -1,100 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactAddLength, u8aConcat, isU8a, logger } from '@polkadot/util';
import NodeHeader from './NodeHeader';
import { BITMAP, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
import { extractKey } from './nibbles';
import { fromNibbles } from './util';
const BRANCH_VALUE_INDEX = 16;
const EMPTY = new Uint8Array();
const l = logger('trie/codec');
l.noop();
// in the case of odd nibbles, the first byte is encoded as a single
// byte from the nibble, with the remainder of the nibbles is converted
// as nomral nibble combined bytes
function encodeKey (input: null | Uint8Array): Uint8Array {
const nibbles = extractKey(input);
// l.debug(() => ['encodeKey', { input, nibbles }]);
return nibbles.length % 2
? u8aConcat(Uint8Array.from([nibbles[0]]), fromNibbles(nibbles.subarray(1)))
: fromNibbles(nibbles);
}
function encodeValue (input: null | Uint8Array | (null | Uint8Array)[]): Uint8Array {
if (!input) {
return EMPTY;
}
// l.debug(() => ['encodeValue', { input, encoded }]);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return compactAddLength(encode(input));
}
function _encodeBranch (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array {
const values: Uint8Array[] = [];
let bitmap = 0;
for (let index = 0; index < BRANCH_VALUE_INDEX; index++) {
const value = input[index];
if (value) {
bitmap |= BITMAP[index];
values.push(encodeValue(value));
}
}
return u8aConcat(
header.toU8a(),
new Uint8Array([(bitmap & 0xff), (bitmap >> 8)]),
encodeValue(input[BRANCH_VALUE_INDEX]),
...values
);
}
function _encodeKv (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array {
const [path, value] = input;
return u8aConcat(
header.toU8a(),
encodeKey(path),
encodeValue(value)
);
}
export default function encode (input?: null | Uint8Array | (null | Uint8Array)[]): Uint8Array {
if (isU8a(input)) {
return input;
}
const header = new NodeHeader(input);
const nodeType = header.nodeType;
if (!input || nodeType === NODE_TYPE_NULL) {
return header.toU8a();
} else if (nodeType === NODE_TYPE_BRANCH) {
return _encodeBranch(header, input);
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
return _encodeKv(header, input);
}
throw new Error('Unreachable');
}
// export default function encode (input?: null | Uint8Array | Array<null | Uint8Array>): Uint8Array {
// const encoded = _encode(input);
// // l.debug(() => ['encode', { input, encoded }]);
// return encoded;
// }
-7
View File
@@ -1,7 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { blake2AsU8a as hashing } from '@polkadot/util-crypto';
export default hashing;
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Codec } from './types';
import decode from './decode';
import encode from './encode';
import hashing from './hashing';
export { default as stream } from './stream';
const codec: Codec = {
decode,
encode,
hashing,
type: 'Substrate'
};
export default codec;
-79
View File
@@ -1,79 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { fromNibbles, toNibbles } from './util';
const HP_FLAG_2 = 2;
const HP_FLAG_0 = 0;
const NIBBLE_TERMINATOR = 16;
const NEEDS_TERMINATOR = [HP_FLAG_2, HP_FLAG_2 + 1];
const IS_ODD_LENGTH = [HP_FLAG_0 + 1, HP_FLAG_2 + 1];
export function isNibblesTerminated (nibbles: Uint8Array): boolean {
return nibbles[nibbles.length - 1] === NIBBLE_TERMINATOR;
}
export function addNibblesTerminator (nibbles: Uint8Array): Uint8Array {
if (isNibblesTerminated(nibbles)) {
return nibbles;
}
const terminated = new Uint8Array(nibbles.length + 1);
terminated.set(nibbles);
terminated[nibbles.length] = NIBBLE_TERMINATOR;
return terminated;
}
export function removeNibblesTerminator (nibbles: Uint8Array): Uint8Array {
if (isNibblesTerminated(nibbles)) {
return nibbles.subarray(0, nibbles.length - 1);
}
return nibbles;
}
export function decodeNibbles (value: null | Uint8Array): Uint8Array {
const nibblesWithFlag = toNibbles(value);
const [flag] = nibblesWithFlag;
const rawNibbles = IS_ODD_LENGTH.includes(flag)
? nibblesWithFlag.subarray(1)
: nibblesWithFlag.subarray(2);
return NEEDS_TERMINATOR.includes(flag)
? addNibblesTerminator(rawNibbles)
: rawNibbles;
}
export function encodeNibbles (nibbles: Uint8Array): Uint8Array {
const flag = isNibblesTerminated(nibbles)
? HP_FLAG_2
: HP_FLAG_0;
const rawNibbles = removeNibblesTerminator(nibbles);
const prefix = rawNibbles.length % 2
? [flag + 1]
: [flag, 0];
const prefixed = new Uint8Array(prefix.length + rawNibbles.length);
prefixed.set(prefix);
prefixed.set(rawNibbles, prefix.length);
return fromNibbles(prefixed);
}
export function extractKey (key: null | Uint8Array): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
export function extractNodeKey ([key]: (null | Uint8Array)[]): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aConcat } from '@polkadot/util';
import { BITMAP, BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE } from '../constants';
import createValue from './createValue';
export default function createBranch (value: Uint8Array | null, hasChildren: boolean[]): Uint8Array {
let bitmap = 0;
for (let i = 0; i < hasChildren.length; i++) {
if (hasChildren[i]) {
bitmap |= BITMAP[i];
}
}
return u8aConcat(
Uint8Array.from([
value
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE,
(bitmap & 0xff),
(bitmap >> 8)
]),
createValue(value)
);
}
@@ -1,9 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { EMPTY_TRIE } from '../constants';
export default function createEmpty (): Uint8Array {
return Uint8Array.from([EMPTY_TRIE]);
}
@@ -1,9 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { fuseNibbles } from '../util';
export default function createExtension (key: Uint8Array): Uint8Array {
return fuseNibbles(key, false);
}
@@ -1,15 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aConcat } from '@polkadot/util';
import { fuseNibbles } from '../util';
import createValue from './createValue';
export default function createLeaf (key: Uint8Array, value: Uint8Array): Uint8Array {
return u8aConcat(
fuseNibbles(key, true),
createValue(value)
);
}
@@ -1,14 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import hashing from '../hashing';
import createValue from './createValue';
export default function createSubstream (value: Uint8Array): Uint8Array {
return createValue(
value.length < 32
? value
: hashing(value)
);
}
@@ -1,13 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactAddLength } from '@polkadot/util';
const NO_VALUE = new Uint8Array();
export default function createValue (value: null | Uint8Array): Uint8Array {
return value
? compactAddLength(value)
: NO_VALUE;
}
@@ -1,10 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const NO_VALUE = new Uint8Array();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function encBranch (value: Uint8Array | null): Uint8Array {
return NO_VALUE;
}
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import createBranch from './createBranch';
import createEmpty from './createEmpty';
import createExtension from './createExtension';
import createLeaf from './createLeaf';
import createSubstream from './createSubstream';
import createValue from './createValue';
import endBranch from './endBranch';
export default {
createBranch,
createEmpty,
createExtension,
createLeaf,
createSubstream,
createValue,
endBranch
};
-10
View File
@@ -1,10 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface Codec {
decode: (input: null | Uint8Array) => Uint8Array | null | (null | Uint8Array | (null | Uint8Array)[])[];
encode: (input?: null | Uint8Array | (null | Uint8Array)[]) => Uint8Array;
hashing: (input: Uint8Array) => Uint8Array;
type: string;
}
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import stringToU8a from '@polkadot/util/string/toU8a';
import fromNibbles from './fromNibbles';
describe('fromNibbles', (): void => {
it('converts a single', (): void => {
expect(
fromNibbles(
new Uint8Array([4, 1])
)
).toEqual(
stringToU8a('A')
);
});
it('converts an number of values', (): void => {
expect(
fromNibbles(
new Uint8Array([3, 1, 2, 3, 4, 5])
)
).toEqual(
new Uint8Array([0x31, 0x23, 0x45])
);
});
it('converts an number of values (array)', (): void => {
expect(
fromNibbles(Uint8Array.from([
3, 1, 2, 3, 4, 5, 7, 8
]))
).toEqual(
new Uint8Array([0x31, 0x23, 0x45, 0x78])
);
});
});
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @name fromNibbles
* @summary Converts the input to Nibbles.
* @description
* From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input.
* @example
* <BR>
*
* ```javascript
* import { fromNibbles } from '@polkadot/trie-codec/util';
*
* fromNibbles(new Uint8Array([4, 1, 2, 0])); // => Uint8Array([0x41, 0x20]
* ```
*/
export default function fromNibbles (input: Uint8Array): Uint8Array {
const u8a = new Uint8Array(input.length / 2);
for (let index = 0; index < u8a.length; index++) {
const nibIndex = index << 1;
u8a[index] = (input[nibIndex] << 4) + input[nibIndex + 1];
}
return u8a;
}
@@ -1,34 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { assert, u8aConcat } from '@polkadot/util';
import { EXTENSION_NODE_BIG, EXTENSION_NODE_OFFSET, LEAF_NODE_BIG, LEAF_NODE_OFFSET } from '../constants';
import fromNibbles from './fromNibbles';
const MAX_FUSE_LENGTH = 255 + 126;
export default function fuseNibbles (nibbles: Uint8Array, isLeaf: boolean): Uint8Array {
assert(nibbles.length < MAX_FUSE_LENGTH, `Input to fuseNibbles too large, found ${nibbles.length} >= ${MAX_FUSE_LENGTH}`);
const [firstByteSmall, bigThreshold] = isLeaf
? [LEAF_NODE_OFFSET, LEAF_NODE_BIG - LEAF_NODE_OFFSET]
: [EXTENSION_NODE_OFFSET, EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET];
const result: Uint8Array[] = [
Uint8Array.from([firstByteSmall + Math.min(nibbles.length, bigThreshold)])
];
const oddFlag = nibbles.length % 2;
if (nibbles.length >= bigThreshold) {
result.push(Uint8Array.from([nibbles.length - bigThreshold]));
}
if (oddFlag === 1) {
result.push(nibbles.subarray(0, 1));
}
result.push(fromNibbles(nibbles.subarray(oddFlag)));
return u8aConcat(...result);
}
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as fromNibbles } from './fromNibbles';
export { default as fuseNibbles } from './fuseNibbles';
export { default as sharedPrefixLength } from './sharedPrefixLength';
export { default as toNibbles } from './toNibbles';
@@ -1,15 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default function sharedPrefixLength (first: Uint8Array, second: Uint8Array): number {
const length = Math.min(first.length, second.length);
for (let index = 0; index < length; index++) {
if (first[index] !== second[index]) {
return index;
}
}
return length;
}
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import stringToU8a from '@polkadot/util/string/toU8a';
import toNibbles from './toNibbles';
describe('toNibbles', (): void => {
it('converts an array', (): void => {
expect(
toNibbles(Uint8Array.from([
0x31, 0x23, 0x45
]))
).toEqual(
new Uint8Array([3, 1, 2, 3, 4, 5])
);
});
it('converts a single', (): void => {
expect(
toNibbles(
stringToU8a('A')
)
).toEqual(
new Uint8Array([4, 1])
);
});
});
-35
View File
@@ -1,35 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @name toNibbles
* @summary Converts the input to Nibbles.
* @description
* From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input.
* @example
* <BR>
*
* ```javascript
* import { toNibbles } from '@polkadot/trie-codec/util';
*
* toNibbles(new Uint8Array([0x41, 0x20]); // => Uint8Array([4, 1, 2, 0])
* ```
*/
export default function toNibbles (input?: Uint8Array | null): Uint8Array {
if (!input) {
return new Uint8Array();
}
const result = new Uint8Array(input.length * 2);
for (let index = 0; index < input.length; index++) {
const nibIndex = index << 1;
const byte = input[index];
result[nibIndex] = byte >> 4;
result[nibIndex + 1] = byte & 0b1111;
}
return result;
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-23
View File
@@ -1,23 +0,0 @@
# @polkadot/trie-db
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 codecs, by default only the Substrate codec.
## Usage
Installation -
```
yarn add @polkadot/trie-db
```
Classes can be imported as follows:
```js
import Trie from '@polkadot/trie-db'; // Default export
```
## Utilities
[Utilities](SUMMARY.md)
-40
View File
@@ -1,40 +0,0 @@
{
"name": "@polkadot/trie-db",
"version": "1.3.1",
"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"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/common.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-db#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/db": "^1.3.1",
"@polkadot/trie-codec": "^1.3.1",
"@polkadot/trie-hash": "^1.3.1",
"@polkadot/util": "^1.3.1",
"@polkadot/util-crypto": "^1.3.1"
},
"devDependencies": {
"@polkadot/chainspec": "^1.3.1",
"@polkadot/util-rlp": "^1.3.1",
"ethereumjs-testing": "1.0.4"
}
}
-30
View File
@@ -1,30 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default class Checkpoint {
protected txRoot: Uint8Array;
protected rootHash: Uint8Array;
public constructor (rootHash: Uint8Array) {
this.rootHash = rootHash;
this.txRoot = rootHash;
}
protected createCheckpoint (): Uint8Array {
this.txRoot = this.rootHash;
return this.txRoot;
}
protected commitCheckpoint (): Uint8Array {
return this.rootHash;
}
protected revertCheckpoint (): Uint8Array {
this.rootHash = this.txRoot;
return this.rootHash;
}
}
-418
View File
@@ -1,418 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { TxDb, ProgressCb } from '@polkadot/db/types';
import { Codec } from '@polkadot/trie-codec/types';
import { EncodedPath, TrieDb, Node, NodeBranch, NodeEncodedOrEmpty, NodeKv, NodeNotEmpty, NodeType, TrieEntry } from './types';
import substrateCodec from '@polkadot/trie-codec';
import { decodeNibbles, encodeNibbles, extractNodeKey } from '@polkadot/trie-codec/nibbles';
import { isNull, u8aConcat } from '@polkadot/util';
import { isBranchNode, isEmptyNode, isExtensionNode, isKvNode, isLeafNode } from './util/is';
import { keyEquals, keyStartsWith, computeExtensionKey, computeLeafKey, consumeCommonPrefix } from './util/key';
import { getNodeType, decodeNode, encodeNode } from './util/node';
import Checkpoint from './Checkpoint';
import constants, { Constants } from './constants';
interface Normalized {
index: number;
value: EncodedPath;
}
const BLANK_BRANCH: EncodedPath[] = [
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null
];
/**
* # @polkadot/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 Impl extends Checkpoint {
public readonly db: TxDb;
protected codec: Codec;
protected constants: Constants;
public constructor (db: TxDb, rootHash?: Uint8Array, codec: Codec = substrateCodec) {
const _constants = constants(codec);
super(rootHash || _constants.EMPTY_HASH);
this.db = db;
this.codec = codec;
this.constants = _constants;
}
protected _entry (root: Uint8Array): TrieEntry | null {
const [encoded, node] = this._getNodeRaw(root);
if (isNull(encoded) || isNull(node)) {
return null;
}
return [root, encoded, node.filter((u8a): boolean => !!u8a && u8a.length === 32) as Uint8Array[]];
}
protected _entries (root: Uint8Array, entries: TrieEntry[] = []): TrieEntry[] {
// l.debug(() => ['entries', { root }]);
const entry = this._entry(root);
if (!entry) {
return entries;
}
entries.push(entry);
entry[2].forEach((u8a): void => {
this._entries(u8a, entries);
});
return entries;
}
protected _snapshot (dest: TrieDb, fn: ProgressCb | undefined, root: Uint8Array, keys: number, percent: number, depth: number): number {
// l.debug(() => ['snapshot', { root }]);
const [encoded, node] = this._getNodeRaw(root);
if (isNull(encoded) || isNull(node)) {
return keys;
}
dest.db.put(root, encoded);
fn && fn({ keys: ++keys, percent });
node.forEach((u8a): void => {
if (u8a && u8a.length === 32) {
keys = this._snapshot(dest, fn, u8a, keys, percent, depth + 1);
}
percent += (100 / node.length) / Math.pow(16, depth);
});
return keys;
}
protected _getNodeRaw (hash: Uint8Array | null): [Uint8Array | null, Node] {
// l.debug(() => ['_getNode', { hash }]);
if (!hash || hash.length === 0 || keyEquals(hash, this.constants.EMPTY_HASH)) {
return [null, null];
} else if (hash.length < 32) {
return [hash, decodeNode(this.codec, hash)];
}
const raw = this.db.get(hash);
return [raw, decodeNode(this.codec, raw)];
}
protected _getNode (hash: Uint8Array | null): Node {
// l.debug(() => ['_getNode', { hash }]);
if (!hash || hash.length === 0 || keyEquals(hash, this.constants.EMPTY_HASH)) {
return null;
} else if (hash.length < 32) {
return decodeNode(this.codec, hash);
}
return decodeNode(this.codec, this.db.get(hash));
}
protected _del (node: Node, trieKey: Uint8Array): Node {
// l.debug(() => ['_del', { node, trieKey }]);
if (isEmptyNode(node)) {
return null;
} else if (isBranchNode(node)) {
return this._delBranchNode(node, trieKey);
} else if (isKvNode(node)) {
return this._delKvNode(node, trieKey);
}
throw new Error('Unreachable');
}
protected _delBranchNode (node: NodeBranch, trieKey: Uint8Array): Node {
// l.debug(() => ['_delBranchNode', { node, trieKey }]);
if (trieKey.length === 0) {
node[node.length - 1] = null;
return this._normaliseBranchNode(node);
}
const nodeToDelete = this._getNode(node[trieKey[0]]);
const subNode = this._del(nodeToDelete, trieKey.subarray(1));
const encodedSubNode = this._persistNode(subNode);
if (keyEquals(encodedSubNode, node[trieKey[0]])) {
return node;
}
node[trieKey[0]] = encodedSubNode;
return isNull(encodedSubNode)
? this._normaliseBranchNode(node)
: node;
}
protected _delKvNode (node: NodeNotEmpty, trieKey: Uint8Array): Node {
// l.debug(() => ['_delKvNode', { node, trieKey }]);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
if (!keyStartsWith(trieKey, currentKey)) {
return node;
} else if (nodeType === NodeType.LEAF) {
return keyEquals(trieKey, currentKey)
? null
: node;
}
const subKey = trieKey.subarray(currentKey.length);
const subNode = this._getNode(node[1]);
const newSub = this._del(subNode, subKey);
const encodedNewSub = this._persistNode(newSub);
if (keyEquals(encodedNewSub, node[1])) {
return node;
} else if (isNull(newSub)) {
return null;
}
if (isKvNode(newSub)) {
const subNibbles = decodeNibbles(newSub[0]);
const newKey = u8aConcat(currentKey, subNibbles);
return [encodeNibbles(newKey), newSub[1]];
} else if (isBranchNode(newSub)) {
return [encodeNibbles(currentKey), encodedNewSub];
}
throw new Error('Unreachable');
}
protected _get (node: Node, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_get', { node, trieKey }]);
if (isEmptyNode(node)) {
return null;
} else if (isBranchNode(node)) {
return this._getBranchNode(node, trieKey);
} else if (isKvNode(node)) {
return this._getKvNode(node, trieKey);
}
throw new Error('Invalid NodeType');
}
protected _getBranchNode (node: NodeBranch, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_getBranchNode', { node, trieKey }]);
if (trieKey.length === 0) {
return node[16];
}
const subNode = this._getNode(node[trieKey[0]]);
return this._get(subNode, trieKey.subarray(1));
}
protected _getKvNode (node: NodeKv, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_getKvNode', { node, trieKey }]);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
// l.debug(() => [{ currentKey, trieKey, nodeType }]);
if (nodeType === NodeType.LEAF) {
return keyEquals(trieKey, currentKey)
? node[1]
: null;
} else if (nodeType === NodeType.EXTENSION) {
if (keyStartsWith(trieKey, currentKey)) {
const subNode = this._getNode(node[1]);
return this._get(subNode, trieKey.subarray(currentKey ? currentKey.length : 0));
}
return null;
}
throw new Error('Unreachable');
}
protected _nodeToDbMapping (node: Node): NodeNotEmpty {
// l.debug(() => ['_nodeToDbMapping', { node }]);
if (isEmptyNode(node)) {
return [null, null];
}
const encoded = encodeNode(this.codec, node);
return (encoded.length < 32)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
? [node as any, null]
: [this.codec.hashing(encoded), encoded];
}
protected _normaliseBranchNode (node: NodeNotEmpty): Node {
// l.debug(() => ['_normaliseBranchNode', { node }]);
const mapped = node
.map((value, index): Normalized => ({ index, value }))
.filter(({ value }): boolean => !!value && value.length !== 0);
if (mapped.length >= 2) {
return node;
} else if (node[16]) {
return [computeLeafKey(new Uint8Array()), node[16]];
}
const [{ index, value }] = mapped;
const subNode = this._getNode(value);
if (isBranchNode(subNode)) {
return [encodeNibbles(new Uint8Array([index])), this._persistNode(subNode)];
} else if (isKvNode(subNode)) {
const subNibbles = decodeNibbles(subNode[0]);
const newKey = u8aConcat(new Uint8Array([index]), subNibbles);
return [encodeNibbles(newKey), subNode[1]];
}
throw new Error('Unreachable');
}
protected _persistNode (node: Node): NodeEncodedOrEmpty {
const [key, value] = this._nodeToDbMapping(node);
// l.debug(() => ['_persistNode', { node, key, value }]);
if (value) {
this.db.put(key as Uint8Array, value);
}
return key;
}
protected _put (node: Node, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_put', { node, trieKey, value }]);
if (isEmptyNode(node)) {
return [computeLeafKey(trieKey), value];
} else if (isKvNode(node)) {
return this._putKvNode(node, trieKey, value);
} else if (isBranchNode(node)) {
return this._putBranchNode(node, trieKey, value);
}
throw new Error('Unreachable');
}
protected _putBranchNode (node: NodeBranch, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_putBranchNode', { node, trieKey, value }]);
if (trieKey && trieKey.length) {
const subNode = this._getNode(node[trieKey[0]]);
const newNode = this._put(subNode, trieKey.subarray(1), value);
node[trieKey[0]] = this._persistNode(newNode);
} else {
node[node.length - 1] = value;
}
return node;
}
protected _putKvNode (node: NodeKv, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_putKvNode', { node, trieKey, value }]);
const currentKey = extractNodeKey(node);
const [commonPrefix, currentRemainder, trieRemainder] = consumeCommonPrefix(currentKey, trieKey);
const isExtension = isExtensionNode(node);
const isLeaf = isLeafNode(node);
let newNode: NodeNotEmpty;
// l.debug(() => ['_putKvNode', { currentKey, commonPrefix, currentRemainder, trieRemainder }]);
if (currentRemainder.length === 0 && trieRemainder.length === 0) {
if (isLeaf) {
return [node[0], value];
}
const subNode = this._getNode(node[1]);
newNode = this._put(subNode, trieRemainder, value);
} else if (currentRemainder.length === 0) {
if (isExtension) {
const subNode = this._getNode(node[1]);
newNode = this._put(subNode, trieRemainder, value);
} else {
const subPosition = trieRemainder[0];
const subKey = computeLeafKey(trieRemainder.subarray(1));
const subNode: NodeKv = [subKey, value];
newNode = BLANK_BRANCH.concat(node[1]) as NodeNotEmpty;
newNode[subPosition] = this._persistNode(subNode);
}
} else {
newNode = BLANK_BRANCH.concat(null) as NodeNotEmpty;
if (currentRemainder.length === 1 && isExtension) {
newNode[currentRemainder[0]] = node[1];
} else {
const computedKey = isExtension
? computeExtensionKey(currentRemainder.subarray(1))
: computeLeafKey(currentRemainder.subarray(1));
newNode[currentRemainder[0]] = this._persistNode([computedKey, node[1]]);
}
if (trieRemainder.length) {
newNode[trieRemainder[0]] = this._persistNode([computeLeafKey(trieRemainder.subarray(1)), value]);
} else {
newNode[16] = value;
}
}
// l.debug(() => ['newNode', newNode]);
if (commonPrefix.length) {
return [computeExtensionKey(commonPrefix), this._persistNode(newNode)];
}
return newNode;
}
protected _setRootNode (node: Node): void {
// l.debug(() => ['_setRootNode', { node }]);
if (isEmptyNode(node)) {
this.rootHash = this.constants.EMPTY_HASH;
} else {
const encoded = encodeNode(this.codec, node);
const rootHash = this.codec.hashing(encoded);
// l.debug(() => ['_setRootNode', { encoded, rootHash }]);
this.db.put(rootHash, encoded);
this.rootHash = rootHash;
}
}
}

Some files were not shown because too many files have changed in this diff Show More