Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd20fe6c8b | ||
|
|
28f8ca73aa | ||
|
|
f4a8bfc0c0 | ||
|
|
94b058d6a3 | ||
|
|
3d7ddb85a2 | ||
|
|
f7a2bb895f | ||
|
|
c1bfcc00b6 | ||
|
|
b16d8e7c26 | ||
|
|
2a4b363fcd | ||
|
|
de689b8e6f | ||
|
|
2e72ab920b | ||
|
|
565e6baecd | ||
|
|
1e15203b6c | ||
|
|
cc8639565d | ||
|
|
b77d2e6860 | ||
|
|
e1fbd8ff9f | ||
|
|
f56dd32b4a | ||
|
|
6077bef570 | ||
|
|
377d83d4ed | ||
|
|
bdb14f91a8 | ||
|
|
cc5b7ed0ad | ||
|
|
d4491aeb7f | ||
|
|
0f6e996799 | ||
|
|
1f3dd60a8d | ||
|
|
3351fb1cba | ||
|
|
32d176e424 | ||
|
|
aec1e26cb9 | ||
|
|
7d529b6c93 | ||
|
|
e22b39ae01 | ||
|
|
18a202c460 | ||
|
|
fd9ce319a5 | ||
|
|
a04c0a5e82 | ||
|
|
06cb5e57a0 | ||
|
|
103ea045bf | ||
|
|
4315c76814 | ||
|
|
6de6b871cd | ||
|
|
82e5d76821 | ||
|
|
d9a18a4acf | ||
|
|
2d1d4f808e | ||
|
|
d1de30907f | ||
|
|
d3583dc432 | ||
|
|
bb04fa28f7 | ||
|
|
bd8e862b62 | ||
|
|
0f45b7fbf3 | ||
|
|
03eb72f128 | ||
|
|
f76a4a98be | ||
|
|
c2b91ad8c2 | ||
|
|
ffc6b0323b | ||
|
|
b666db2721 | ||
|
|
b00d49564f | ||
|
|
34380caf1f | ||
|
|
277cc2b5a8 | ||
|
|
733e9e2729 | ||
|
|
482264c615 | ||
|
|
5d0abef952 | ||
|
|
2397e1c5d7 | ||
|
|
62ebe257a6 | ||
|
|
a2844a449c | ||
|
|
60a9866abe | ||
|
|
b196158125 | ||
|
|
6b1caacfb9 | ||
|
|
a7679fb07c | ||
|
|
c4acca6c7c | ||
|
|
5012792693 | ||
|
|
d40d6c65f7 | ||
|
|
2c0d8e4b59 | ||
|
|
d3d8caa0df | ||
|
|
a8f8525c9d | ||
|
|
caa5a8b9e6 | ||
|
|
ce6187f378 | ||
|
|
fe9c7a8a80 | ||
|
|
d5584c1837 | ||
|
|
adb1c1fea4 | ||
|
|
c87c228ab1 | ||
|
|
cbec4add88 | ||
|
|
6429cc307c | ||
|
|
c98e994777 | ||
|
|
697a452ba6 | ||
|
|
f68294c4e7 | ||
|
|
0130d18945 | ||
|
|
15c9904c96 | ||
|
|
add2749967 | ||
|
|
fe2f054389 | ||
|
|
bb1c117727 | ||
|
|
27c474bd78 | ||
|
|
039b5ec932 | ||
|
|
9eea21e0c4 | ||
|
|
aab533f92e | ||
|
|
2159270d80 | ||
|
|
f1b09eb2e5 | ||
|
|
d08cf8b5fe | ||
|
|
941618b830 | ||
|
|
983ca718ec | ||
|
|
41ebdd5c59 | ||
|
|
8971c89081 | ||
|
|
d1934060e0 | ||
|
|
6d9da39d8b | ||
|
|
4ed096024e | ||
|
|
ae36d58802 | ||
|
|
c8100dbe43 | ||
|
|
28d2ce38bd | ||
|
|
afce99ed1a | ||
|
|
29d13ab19c | ||
|
|
68a8bcb7db | ||
|
|
d2ecf1730a | ||
|
|
af56c10278 | ||
|
|
42f318fcb5 | ||
|
|
336df0d76d | ||
|
|
d85cedf5a0 | ||
|
|
a59187bce6 | ||
|
|
f9a5b75e10 | ||
|
|
87228149d4 | ||
|
|
67f36f6a13 | ||
|
|
75a9898daf | ||
|
|
0f726ce777 | ||
|
|
765f9baf44 | ||
|
|
2d181df360 | ||
|
|
77ff703a08 | ||
|
|
804ed13d0a | ||
|
|
341a6b0c08 | ||
|
|
614985b8ac | ||
|
|
d5bfa8c3c4 | ||
|
|
359981d2ef | ||
|
|
b0ee79f90c | ||
|
|
c2d595fb3f | ||
|
|
f837200a73 | ||
|
|
ea7dd553a2 | ||
|
|
7c1ca3a5c9 | ||
|
|
75cd547b49 | ||
|
|
91c4c407a9 | ||
|
|
20b46a65fa | ||
|
|
c60459e303 | ||
|
|
92ab4699b3 | ||
|
|
932f4c25f5 | ||
|
|
aaa35a8198 | ||
|
|
9708131620 | ||
|
|
c539430a0b | ||
|
|
8defc792a9 | ||
|
|
76a0daeed6 | ||
|
|
e236fdc396 | ||
|
|
e30dd7c0d9 | ||
|
|
f3ac6b2674 | ||
|
|
171015fbba | ||
|
|
dca36e41fd | ||
|
|
a602b0409c | ||
|
|
04d79da155 | ||
|
|
81a31519db | ||
|
|
78e39dcf34 | ||
|
|
6194660b3b | ||
|
|
2e08018718 | ||
|
|
b0d6ccdbd4 | ||
|
|
48b753b8ac | ||
|
|
506bc59f86 | ||
|
|
f86fcc6044 | ||
|
|
e8d2a439d5 | ||
|
|
9fa6b5bffa | ||
|
|
932ef41aae | ||
|
|
3910853ba1 | ||
|
|
6956e88708 | ||
|
|
3769b99cd2 | ||
|
|
ee17054b38 | ||
|
|
72cfbddd4a | ||
|
|
cffb23728d | ||
|
|
a69dc01c78 | ||
|
|
d889c71056 | ||
|
|
8eef3f9989 | ||
|
|
3112e43715 | ||
|
|
fc9a5ac25f | ||
|
|
242b107752 | ||
|
|
bf5ba0f405 | ||
|
|
e4de3a1339 | ||
|
|
69279f1b81 | ||
|
|
303c822d48 | ||
|
|
90ca8a0d78 | ||
|
|
94bbc6f2ee | ||
|
|
f4be1fe52e | ||
|
|
d3f6f3621b | ||
|
|
ea9ad6f389 | ||
|
|
b03ce51a31 | ||
|
|
b8411bb0ea | ||
|
|
36b53c5a8e | ||
|
|
e60bbbeb59 | ||
|
|
eb90564260 | ||
|
|
1c151ca04a | ||
|
|
249919502a | ||
|
|
a2f9614ce8 | ||
|
|
98bdc9950a | ||
|
|
1387839696 | ||
|
|
4e8cb2af2f | ||
|
|
dd0de55638 | ||
|
|
e09d0ca5ca | ||
|
|
41f024d0fc | ||
|
|
4ce452b40a | ||
|
|
0a8ab20744 | ||
|
|
d108970d09 | ||
|
|
7fb1adb94e | ||
|
|
b7635d7e2b | ||
|
|
2273ce8bd3 | ||
|
|
cfdf629b49 | ||
|
|
f5f35ee3bf | ||
|
|
c776f0d815 | ||
|
|
c1a23937bd | ||
|
|
241febb707 | ||
|
|
357c7368d2 | ||
|
|
4e4ff5de4b | ||
|
|
8d80bf869b | ||
|
|
337c67ff30 | ||
|
|
66573f6234 | ||
|
|
408129d5ca | ||
|
|
efa6661817 | ||
|
|
c988d5011c | ||
|
|
f173bb3d2a | ||
|
|
1f0368061f | ||
|
|
45ef924862 | ||
|
|
dec88b6ab7 | ||
|
|
ed402341dc | ||
|
|
76a9f2787c | ||
|
|
5b1c9b8ccb | ||
|
|
af751c6c89 | ||
|
|
4ab8dd70bd | ||
|
|
a5f59ca926 | ||
|
|
71f26aac8d | ||
|
|
cc7d6a2e01 | ||
|
|
e29f0a3920 | ||
|
|
f38975d126 | ||
|
|
dc4b59bb0c | ||
|
|
2f5df085b6 | ||
|
|
225ca1de00 | ||
|
|
aeb500e804 | ||
|
|
e9dd6f1efc | ||
|
|
563dbbf7e4 | ||
|
|
5a5bc7da0b | ||
|
|
fb2c51a49b | ||
|
|
568e3b7840 | ||
|
|
87d69d7098 | ||
|
|
255cd93bf4 | ||
|
|
ef5780996e | ||
|
|
5155ae8d2b | ||
|
|
f1447ffcbc | ||
|
|
64e9ec5044 | ||
|
|
05986f6d64 | ||
|
|
caca69525a | ||
|
|
845398846c | ||
|
|
412ca6ccd7 | ||
|
|
9232fd5a91 | ||
|
|
49174d181e | ||
|
|
c5bc09fde7 | ||
|
|
1a436906f5 | ||
|
|
d7bb55c003 | ||
|
|
50f015a713 | ||
|
|
1c94508d61 | ||
|
|
ddb007de7b | ||
|
|
8bee7d5d6b | ||
|
|
253eea9249 | ||
|
|
502fdc1e32 | ||
|
|
f3aaaede25 | ||
|
|
309d691938 | ||
|
|
4d6438c3e7 | ||
|
|
19817b213b | ||
|
|
20d4457483 | ||
|
|
a2d0f2b1a3 | ||
|
|
a512766bfb | ||
|
|
b11b42e2b6 | ||
|
|
c13c2022ca | ||
|
|
bf1c187969 | ||
|
|
16d077c87d | ||
|
|
00374effc5 | ||
|
|
891a855fb8 | ||
|
|
854cb56621 | ||
|
|
1018a11548 | ||
|
|
dc55f2170f | ||
|
|
36cd5cd504 | ||
|
|
a5d23696e6 | ||
|
|
5adc753f81 | ||
|
|
5e494b7163 |
+2
-1
@@ -1 +1,2 @@
|
||||
1
|
||||
5
|
||||
2.6.22.12.2
|
||||
@@ -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,3 +1,4 @@
|
||||
.eslintrc.js
|
||||
**/build/*
|
||||
**/coverage/*
|
||||
**/node_modules/*
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ module.exports = {
|
||||
parserOptions: {
|
||||
...base.parserOptions,
|
||||
project: [
|
||||
'./tsconfig.eslint.json'
|
||||
'./tsconfig.json'
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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 }}
|
||||
@@ -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"
|
||||
@@ -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
@@ -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
+56
File diff suppressed because one or more lines are too long
+11
@@ -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
|
||||
+211
-19
@@ -1,18 +1,146 @@
|
||||
# 1.2.1
|
||||
# CHANGELOG
|
||||
|
||||
## 2.13.1 Jun 8, 2020
|
||||
|
||||
- Fix JS blake2 fallback (non-wasm) to correctly deal with hex inputs
|
||||
- Align `bnToHex` signature with `bnToU8a` (with old/new style)
|
||||
- Allow `bnTo{Hex,U8a}` to take any value with `.toBn()` signatures
|
||||
|
||||
## 2.12.2 Jun 1, 2020
|
||||
|
||||
- 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)
|
||||
@@ -20,7 +148,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)`
|
||||
@@ -28,69 +156,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
|
||||
|
||||
@@ -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
@@ -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
@@ -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'
|
||||
});
|
||||
|
||||
@@ -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
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.2.1"
|
||||
"version": "2.13.1"
|
||||
}
|
||||
|
||||
+17
-16
@@ -1,29 +1,30 @@
|
||||
{
|
||||
"version": "1.2.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.10.2",
|
||||
"@polkadot/dev": "^0.55.8",
|
||||
"@polkadot/ts": "^0.3.26",
|
||||
"@types/jest": "^25.2.3"
|
||||
},
|
||||
"version": "2.13.1"
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -1,7 +0,0 @@
|
||||
# @polkadot/chainspec
|
||||
|
||||
Chainspecs for known chains
|
||||
|
||||
## Utilities
|
||||
|
||||
[Utilities](SUMMARY.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"name": "@polkadot/chainspec",
|
||||
"version": "1.2.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.2.1"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -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';
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"name": "@polkadot/db",
|
||||
"version": "1.2.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.2.1",
|
||||
"@polkadot/util": "^1.2.1",
|
||||
"lru_map": "^0.3.3"
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/keyring",
|
||||
"version": "1.2.1",
|
||||
"version": "2.13.1",
|
||||
"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.2.1",
|
||||
"@polkadot/util-crypto": "^1.2.1"
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/util": "2.13.1",
|
||||
"@polkadot/util-crypto": "2.13.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,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);
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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,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,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,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,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,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
|
||||
);
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,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,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,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,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 => {
|
||||
|
||||
@@ -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,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,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;
|
||||
|
||||
@@ -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.
|
||||
@@ -1,7 +0,0 @@
|
||||
# @polkadot/trie-codec
|
||||
|
||||
Implementation of the Substrate-specific codec for a Trie
|
||||
|
||||
## Utilities
|
||||
|
||||
[Utilities](SUMMARY.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"name": "@polkadot/trie-codec",
|
||||
"version": "1.2.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.2.1"
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
// }
|
||||
@@ -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'
|
||||
));
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
// }
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -1,40 +0,0 @@
|
||||
{
|
||||
"name": "@polkadot/trie-db",
|
||||
"version": "1.2.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.2.1",
|
||||
"@polkadot/trie-codec": "^1.2.1",
|
||||
"@polkadot/trie-hash": "^1.2.1",
|
||||
"@polkadot/util": "^1.2.1",
|
||||
"@polkadot/util-crypto": "^1.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/chainspec": "^1.2.1",
|
||||
"@polkadot/util-rlp": "^1.2.1",
|
||||
"ethereumjs-testing": "1.0.4"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
Reference in New Issue
Block a user