Compare commits

..
109 Commits
Author SHA1 Message Date
Github Actions 3112e43715 [CI Skip] 2.2.1
skip-checks: true
2020-02-06 14:46:00 +00:00
Jaco Greeff fc9a5ac25f 2.2 (#520) 2020-02-06 15:44:11 +01:00
Github Actions 242b107752 [CI Skip] 2.2.0-beta.0
skip-checks: true
2020-02-06 13:51:56 +00:00
Jaco Greeff bf5ba0f405 Add resolver for jest (#519) 2020-02-06 14:49:55 +01:00
Github Actions e4de3a1339 [CI Skip] 2.1.1
skip-checks: true
2020-02-04 12:53:47 +00:00
Jaco Greeff 69279f1b81 2.1 (#518) 2020-02-04 13:51:51 +01:00
Github Actions 303c822d48 [CI Skip] 2.1.0-beta.1
skip-checks: true
2020-02-04 10:39:58 +00:00
Jaco Greeff 90ca8a0d78 Backwards compat. on detctPackage (#517) 2020-02-04 11:38:00 +01:00
Github Actions 94bbc6f2ee [CI Skip] 2.1.0-beta.0
skip-checks: true
2020-02-03 12:23:51 +00:00
Jaco Greeff f4be1fe52e Multiple versions with __dirname (#515)
* Multiple versions with __dirname

* Fallback for __dirname

* Update path

* Flatten versions extracted

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

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

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

* Remove mdEngine

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

* Update dev

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

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

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

* Add KDF case for double ratchet

* chore: add .idea in .gitignore

* chore: add .vscode to .gitignore

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

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

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

* Throw in condition

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

* nobody -> derive

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

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

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

* Expose setSS58Format everywhere

* Remove setAddressPrefix

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

* Add tests
2019-09-12 13:48:06 +02:00
Travis CI 891a855fb8 [CI Skip] 1.4.0-beta.0 2019-09-11 10:33:22 +00:00
Jaco Greeff 854cb56621 Bump deps (#469) 2019-09-11 12:25:47 +02:00
Travis CI 1018a11548 [CI Skip] 1.3.1 2019-09-10 17:14:48 +00:00
Jaco Greeff dc55f2170f 1.3.1 (#467)
* 1.3.1

* CHANGELOG bump
2019-09-10 19:08:12 +02:00
Travis CI 36cd5cd504 [CI Skip] 1.3.0-beta.1 2019-09-10 15:51:48 +00:00
Jaco Greeff a5d23696e6 Remove ExtError 2019-09-10 17:44:47 +02:00
Travis CI 5adc753f81 [CI Skip] 1.3.0-beta.0 2019-09-10 15:16:34 +00:00
Jaco Greeff 5e494b7163 Fix ExtError construction 2019-09-10 17:03:21 +02:00
411 changed files with 4937 additions and 9507 deletions
+1 -1
View File
@@ -1 +1 @@
1
4
-21
View File
@@ -1,21 +0,0 @@
version: 2
jobs:
build:
working_directory: ~/polkadot-js
docker:
- image: circleci/node:10
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
- run:
name: install-deps
command: yarn install --frozen-lockfile
- save_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
paths:
- ./node_modules
- ~/.cache/yarn
- run:
name: build
command: yarn polkadot-dev-circleci-build
+1 -1
View File
@@ -5,7 +5,7 @@ module.exports = {
parserOptions: {
...base.parserOptions,
project: [
'./tsconfig.eslint.json'
'./tsconfig.json'
]
}
};
+73
View File
@@ -0,0 +1,73 @@
name: PR
on: [pull_request]
jobs:
lint:
name: Linting
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: lint
run: |
yarn install --frozen-lockfile
yarn lint
test:
name: Testing
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: test
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
run: |
yarn install --frozen-lockfile
yarn test
build_code:
name: Build Code
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build
run: |
yarn install --frozen-lockfile
yarn build
build_docs:
name: Build Docs
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build
run: |
yarn install --frozen-lockfile
yarn docs
+67
View File
@@ -0,0 +1,67 @@
name: Master
on:
push:
branches:
- master
jobs:
build_code:
name: Build Code
if: "! contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
with:
token: ${{ secrets.GH_PAT }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAT: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --frozen-lockfile
yarn polkadot-dev-ghact-build
build_docs:
name: Build Docs
if: "! contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build
env:
GH_PAT: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
GH_PAGES_SRC: build-docs
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
yarn install --frozen-lockfile
yarn polkadot-dev-ghact-docs
dummy:
name: Dummy
if: "contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x]
steps:
- name: dummy
run: |
echo "Dummy skip step"
+2
View File
@@ -20,3 +20,5 @@ yarn-debug.log*
yarn-error.log*
store.db
store.db.compacted
.idea
.vscode
-28
View File
@@ -1,28 +0,0 @@
language: node_js
node_js:
- "10"
env:
global:
- CC_TEST_REPORTER_ID=27a299582eb7fd9580e27897a6ecda1c82a1cd24bcfe2f2ebda1ca70238509b4
- GH_PAGES_SRC="build-docs"
cache:
yarn: true
directories:
- node_modules
before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- export PATH=$HOME/.yarn/bin:$(yarn global bin):$PATH
before_script:
- ./cc-test-reporter before-build
script:
- yarn polkadot-dev-travis-build
after_script:
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
deploy:
skip_cleanup: true
provider: script
script: yarn polkadot-dev-travis-deploy
on:
branch: master
+48
View File
@@ -1,3 +1,51 @@
# 2.2.1
- Add resolved for jest requires (tests from src)
# 2.1.1
- Update `detectPackage(<package.json>, __dirname?)` with calling folder
# 2.0.1
- 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
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)
# 1.7.1
- `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
- `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
- 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
- **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
- 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
- Keyring `addFromAddress` can now be used to store external accounts, for example those provided by external signers
-7
View File
@@ -16,13 +16,6 @@ This repository is split up into a number of internal packages, namely utilities
- [keyring](packages/keyring/) Keyring management
- [util](packages/util/) General utilities
- [util-crypto](packages/util-crypto/) Crypto and hashing utilities
- [util-rlp](packages/util-rlp/) RLP encoding & decoding
Various useful trie and database interfaces -
- [db](packages/db/) Sync memory and disk database interfaces
- [trie-db](packages/trie-db/) Merkle Patricia Tree implementation adapted for Polkadot
- [trie-hash](packages/trie-hash/) Calculate hashes (either ordered or unordered) from a set of inputs
## development
+3 -5
View File
@@ -3,11 +3,8 @@ 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',
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1'
},
modulePathIgnorePatterns: [
@@ -20,5 +17,6 @@ module.exports = Object.assign({}, config, {
'<rootDir>/packages/util/build',
'<rootDir>/packages/util-crypto/build',
'<rootDir>/packages/util-rlp/build'
]
],
resolver: './jest.resolver.js'
});
+15
View File
@@ -0,0 +1,15 @@
// 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.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
module.exports = function resolver (file, config) {
if (file.includes('package.json')) {
console.error(file, config);
return path.join(config.basedir.replace('/src', '/'), file);
}
return config.defaultResolver(file, config);
};
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.2.1"
"version": "2.2.1"
}
+7 -8
View File
@@ -1,5 +1,5 @@
{
"version": "1.2.1",
"version": "2.2.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -9,11 +9,11 @@
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.6.2"
"typescript": "^3.7.5"
},
"scripts": {
"build": "polkadot-dev-build-ts && polkadot-dev-build-docs",
"check": "yarn lint",
"build": "polkadot-dev-build-ts",
"docs": "polkadot-dev-build-docs",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"clean": "polkadot-dev-clean-build",
"postinstall": "polkadot-dev-yarn-only",
@@ -21,9 +21,8 @@
"test:one": "jest"
},
"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.8.3",
"@polkadot/dev": "^0.33.3",
"@polkadot/ts": "^0.2.1"
}
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-7
View File
@@ -1,7 +0,0 @@
# @polkadot/chainspec
Chainspecs for known chains
## Utilities
[Utilities](SUMMARY.md)
-31
View File
@@ -1,31 +0,0 @@
{
"name": "@polkadot/chainspec",
"version": "1.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
-6
View File
@@ -1,6 +0,0 @@
// Copyright 2017-2019 @polkadot/chainspec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as alexander } from './alexander';
export { default as driedDanta } from './dried-danta';
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2017-2019 @polkadot/chainspec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export type Telemetry = [string, number];
export interface Chainspec {
bootNodes: string[];
id: string;
genesis: {
raw: Record<string, string>;
};
genesisRoot?: string;
name: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
properties: null | Record<string, any>;
protocolId: string | null;
telemetryUrl?: string | null;
telemetryEndpoints?: Telemetry[];
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-24
View File
@@ -1,24 +0,0 @@
# @polkadot/db
This is an implementation of a basic sync in-memory and on-disk database with overlays. Memory is currently used by polkadot-js/client
## Usage
Installation -
```
yarn add @polkadot/db
```
Classes can be imported as follows:
```js
// Default exports
import DiskDb from '@polkadot/db/Disk';
import MemoryDb from '@polkadot/db/Memory';
import TransactionDb from '@polkadot/db/engines/TransactionDb';
```
## Utilities
[Utilities](SUMMARY.md)
-33
View File
@@ -1,33 +0,0 @@
{
"name": "@polkadot/db",
"version": "1.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"
}
}
-68
View File
@@ -1,68 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import MemoryDb from './engines/MemoryDb';
import TransactionDb from './engines/TransactionDb';
/**
* @name MemoryDb
* @summary Creates a MemoryDb database extending TransactionDb
* @description Create an instance of a Memory database using
* MemoryDb and extending TransactionDb.
* `options` argument (optional) used to specifies whether
* to use compression.
* - Enable compression when storing "blocks" since they compress well.
* - Disable compression when storing "state" Transactions Trie
* using @polkadot/trie-db or @polkadot/db/src/engines/TransactionDb.ts
* (potentially LevelDb or RocksDb implementation of a Merkle Patricia Trie)
* data structure serialised with Recursive Length Prefix (RLP) encoding
* @example
* <BR>
*
* ```javascript
* import stringToU8a from '@polkadot/util/string/toU8a';
* import MemoryDb from '@polkadot/db/Memory';
* import TransactionDb from '@polkadot/db/engines/TransactionDb';
*
* const memoryDb = new MemoryDb();
* const txDb = new TransactionDb(memoryDb);
*
* // Open the memory database
* memoryDb.open();
*
* // Declare key/value pair to allocate to store under a the key
* const key = stringToU8a('key');
* const value = stringToU8a('some value');
*
* // Store key/value pair in memory db
* memoryDb.put(key, value);
*
* // Retrieve value for key from memory db
* valueRetrieved = memoryDb.get(key);
*
* // Delete key/value pair from memory db
* memoryDb.del(key);
*
* // Transaction to Store key/value pair in transaction db
* const isTxSuccess = txDb.transaction((): void => {
* txDb.put(key, value);
*
* // Boolean to indicate whether transaction was successful or not
* return true;
* });
*
* console.log(`Transaction successful?: ${isTxSuccess}`);
*
* // Retrieve transaction value from memory db
* console.log(`Transfered value: ${memoryDb.get(key)}`);
*
* // Close the memory database
* memoryDb.close();
* ```
*/
export default class Memory extends TransactionDb {
public constructor () {
super(new MemoryDb());
}
}
-63
View File
@@ -1,63 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/u8a/toU8a';
import LruDb from './LruDb';
import MemoryDb from './MemoryDb';
describe('LruDb', (): void => {
const memory = new MemoryDb();
const db = new LruDb(memory);
it('retrieves an item from the backing when not available (caching it)', (): void => {
const key = toU8a('test1');
const value = toU8a('value1');
memory.put(key, value);
expect(db.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('replaces an item (caching and backing)', (): void => {
const key = toU8a('test1');
const value = toU8a('test');
db.put(key, value);
expect(db.get(key)).toEqual(value);
expect(memory.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('retrieves item from LRU when available', (): void => {
const key = toU8a('test1');
const value = toU8a('test');
memory.del(key);
expect(db.get(key)).toEqual(value);
});
it('puts item both in LRU and backing', (): void => {
const key = toU8a('test0');
const value = toU8a('value0');
db.put(key, value);
expect(memory.get(key)).toEqual(value);
expect(db._getLru(key)).toEqual({ value });
});
it('deletes an item from both backing and db', (): void => {
const key = toU8a('test0');
db.del(key);
expect(memory.get(key)).toEqual(null);
expect(db._getLru(key)).toEqual({ value: null });
expect(db.get(key)).toEqual(null);
});
});
-116
View File
@@ -1,116 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, ProgressCb } from '../types';
import { LRUMap } from 'lru_map';
import { logger } from '@polkadot/util';
interface CachedValue {
value: Uint8Array | null;
}
const DEFAULT_ITEM_COUNT = 4096;
const l = logger('db/lru');
export default class LruDb implements BaseDb {
private backing: BaseDb;
private lru: LRUMap<string, CachedValue>;
public constructor (backing: BaseDb, itemCount: number = DEFAULT_ITEM_COUNT) {
this.backing = backing;
this.lru = new LRUMap(itemCount);
}
public close (): void {
l.debug((): string[] => ['close']);
this.lru.clear();
this.backing.close();
}
public open (): void {
l.debug((): string[] => ['open']);
this.lru.clear();
this.backing.open();
}
public drop (): void {
this.backing.drop();
}
public empty (): void {
l.debug((): string[] => ['empty']);
this.lru.clear();
this.backing.empty();
}
public rename (base: string, file: string): void {
this.backing.rename(base, file);
}
public maintain (fn: ProgressCb): void {
this.backing.maintain(fn);
}
public size (): number {
return this.backing.size();
}
public del (key: Uint8Array): void {
const keyStr = key.toString();
this.backing.del(key);
this.lru.set(keyStr, { value: null });
}
public get (key: Uint8Array): Uint8Array | null {
const keyStr = key.toString();
const cached = this.lru.get(keyStr);
if (cached) {
return cached.value;
}
const value = this.backing.get(key);
this.lru.set(keyStr, { value });
return value;
}
// Convenience methods used in tests
public _getLru (key: Uint8Array): CachedValue | undefined {
return this.lru.get(key.toString());
}
public put (key: Uint8Array, value: Uint8Array): void {
const keyStr = key.toString();
this.backing.put(key, value);
this.lru.set(keyStr, { value });
}
public txCommit (): void {
if (this.backing.txCommit) {
this.backing.txCommit();
}
}
public txRevert (): void {
if (this.backing.txRevert) {
this.backing.txRevert();
}
}
public txStart (): void {
if (this.backing.txStart) {
this.backing.txStart();
}
}
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import MemoryDb from './MemoryDb';
describe('MemoryDb', (): void => {
const memory = new MemoryDb();
it('gets the combioned size of the entry values', (): void => {
memory.put(new Uint8Array([1]), new Uint8Array([1, 2, 3]));
memory.put(new Uint8Array([2]), new Uint8Array([1, 2, 3]));
memory.put(new Uint8Array([3]), new Uint8Array([1, 2, 3]));
expect(memory.size()).toEqual(9);
});
it('does not throw on the stubs', (done): void => {
memory.close();
memory.open();
memory.drop();
memory.empty();
memory.rename('foo', 'bar');
memory.maintain((): void => done());
});
});
-70
View File
@@ -1,70 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, ProgressCb } from '../types';
import { logger } from '@polkadot/util';
const l = logger('db/memory');
export default class MemoryDb implements BaseDb {
private _storage: Map<string, Uint8Array> = new Map();
public close (): void {
this.empty();
}
public open (): void {
this.empty();
}
public drop (): void {
this.empty();
}
public empty (): void {
this._storage.clear();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public rename (base: string, file: string): void {
l.warn('rename() is not implemented');
}
public maintain (fn: ProgressCb): void {
fn({
isCompleted: true,
keys: this._storage.size,
percent: 100
});
}
public size (): number {
let size = 0;
this._storage.forEach((value): void => {
size += value.length;
});
return size;
}
public del (key: Uint8Array): void {
// l.debug(() => ['del', { key }]);
this._storage.delete(key.toString());
}
public get (key: Uint8Array): Uint8Array | null {
// l.debug(() => ['get', { key }]);
return this._storage.get(key.toString()) || null;
}
public put (key: Uint8Array, value: Uint8Array): void {
// l.debug(() => ['put', { key, value }]);
this._storage.set(key.toString(), value);
}
}
@@ -1,93 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import toU8a from '@polkadot/util/string/toU8a';
import MemoryDb from './MemoryDb';
import TransactionDb from './TransactionDb';
describe('TransactionDb', (): void => {
const memory = new MemoryDb();
const db = new TransactionDb(memory);
it('passed through values immediately when not in transaction', (): void => {
const key = toU8a('test0');
const value = toU8a('value0');
db.put(key, value);
expect(memory.get(key)).toEqual(value);
});
it('commits when transaction passes (result = true, put)', (): void => {
const key = toU8a('test1');
const value = toU8a('value1');
expect(
db.transaction((): boolean => {
db.put(key, value);
return true;
})
).toEqual(true);
expect(memory.get(key)).toEqual(value);
});
it('commits when transaction passes (result = true, del)', (): void => {
const key = toU8a('test0');
expect(
db.transaction((): boolean => {
db.del(key);
return true;
})
).toEqual(true);
expect(memory.get(key)).toEqual(null);
});
it('does not commit when transaction fails (result = false)', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
expect(
db.transaction((): boolean => {
db.put(key, value);
return false;
})
).toEqual(false);
expect(memory.get(key)).toEqual(null);
});
it('does not commit when transaction throws', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
expect(
(): void => {
db.transaction((): void => {
db.put(key, value);
throw new Error('test');
});
}
).toThrow(/test/);
expect(memory.get(key)).toEqual(null);
});
it('inside the transaction, the value is set', (): void => {
const key = toU8a('test2');
const value = toU8a('value2');
db.transaction((): boolean => {
db.put(key, value);
expect(db.get(key)).toEqual(value);
return false;
});
expect(memory.get(key)).toEqual(null);
});
});
-157
View File
@@ -1,157 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BaseDb, TxDb, ProgressCb } from '../types';
import { assert, isNull, logger } from '@polkadot/util';
interface OverlayItem {
key: Uint8Array;
value: Uint8Array | null;
}
const l = logger('db/transact');
export default class TransactionDb implements TxDb {
private backing: BaseDb;
private txOverlay: Map<string, OverlayItem> = new Map();
private txStarted: boolean;
public constructor (backing: BaseDb) {
this.backing = backing;
this.txStarted = false;
}
public transaction<T> (fn: () => T): T {
l.debug((): string[] => ['transaction']);
try {
this.createTx();
const result = fn();
if (result) {
this.commitTx();
} else {
this.revertTx();
}
return result;
} catch (error) {
this.revertTx();
throw error;
}
}
public close (): void {
this.backing.close();
}
public open (): void {
this.backing.open();
}
public drop (): void {
this.backing.drop();
}
public empty (): void {
this.backing.empty();
}
public rename (base: string, file: string): void {
this.backing.rename(base, file);
}
public maintain (fn: ProgressCb): void {
assert(this.txStarted === false, 'Cannot maintain inside an open transaction');
this.backing.maintain(fn);
}
public size (): number {
return this.backing.size();
}
public del (key: Uint8Array): void {
if (this.txStarted) {
this.txOverlay.set(key.toString(), { key, value: null });
return;
}
this.backing.del(key);
}
public get (key: Uint8Array): Uint8Array | null {
// l.debug(() => ['get', u8aToHex(key)]);
if (this.txStarted) {
const value = this.txOverlay.get(key.toString());
if (value) {
return value.value;
}
}
return this.backing.get(key);
}
public put (key: Uint8Array, value: Uint8Array): void {
// l.debug(() => ['put', u8aToHex(key), u8aToHex(value)]);
if (this.txStarted) {
this.txOverlay.set(key.toString(), { key, value });
return;
}
return this.backing.put(key, value);
}
private createTx (): void {
l.debug((): string[] => ['createTx']);
assert(!this.txStarted, 'Cannot create a transaction when one is already active');
this.txOverlay.clear();
this.txStarted = true;
}
private commitTx (): void {
l.debug((): [string, number, string] => ['commitTx', Object.keys(this.txOverlay).length, 'keys']);
assert(this.txStarted, 'Cannot commit when not in transaction');
if (this.backing.txStart) {
this.backing.txStart();
}
this.txOverlay.forEach(({ key, value }): void => {
if (isNull(value)) {
this.backing.del(key);
} else {
this.backing.put(key, value);
}
});
if (this.backing.txCommit) {
this.backing.txCommit();
}
this.txOverlay.clear();
this.txStarted = false;
}
private revertTx (): void {
l.debug((): string[] => ['revertTx']);
assert(this.txStarted, 'Cannot revert when not in transaction');
this.txOverlay.clear();
this.txStarted = false;
}
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface ProgressValue {
isCompleted?: boolean;
keys: number;
percent: number;
}
export type ProgressCb = (progress: ProgressValue) => void;
export interface BaseDbOptions {
isCompressed?: boolean;
isLru?: boolean;
isNative?: boolean;
}
export interface BaseDb {
close (): void;
open (): void;
drop (): void;
empty (): void;
maintain (fn: ProgressCb): void;
rename (base: string, file: string): void;
size (): number;
txCommit?: () => void;
txRevert?: () => void;
txStart?: () => void;
del (key: Uint8Array): void;
get (key: Uint8Array): Uint8Array | null;
put (key: Uint8Array, value: Uint8Array): void;
}
export interface TxDb extends BaseDb {
transaction <T> (fn: () => T): T;
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "1.2.1",
"version": "2.2.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.8.3",
"@polkadot/util": "^2.2.1",
"@polkadot/util-crypto": "^2.2.1"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+12 -4
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { cryptoWaitReady, setAddressPrefix } from '@polkadot/util-crypto';
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
import Keyring from '.';
@@ -25,6 +25,10 @@ describe('keypair', (): void => {
keypair.addFromSeed(seedOne, {});
});
afterEach((): void => {
setSS58Format(42);
});
it('adds the pair', (): void => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey
@@ -40,7 +44,7 @@ describe('keypair', (): void => {
});
it('adds from a mnemonic', (): void => {
setAddressPrefix(68);
setSS58Format(68);
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
@@ -93,6 +97,10 @@ describe('keypair', (): void => {
keypair.addFromSeed(seedOne, {});
});
afterEach((): void => {
setSS58Format(42);
});
it('creates with dev phrase when only path specified', (): void => {
expect(
keypair.createFromUri('//Alice').address
@@ -106,7 +114,7 @@ describe('keypair', (): void => {
});
it('adds from a mnemonic', (): void => {
setAddressPrefix(68);
setSS58Format(68);
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
+11 -5
View File
@@ -1,13 +1,19 @@
// 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 no-useless-catch
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), __dirname);
} catch (error) {
throw error;
}
export default Keyring;
@@ -15,5 +21,5 @@ export {
Keyring,
decodeAddress,
encodeAddress,
setAddressPrefix
setSS58Format
};
+10 -5
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -6,7 +6,7 @@ import { KeypairType } 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 { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret, setSS58Format } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
import createPair from './pair';
@@ -37,17 +37,22 @@ export default class Keyring implements KeyringInstance {
public encodeAddress = encodeAddress;
public setAddressPrefix = setAddressPrefix;
public setSS58Format = setSS58Format;
public constructor (options: KeyringOptions = {}) {
constructor (options: KeyringOptions = {}) {
options.type = options.type || 'ed25519';
options.ss58Format = isNumber(options.ss58Format)
? options.addressPrefix
: options.ss58Format;
assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`);
this._pairs = new Pairs();
this._type = options.type;
setAddressPrefix(isNumber(options.addressPrefix) ? options.addressPrefix : 42);
if (isNumber(options.ss58Format)) {
setSS58Format(options.ss58Format);
}
}
/**
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+3 -4
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,10 +14,9 @@ type DecodeResult = PairInfo & {
secretKey: Uint8Array;
};
export default function decode (passphrase?: string, _encrypted?: Uint8Array | null): DecodeResult {
assert(_encrypted, 'No encrypted data available to decode');
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),
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,7 +14,7 @@ export default function encode ({ publicKey, secretKey }: PairInfo, passphrase?:
const encoded = u8aConcat(
PKCS8_HEADER,
secretKey as Uint8Array,
secretKey,
PKCS8_DIVIDER,
publicKey
);
+19 -3
View File
@@ -1,15 +1,20 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { setAddressPrefix } from '@polkadot/util-crypto';
import { cryptoWaitReady, 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,11 +66,13 @@ describe('pair', (): void => {
'5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'
);
setAddressPrefix(68);
setSS58Format(68);
expect(keyring.alice.address).toEqual(
'7sGUeMak588SPY2YMmmuKUuLz7u2WQpf74F9dCFtSLB2td9d'
);
setSS58Format(42);
});
it('allows getting public key after decoding', (): void => {
@@ -77,4 +84,13 @@ describe('pair', (): void => {
expect(pair.isLocked).toEqual(false);
});
it('allows derivation on the pair', (): void => {
const alice = createPair('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');
});
});
+58 -25
View File
@@ -1,38 +1,61 @@
// 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 { u8aConcat, assert } from '@polkadot/util';
import { encodeAddress, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
import decode from './decode';
import encode from './encode';
import toJson from './toJson';
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 isSr25519 (type: KeypairType): boolean {
return type === 'sr25519';
}
const fromSeed = (type: KeypairType, seed: Uint8Array): Keypair =>
isSr25519(type)
function fromSeed (type: KeypairType, seed: Uint8Array): Keypair {
return isSr25519(type)
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
}
const sign = (type: KeypairType, message: Uint8Array, pair: Partial<Keypair>): Uint8Array =>
isSr25519(type)
? schnorrkelSign(message, pair)
: naclSign(message, pair);
function multiSignaturePrefix (type: KeypairType): Uint8Array {
return isSr25519(type)
? SIG_TYPE_SR25519
: SIG_TYPE_ED25519;
}
const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean =>
isSr25519(type)
function sign (type: KeypairType, message: Uint8Array, pair: Partial<Keypair>, { withType = false }: SignOptions = {}): Uint8Array {
return u8aConcat(
// for multi-signatures, i.e. with indicator, append the signature type as per
// the MultiSignature enum
withType
? multiSignaturePrefix(type)
: SIG_TYPE_NONE,
isSr25519(type)
? schnorrkelSign(message, pair)
: naclSign(message, pair)
);
}
function verify (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean {
return isSr25519(type)
? schnorrkelVerify(message, signature, publicKey)
: naclVerify(message, signature, publicKey);
}
/**
* @name pair
@@ -67,10 +90,21 @@ const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, p
*/
export default function createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
return {
type,
get address (): string {
return encodeAddress(publicKey);
},
get meta (): KeyringPair$Meta {
return meta;
},
get isLocked (): boolean {
return !secretKey || secretKey.length === 0 || isEmpty(secretKey);
},
get publicKey (): Uint8Array {
return publicKey;
},
get type (): KeypairType {
return type;
},
decodePkcs8: (passphrase?: string, _encoded?: Uint8Array | null): void => {
const decoded = decode(passphrase, _encoded || encoded);
@@ -84,25 +118,24 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }:
secretKey = pair.secretKey;
}
},
derive: (suri: string, meta?: KeyringPair$Meta): KeyringPair => {
assert(secretKey, 'Cannot derive on a locked keypair');
const { path } = keyExtractPath(suri);
const derived = keyFromPath({ publicKey, secretKey: secretKey }, path, type);
return createPair(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 =>
sign(type, message, { publicKey, secretKey }, options),
toJson: (passphrase?: string): KeyringPair$Json =>
toJson(type, { meta, publicKey }, encode({ publicKey, secretKey }, passphrase), !!passphrase),
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
+7 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -24,13 +24,16 @@ const json: KeyringPair$Json = {
};
export default function everybody (): KeyringPair {
return {
const pair: KeyringPair = {
type: 'ed25519',
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,
@@ -52,4 +55,6 @@ export default function everybody (): KeyringPair {
verify: (message: Uint8Array, signature: Uint8Array): boolean =>
false
};
return pair;
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+2 -2
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -12,7 +12,7 @@ type KeyringPairMap = Record<string, KeyringPair>;
export default class Pairs implements KeyringPairs {
private _map: KeyringPairMap;
public constructor () {
constructor () {
this._map = {};
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+2 -9
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -21,7 +21,7 @@ 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',
secretKey: hexToU8a('0x98319d4ff8a9508c4bb0cf0b5a78d760a0b2082c02775e6e82370816fedfff48925a225d97aa00682d6a59b95b18780c10d7032336e88f3442b42361f4a66011'),
@@ -32,13 +32,6 @@ const PAIRS: PairDef[] = [
secretKey: hexToU8a('0xe8da6c9d810e020f5e3c7f5af2dea314cbeaa0d72bc6421e92c0808a0c584a6046ab28e97c3ffc77fe12b5a4d37e8cd4afbfebbf2391ffc7cb07c0f38c023efd'),
publicKey: hexToU8a('0xbe5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f')
},
{
name: 'alice_session',
type: 'ed25519',
seed: 'Alice',
secretKey: hexToU8a('0xabf8e5bdbe30c65656c0a3cbd181ff8a56294a69dfedd27982aace4a7690911588dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee'),
publicKey: hexToU8a('0x88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee')
},
{
seed: 'Bob',
secretKey: hexToU8a('0x081ff694633e255136bdb456c20a5fc8fed21f8b964c11bb17ff534ce80ebd5941ae88f85d0c1bfc37be41c904e1dfc01de8c8067b0d6d5df25dd1ac0894a325'),
+2 -8
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -14,7 +14,7 @@ describe('testingPairs', (): void => {
it('creates without failing', (): void => {
expect(
Object.keys(testingPairs())
).toHaveLength(2 + 1 + 7);
).toHaveLength(2 + 0 + 7); // stash, session, pairs
});
it('has the correct address for Alice (non-HDKD)', (): void => {
@@ -28,10 +28,4 @@ describe('testingPairs', (): void => {
testingPairs({ type: 'ed25519' }).alice.address
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
it('has the correct address for Alice_session (HDKD)', (): void => {
expect(
testingPairs({ type: 'ed25519' }).alice_session.address
).toEqual('5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu');
});
});
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2019 @polkadot/keyring authors & contributors
// Copyright 2017-2020 @polkadot/keyring authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+16 -9
View File
@@ -1,5 +1,5 @@
/* 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,7 +7,9 @@ import { Prefix } from '@polkadot/util-crypto/address/types';
import { KeypairType } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
// @deprecated
addressPrefix?: Prefix;
ss58Format?: Prefix;
type?: KeypairType;
}
@@ -31,18 +33,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 +66,9 @@ export interface KeyringInstance {
readonly publicKeys: Uint8Array[];
readonly type: KeypairType;
decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array;
encodeAddress (key: Uint8Array | string): string;
setAddressPrefix (prefix: Prefix): void;
decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean, ss58Format?: Prefix): Uint8Array;
encodeAddress (key: Uint8Array | string, ss58Format?: Prefix): string;
setSS58Format (ss58Format: Prefix): void;
addPair (pair: KeyringPair): KeyringPair;
addFromAddress (address: string | Uint8Array, meta?: KeyringPair$Meta, encoded?: Uint8Array | null, type?: KeypairType, ignoreChecksum?: boolean): KeyringPair;
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-7
View File
@@ -1,7 +0,0 @@
# @polkadot/trie-codec
Implementation of the Substrate-specific codec for a Trie
## Utilities
[Utilities](SUMMARY.md)
-31
View File
@@ -1,31 +0,0 @@
{
"name": "@polkadot/trie-codec",
"version": "1.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"
}
}
-135
View File
@@ -1,135 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { decodeNibbles, isNibblesTerminated } from '@polkadot/trie-codec/nibbles';
import { BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE, EMPTY_TRIE, EXTENSION_NODE_BIG, EXTENSION_NODE_OFFSET, EXTENSION_NODE_SMALL_MAX, EXTENSION_NODE_THRESHOLD, LEAF_NODE_BIG, LEAF_NODE_OFFSET, LEAF_NODE_SMALL_MAX, LEAF_NODE_THRESHOLD, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
// FIXME These are not actually extending from types, we may want to bring
// that in if the dependency imports can be sorted out
type NodeType = 0 | 1 | 2 | 3;
export type Null = null;
export type BranchHeader = boolean;
export type NibbleHeader = number;
export type ExtensionHeader = NibbleHeader;
export type LeafHeader = NibbleHeader;
export default class NodeHeader {
private _nodeType: NodeType;
private _value: Null | BranchHeader | ExtensionHeader | LeafHeader;
public constructor (input?: null | Uint8Array | (null | Uint8Array)[]) {
const [nodeType, value] = Array.isArray(input)
? NodeHeader.decodeNodeHeaderArray(input)
: NodeHeader.decodeNodeHeaderU8a(input);
this._nodeType = nodeType;
this._value = value;
}
private static decodeNodeHeaderArray (input: (null | Uint8Array)[]): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] {
if (input.length === 0) {
return [NODE_TYPE_NULL, null];
} else if (input.length === 2) {
const nibbles = decodeNibbles(input[0]);
const isTerminated = isNibblesTerminated(nibbles);
return isTerminated
? [NODE_TYPE_LEAF, nibbles.length - 1]
: [NODE_TYPE_EXT, nibbles.length];
} else if (input.length === 17) {
return [NODE_TYPE_BRANCH, !!input[16]];
}
throw new Error('Unreachable');
}
private static decodeNodeHeaderU8a (input?: null | Uint8Array): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] {
const firstByte = input
? input[0]
: EMPTY_TRIE;
if (!input || firstByte === EMPTY_TRIE) {
return [NODE_TYPE_NULL, null];
} else if (firstByte === BRANCH_NODE_NO_VALUE) {
return [NODE_TYPE_BRANCH, false];
} else if (firstByte === BRANCH_NODE_WITH_VALUE) {
return [NODE_TYPE_BRANCH, true];
} else if (firstByte >= EXTENSION_NODE_OFFSET && firstByte <= EXTENSION_NODE_SMALL_MAX) {
return [NODE_TYPE_EXT, firstByte - EXTENSION_NODE_OFFSET];
} else if (firstByte === EXTENSION_NODE_BIG) {
return [NODE_TYPE_EXT, input[1] + EXTENSION_NODE_THRESHOLD];
} else if (firstByte >= LEAF_NODE_OFFSET && firstByte <= LEAF_NODE_SMALL_MAX) {
return [NODE_TYPE_LEAF, firstByte - LEAF_NODE_OFFSET];
} else if (firstByte === LEAF_NODE_BIG) {
return [NODE_TYPE_LEAF, input[1] + LEAF_NODE_THRESHOLD];
}
throw new Error('Unreachable');
}
public get encodedLength (): number {
switch (this.nodeType) {
case NODE_TYPE_NULL:
case NODE_TYPE_BRANCH:
return 1;
case NODE_TYPE_EXT:
return (this.value as ExtensionHeader) < EXTENSION_NODE_THRESHOLD
? 1
: 2;
case NODE_TYPE_LEAF:
return (this.value as LeafHeader) < LEAF_NODE_THRESHOLD
? 1
: 2;
default:
throw new Error('Unreachable');
}
}
public get nodeType (): number {
return this._nodeType;
}
public get value (): Null | BranchHeader | ExtensionHeader | LeafHeader {
return this._value;
}
public toU8a (): Uint8Array {
switch (this.nodeType) {
case NODE_TYPE_NULL:
return new Uint8Array([EMPTY_TRIE]);
case NODE_TYPE_BRANCH:
return new Uint8Array([
this.value as BranchHeader
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE
]);
case NODE_TYPE_EXT: {
const nibbleCount = this.value as ExtensionHeader;
return (nibbleCount < EXTENSION_NODE_THRESHOLD)
? new Uint8Array([EXTENSION_NODE_OFFSET + nibbleCount])
: new Uint8Array([EXTENSION_NODE_BIG, nibbleCount - EXTENSION_NODE_THRESHOLD]);
}
case NODE_TYPE_LEAF: {
const nibbleCount = this.value as LeafHeader;
return (nibbleCount < LEAF_NODE_THRESHOLD)
? new Uint8Array([LEAF_NODE_OFFSET + nibbleCount])
: new Uint8Array([LEAF_NODE_BIG, nibbleCount - LEAF_NODE_THRESHOLD]);
}
default:
throw new Error('Unreachable');
}
}
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export const BITMAP = [
1 << 0,
1 << 1,
1 << 2,
1 << 3,
1 << 4,
1 << 5,
1 << 6,
1 << 7,
1 << 8,
1 << 9,
1 << 10,
1 << 11,
1 << 12,
1 << 13,
1 << 14,
1 << 15
];
export const EMPTY_TRIE = 0;
export const LEAF_NODE_OFFSET = 1;
export const LEAF_NODE_BIG = 127;
export const EXTENSION_NODE_OFFSET = 128;
export const EXTENSION_NODE_BIG = 253;
export const BRANCH_NODE_NO_VALUE = 254;
export const BRANCH_NODE_WITH_VALUE = 255;
export const LEAF_NODE_THRESHOLD = LEAF_NODE_BIG - LEAF_NODE_OFFSET;
export const EXTENSION_NODE_THRESHOLD = EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET; // 125
export const LEAF_NODE_SMALL_MAX = LEAF_NODE_BIG - 1;
export const EXTENSION_NODE_SMALL_MAX = EXTENSION_NODE_BIG - 1;
export const NODE_TYPE_NULL = 0;
export const NODE_TYPE_BRANCH = 1;
export const NODE_TYPE_EXT = 2;
export const NODE_TYPE_LEAF = 3;
-74
View File
@@ -1,74 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a } from '@polkadot/util';
import decode from './decode';
describe('decode', (): void => {
it('decodes a leaf', (): void => {
expect(
decode(Uint8Array.from([
0x05, 0x48, 0x19, 0x04, 0xfe
]))
).toEqual([
Uint8Array.from([0x20, 0x48, 0x19]),
Uint8Array.from([0xfe])
]);
});
it('decodes a branch', (): void => {
expect(
decode(Uint8Array.from([
0xfe, 0x00, 0x0c, 0x48, 0x81, 0x0a, 0x3c, 0xff, 0x00, 0x0c, 0x04, 0xa0, 0x10, 0x02, 0x0a, 0x04,
0xaa, 0x10, 0x02, 0x0b, 0x04, 0xab, 0x10, 0x02, 0x0b, 0x04, 0xb0
]))
).toEqual([
null, null, null, null, null, null, null, null, null, null,
[
Uint8Array.from([26]),
Uint8Array.from([255, 0, 12, 4, 160, 16, 2, 10, 4, 170, 16, 2, 11, 4, 171])
],
[
Uint8Array.from([59]),
Uint8Array.from([176])
],
null, null, null, null, null
]);
});
it('decodes a complex branch', (): void => {
expect(
decode(hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
))
).toEqual([
null,
null,
[
hexToU8a('0x37b3872d47181b4a2dc15f0da43e7026'),
hexToU8a('0xe803000000000000')
],
Uint8Array.from([
23, 13, 50, 42, 196, 157, 135, 8, 241, 81, 52, 108, 104, 217, 229, 132, 82, 216, 58, 157, 59, 113, 14, 30, 173, 53, 235, 50, 105, 171, 35, 83
]),
null,
null,
null,
[
hexToU8a('0x3935e46f94f24b82716c0142e2271de9'),
hexToU8a('0x0087000000000000')
],
null,
null,
null,
null,
null,
null,
null,
null,
null
]);
});
});
-97
View File
@@ -1,97 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactStripLength, logger } from '@polkadot/util';
import NodeHeader, { BranchHeader, NibbleHeader } from './NodeHeader';
import { BITMAP, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
import { addNibblesTerminator, encodeNibbles } from './nibbles';
import { toNibbles } from './util';
const EMPTY_BRANCH: (Uint8Array | null)[] = [
null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null, null
];
const l = logger('trie/codec');
l.noop();
function _decodeBranch (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] {
let offset = header.encodedLength;
const branch = header.value as BranchHeader;
const bitmap = input[offset] + (input[offset + 1] << 8);
let value: null | Uint8Array;
offset += 2;
if (branch === true) {
const [length, bytes] = compactStripLength(input.subarray(offset));
value = bytes;
offset += length;
} else {
value = null;
}
return EMPTY_BRANCH.concat(value).map((value, index): null | Uint8Array | [Uint8Array, Uint8Array] => {
let result: null | Uint8Array | [Uint8Array, Uint8Array] = value;
if ((index < 16) && (bitmap & BITMAP[index])) {
const [length, bytes] = compactStripLength(input.subarray(offset));
result = bytes.length === 32
? bytes
// eslint-disable-next-line @typescript-eslint/no-use-before-define
: decode(bytes) as Uint8Array;
offset += length;
}
return result;
});
}
function _decodeKv (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] {
const offset = header.encodedLength;
const nibbleCount = (header.value as NibbleHeader);
const nibbleLength = (nibbleCount + 1) >> 1;
const nibbleData = input.subarray(offset, offset + nibbleLength);
// for odd, ignore the first nibble, data starts at offset 1
const nibbles = toNibbles(nibbleData).subarray(nibbleCount % 2);
const [, value] = compactStripLength(input.subarray(offset + nibbleData.length));
return [
encodeNibbles(
header.nodeType === NODE_TYPE_LEAF
? addNibblesTerminator(nibbles)
: nibbles
),
value
];
}
export default function decode (input: null | Uint8Array): Uint8Array | null | (null | Uint8Array | [Uint8Array, Uint8Array])[] {
const header = new NodeHeader(input);
const nodeType = header.nodeType;
if (!input || nodeType === NODE_TYPE_NULL) {
return input;
} else if (nodeType === NODE_TYPE_BRANCH) {
return _decodeBranch(header, input);
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
return _decodeKv(header, input);
}
throw new Error('Unreachable');
}
// export default function decode (input: null | Uint8Array): Uint8Array | null | Array<null | Uint8Array | Array<null | Uint8Array>> {
// const decoded = _decode(input);
// // l.debug(() => ['decode', { input, decoded }]);
// return decoded;
// }
-107
View File
@@ -1,107 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a } from '@polkadot/util';
import encode from './encode';
describe('encoding', (): void => {
it('encode a small sub-tree', (): void => {
expect(
encode([
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
[
Uint8Array.from([58]),
Uint8Array.from([170])
],
null,
null,
null,
null,
null,
Uint8Array.from([160])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(Uint8Array.from([
255, 0, 4, 4, 160, 16, 2, 10, 4, 170
]));
});
it('encodes a sub-tree', (): void => {
expect(
encode([
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
[
Uint8Array.from([58]),
Uint8Array.from([170])
],
[
Uint8Array.from([59]),
Uint8Array.from([171])
],
null,
null,
null,
null,
Uint8Array.from([160])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(Uint8Array.from([
255, 0, 12, 4, 160, 16, 2, 10, 4, 170, 16, 2, 11, 4, 171
]));
});
it('encodes a complex tree (with hash)', (): void => {
expect(
encode([
null,
null,
[
hexToU8a('0x37b3872d47181b4a2dc15f0da43e7026'),
hexToU8a('0xe803000000000000')
],
Uint8Array.from([
23, 13, 50, 42, 196, 157, 135, 8, 241, 81, 52, 108, 104, 217, 229, 132, 82, 216, 58, 157, 59, 113, 14, 30, 173, 53, 235, 50, 105, 171, 35, 83
]),
null,
null,
null,
[
hexToU8a('0x3935e46f94f24b82716c0142e2271de9'),
hexToU8a('0x0087000000000000')
],
null,
null,
null,
null,
null,
null,
null,
null,
null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
).toEqual(hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
));
});
});
-100
View File
@@ -1,100 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactAddLength, u8aConcat, isU8a, logger } from '@polkadot/util';
import NodeHeader from './NodeHeader';
import { BITMAP, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
import { extractKey } from './nibbles';
import { fromNibbles } from './util';
const BRANCH_VALUE_INDEX = 16;
const EMPTY = new Uint8Array();
const l = logger('trie/codec');
l.noop();
// in the case of odd nibbles, the first byte is encoded as a single
// byte from the nibble, with the remainder of the nibbles is converted
// as nomral nibble combined bytes
function encodeKey (input: null | Uint8Array): Uint8Array {
const nibbles = extractKey(input);
// l.debug(() => ['encodeKey', { input, nibbles }]);
return nibbles.length % 2
? u8aConcat(Uint8Array.from([nibbles[0]]), fromNibbles(nibbles.subarray(1)))
: fromNibbles(nibbles);
}
function encodeValue (input: null | Uint8Array | (null | Uint8Array)[]): Uint8Array {
if (!input) {
return EMPTY;
}
// l.debug(() => ['encodeValue', { input, encoded }]);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return compactAddLength(encode(input));
}
function _encodeBranch (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array {
const values: Uint8Array[] = [];
let bitmap = 0;
for (let index = 0; index < BRANCH_VALUE_INDEX; index++) {
const value = input[index];
if (value) {
bitmap |= BITMAP[index];
values.push(encodeValue(value));
}
}
return u8aConcat(
header.toU8a(),
new Uint8Array([(bitmap & 0xff), (bitmap >> 8)]),
encodeValue(input[BRANCH_VALUE_INDEX]),
...values
);
}
function _encodeKv (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array {
const [path, value] = input;
return u8aConcat(
header.toU8a(),
encodeKey(path),
encodeValue(value)
);
}
export default function encode (input?: null | Uint8Array | (null | Uint8Array)[]): Uint8Array {
if (isU8a(input)) {
return input;
}
const header = new NodeHeader(input);
const nodeType = header.nodeType;
if (!input || nodeType === NODE_TYPE_NULL) {
return header.toU8a();
} else if (nodeType === NODE_TYPE_BRANCH) {
return _encodeBranch(header, input);
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
return _encodeKv(header, input);
}
throw new Error('Unreachable');
}
// export default function encode (input?: null | Uint8Array | Array<null | Uint8Array>): Uint8Array {
// const encoded = _encode(input);
// // l.debug(() => ['encode', { input, encoded }]);
// return encoded;
// }
-7
View File
@@ -1,7 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { blake2AsU8a as hashing } from '@polkadot/util-crypto';
export default hashing;
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Codec } from './types';
import decode from './decode';
import encode from './encode';
import hashing from './hashing';
export { default as stream } from './stream';
const codec: Codec = {
decode,
encode,
hashing,
type: 'Substrate'
};
export default codec;
-79
View File
@@ -1,79 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { fromNibbles, toNibbles } from './util';
const HP_FLAG_2 = 2;
const HP_FLAG_0 = 0;
const NIBBLE_TERMINATOR = 16;
const NEEDS_TERMINATOR = [HP_FLAG_2, HP_FLAG_2 + 1];
const IS_ODD_LENGTH = [HP_FLAG_0 + 1, HP_FLAG_2 + 1];
export function isNibblesTerminated (nibbles: Uint8Array): boolean {
return nibbles[nibbles.length - 1] === NIBBLE_TERMINATOR;
}
export function addNibblesTerminator (nibbles: Uint8Array): Uint8Array {
if (isNibblesTerminated(nibbles)) {
return nibbles;
}
const terminated = new Uint8Array(nibbles.length + 1);
terminated.set(nibbles);
terminated[nibbles.length] = NIBBLE_TERMINATOR;
return terminated;
}
export function removeNibblesTerminator (nibbles: Uint8Array): Uint8Array {
if (isNibblesTerminated(nibbles)) {
return nibbles.subarray(0, nibbles.length - 1);
}
return nibbles;
}
export function decodeNibbles (value: null | Uint8Array): Uint8Array {
const nibblesWithFlag = toNibbles(value);
const [flag] = nibblesWithFlag;
const rawNibbles = IS_ODD_LENGTH.includes(flag)
? nibblesWithFlag.subarray(1)
: nibblesWithFlag.subarray(2);
return NEEDS_TERMINATOR.includes(flag)
? addNibblesTerminator(rawNibbles)
: rawNibbles;
}
export function encodeNibbles (nibbles: Uint8Array): Uint8Array {
const flag = isNibblesTerminated(nibbles)
? HP_FLAG_2
: HP_FLAG_0;
const rawNibbles = removeNibblesTerminator(nibbles);
const prefix = rawNibbles.length % 2
? [flag + 1]
: [flag, 0];
const prefixed = new Uint8Array(prefix.length + rawNibbles.length);
prefixed.set(prefix);
prefixed.set(rawNibbles, prefix.length);
return fromNibbles(prefixed);
}
export function extractKey (key: null | Uint8Array): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
export function extractNodeKey ([key]: (null | Uint8Array)[]): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aConcat } from '@polkadot/util';
import { BITMAP, BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE } from '../constants';
import createValue from './createValue';
export default function createBranch (value: Uint8Array | null, hasChildren: boolean[]): Uint8Array {
let bitmap = 0;
for (let i = 0; i < hasChildren.length; i++) {
if (hasChildren[i]) {
bitmap |= BITMAP[i];
}
}
return u8aConcat(
Uint8Array.from([
value
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE,
(bitmap & 0xff),
(bitmap >> 8)
]),
createValue(value)
);
}
@@ -1,9 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { EMPTY_TRIE } from '../constants';
export default function createEmpty (): Uint8Array {
return Uint8Array.from([EMPTY_TRIE]);
}
@@ -1,9 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { fuseNibbles } from '../util';
export default function createExtension (key: Uint8Array): Uint8Array {
return fuseNibbles(key, false);
}
@@ -1,15 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { u8aConcat } from '@polkadot/util';
import { fuseNibbles } from '../util';
import createValue from './createValue';
export default function createLeaf (key: Uint8Array, value: Uint8Array): Uint8Array {
return u8aConcat(
fuseNibbles(key, true),
createValue(value)
);
}
@@ -1,14 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import hashing from '../hashing';
import createValue from './createValue';
export default function createSubstream (value: Uint8Array): Uint8Array {
return createValue(
value.length < 32
? value
: hashing(value)
);
}
@@ -1,13 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { compactAddLength } from '@polkadot/util';
const NO_VALUE = new Uint8Array();
export default function createValue (value: null | Uint8Array): Uint8Array {
return value
? compactAddLength(value)
: NO_VALUE;
}
@@ -1,10 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const NO_VALUE = new Uint8Array();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function encBranch (value: Uint8Array | null): Uint8Array {
return NO_VALUE;
}
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import createBranch from './createBranch';
import createEmpty from './createEmpty';
import createExtension from './createExtension';
import createLeaf from './createLeaf';
import createSubstream from './createSubstream';
import createValue from './createValue';
import endBranch from './endBranch';
export default {
createBranch,
createEmpty,
createExtension,
createLeaf,
createSubstream,
createValue,
endBranch
};
-10
View File
@@ -1,10 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface Codec {
decode: (input: null | Uint8Array) => Uint8Array | null | (null | Uint8Array | (null | Uint8Array)[])[];
encode: (input?: null | Uint8Array | (null | Uint8Array)[]) => Uint8Array;
hashing: (input: Uint8Array) => Uint8Array;
type: string;
}
@@ -1,39 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import stringToU8a from '@polkadot/util/string/toU8a';
import fromNibbles from './fromNibbles';
describe('fromNibbles', (): void => {
it('converts a single', (): void => {
expect(
fromNibbles(
new Uint8Array([4, 1])
)
).toEqual(
stringToU8a('A')
);
});
it('converts an number of values', (): void => {
expect(
fromNibbles(
new Uint8Array([3, 1, 2, 3, 4, 5])
)
).toEqual(
new Uint8Array([0x31, 0x23, 0x45])
);
});
it('converts an number of values (array)', (): void => {
expect(
fromNibbles(Uint8Array.from([
3, 1, 2, 3, 4, 5, 7, 8
]))
).toEqual(
new Uint8Array([0x31, 0x23, 0x45, 0x78])
);
});
});
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @name fromNibbles
* @summary Converts the input to Nibbles.
* @description
* From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input.
* @example
* <BR>
*
* ```javascript
* import { fromNibbles } from '@polkadot/trie-codec/util';
*
* fromNibbles(new Uint8Array([4, 1, 2, 0])); // => Uint8Array([0x41, 0x20]
* ```
*/
export default function fromNibbles (input: Uint8Array): Uint8Array {
const u8a = new Uint8Array(input.length / 2);
for (let index = 0; index < u8a.length; index++) {
const nibIndex = index << 1;
u8a[index] = (input[nibIndex] << 4) + input[nibIndex + 1];
}
return u8a;
}
@@ -1,34 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { assert, u8aConcat } from '@polkadot/util';
import { EXTENSION_NODE_BIG, EXTENSION_NODE_OFFSET, LEAF_NODE_BIG, LEAF_NODE_OFFSET } from '../constants';
import fromNibbles from './fromNibbles';
const MAX_FUSE_LENGTH = 255 + 126;
export default function fuseNibbles (nibbles: Uint8Array, isLeaf: boolean): Uint8Array {
assert(nibbles.length < MAX_FUSE_LENGTH, `Input to fuseNibbles too large, found ${nibbles.length} >= ${MAX_FUSE_LENGTH}`);
const [firstByteSmall, bigThreshold] = isLeaf
? [LEAF_NODE_OFFSET, LEAF_NODE_BIG - LEAF_NODE_OFFSET]
: [EXTENSION_NODE_OFFSET, EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET];
const result: Uint8Array[] = [
Uint8Array.from([firstByteSmall + Math.min(nibbles.length, bigThreshold)])
];
const oddFlag = nibbles.length % 2;
if (nibbles.length >= bigThreshold) {
result.push(Uint8Array.from([nibbles.length - bigThreshold]));
}
if (oddFlag === 1) {
result.push(nibbles.subarray(0, 1));
}
result.push(fromNibbles(nibbles.subarray(oddFlag)));
return u8aConcat(...result);
}
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export { default as fromNibbles } from './fromNibbles';
export { default as fuseNibbles } from './fuseNibbles';
export { default as sharedPrefixLength } from './sharedPrefixLength';
export { default as toNibbles } from './toNibbles';
@@ -1,15 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default function sharedPrefixLength (first: Uint8Array, second: Uint8Array): number {
const length = Math.min(first.length, second.length);
for (let index = 0; index < length; index++) {
if (first[index] !== second[index]) {
return index;
}
}
return length;
}
@@ -1,29 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import stringToU8a from '@polkadot/util/string/toU8a';
import toNibbles from './toNibbles';
describe('toNibbles', (): void => {
it('converts an array', (): void => {
expect(
toNibbles(Uint8Array.from([
0x31, 0x23, 0x45
]))
).toEqual(
new Uint8Array([3, 1, 2, 3, 4, 5])
);
});
it('converts a single', (): void => {
expect(
toNibbles(
stringToU8a('A')
)
).toEqual(
new Uint8Array([4, 1])
);
});
});
-35
View File
@@ -1,35 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @name toNibbles
* @summary Converts the input to Nibbles.
* @description
* From an `Uint8Array` input, calculate and return a list of nibbles that makes up the input.
* @example
* <BR>
*
* ```javascript
* import { toNibbles } from '@polkadot/trie-codec/util';
*
* toNibbles(new Uint8Array([0x41, 0x20]); // => Uint8Array([4, 1, 2, 0])
* ```
*/
export default function toNibbles (input?: Uint8Array | null): Uint8Array {
if (!input) {
return new Uint8Array();
}
const result = new Uint8Array(input.length * 2);
for (let index = 0; index < input.length; index++) {
const nibIndex = index << 1;
const byte = input[index];
result[nibIndex] = byte >> 4;
result[nibIndex + 1] = byte & 0b1111;
}
return result;
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-23
View File
@@ -1,23 +0,0 @@
# @polkadot/trie-db
A re-implementation of a Patricia Trie. Unlike other implementations, this allows for the specification of a hash function as well as encoder/decoder and operates in a sync fashion by default.
This is a JavaScript port of the [Python Ethereum Trie](https://github.com/ethereum/py-trie) with additions to support transactions (checkpoints) and multiple codecs, by default only the Substrate codec.
## Usage
Installation -
```
yarn add @polkadot/trie-db
```
Classes can be imported as follows:
```js
import Trie from '@polkadot/trie-db'; // Default export
```
## Utilities
[Utilities](SUMMARY.md)
-40
View File
@@ -1,40 +0,0 @@
{
"name": "@polkadot/trie-db",
"version": "1.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"
}
}
-30
View File
@@ -1,30 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default class Checkpoint {
protected txRoot: Uint8Array;
protected rootHash: Uint8Array;
public constructor (rootHash: Uint8Array) {
this.rootHash = rootHash;
this.txRoot = rootHash;
}
protected createCheckpoint (): Uint8Array {
this.txRoot = this.rootHash;
return this.txRoot;
}
protected commitCheckpoint (): Uint8Array {
return this.rootHash;
}
protected revertCheckpoint (): Uint8Array {
this.rootHash = this.txRoot;
return this.rootHash;
}
}
-418
View File
@@ -1,418 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-db authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { TxDb, ProgressCb } from '@polkadot/db/types';
import { Codec } from '@polkadot/trie-codec/types';
import { EncodedPath, TrieDb, Node, NodeBranch, NodeEncodedOrEmpty, NodeKv, NodeNotEmpty, NodeType, TrieEntry } from './types';
import substrateCodec from '@polkadot/trie-codec';
import { decodeNibbles, encodeNibbles, extractNodeKey } from '@polkadot/trie-codec/nibbles';
import { isNull, u8aConcat } from '@polkadot/util';
import { isBranchNode, isEmptyNode, isExtensionNode, isKvNode, isLeafNode } from './util/is';
import { keyEquals, keyStartsWith, computeExtensionKey, computeLeafKey, consumeCommonPrefix } from './util/key';
import { getNodeType, decodeNode, encodeNode } from './util/node';
import Checkpoint from './Checkpoint';
import constants, { Constants } from './constants';
interface Normalized {
index: number;
value: EncodedPath;
}
const BLANK_BRANCH: EncodedPath[] = [
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null
];
/**
* # @polkadot/trie-db
*
* ## Overview
*
* @name Trie
* @summary Re-implementation of a Patricia Trie
* @example See [Polkadot-JS Common Trie-DB Examples](https://polkadot.js.org/api/common/examples/trie-db/)
*/
export default class Impl extends Checkpoint {
public readonly db: TxDb;
protected codec: Codec;
protected constants: Constants;
public constructor (db: TxDb, rootHash?: Uint8Array, codec: Codec = substrateCodec) {
const _constants = constants(codec);
super(rootHash || _constants.EMPTY_HASH);
this.db = db;
this.codec = codec;
this.constants = _constants;
}
protected _entry (root: Uint8Array): TrieEntry | null {
const [encoded, node] = this._getNodeRaw(root);
if (isNull(encoded) || isNull(node)) {
return null;
}
return [root, encoded, node.filter((u8a): boolean => !!u8a && u8a.length === 32) as Uint8Array[]];
}
protected _entries (root: Uint8Array, entries: TrieEntry[] = []): TrieEntry[] {
// l.debug(() => ['entries', { root }]);
const entry = this._entry(root);
if (!entry) {
return entries;
}
entries.push(entry);
entry[2].forEach((u8a): void => {
this._entries(u8a, entries);
});
return entries;
}
protected _snapshot (dest: TrieDb, fn: ProgressCb | undefined, root: Uint8Array, keys: number, percent: number, depth: number): number {
// l.debug(() => ['snapshot', { root }]);
const [encoded, node] = this._getNodeRaw(root);
if (isNull(encoded) || isNull(node)) {
return keys;
}
dest.db.put(root, encoded);
fn && fn({ keys: ++keys, percent });
node.forEach((u8a): void => {
if (u8a && u8a.length === 32) {
keys = this._snapshot(dest, fn, u8a, keys, percent, depth + 1);
}
percent += (100 / node.length) / Math.pow(16, depth);
});
return keys;
}
protected _getNodeRaw (hash: Uint8Array | null): [Uint8Array | null, Node] {
// l.debug(() => ['_getNode', { hash }]);
if (!hash || hash.length === 0 || keyEquals(hash, this.constants.EMPTY_HASH)) {
return [null, null];
} else if (hash.length < 32) {
return [hash, decodeNode(this.codec, hash)];
}
const raw = this.db.get(hash);
return [raw, decodeNode(this.codec, raw)];
}
protected _getNode (hash: Uint8Array | null): Node {
// l.debug(() => ['_getNode', { hash }]);
if (!hash || hash.length === 0 || keyEquals(hash, this.constants.EMPTY_HASH)) {
return null;
} else if (hash.length < 32) {
return decodeNode(this.codec, hash);
}
return decodeNode(this.codec, this.db.get(hash));
}
protected _del (node: Node, trieKey: Uint8Array): Node {
// l.debug(() => ['_del', { node, trieKey }]);
if (isEmptyNode(node)) {
return null;
} else if (isBranchNode(node)) {
return this._delBranchNode(node, trieKey);
} else if (isKvNode(node)) {
return this._delKvNode(node, trieKey);
}
throw new Error('Unreachable');
}
protected _delBranchNode (node: NodeBranch, trieKey: Uint8Array): Node {
// l.debug(() => ['_delBranchNode', { node, trieKey }]);
if (trieKey.length === 0) {
node[node.length - 1] = null;
return this._normaliseBranchNode(node);
}
const nodeToDelete = this._getNode(node[trieKey[0]]);
const subNode = this._del(nodeToDelete, trieKey.subarray(1));
const encodedSubNode = this._persistNode(subNode);
if (keyEquals(encodedSubNode, node[trieKey[0]])) {
return node;
}
node[trieKey[0]] = encodedSubNode;
return isNull(encodedSubNode)
? this._normaliseBranchNode(node)
: node;
}
protected _delKvNode (node: NodeNotEmpty, trieKey: Uint8Array): Node {
// l.debug(() => ['_delKvNode', { node, trieKey }]);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
if (!keyStartsWith(trieKey, currentKey)) {
return node;
} else if (nodeType === NodeType.LEAF) {
return keyEquals(trieKey, currentKey)
? null
: node;
}
const subKey = trieKey.subarray(currentKey.length);
const subNode = this._getNode(node[1]);
const newSub = this._del(subNode, subKey);
const encodedNewSub = this._persistNode(newSub);
if (keyEquals(encodedNewSub, node[1])) {
return node;
} else if (isNull(newSub)) {
return null;
}
if (isKvNode(newSub)) {
const subNibbles = decodeNibbles(newSub[0]);
const newKey = u8aConcat(currentKey, subNibbles);
return [encodeNibbles(newKey), newSub[1]];
} else if (isBranchNode(newSub)) {
return [encodeNibbles(currentKey), encodedNewSub];
}
throw new Error('Unreachable');
}
protected _get (node: Node, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_get', { node, trieKey }]);
if (isEmptyNode(node)) {
return null;
} else if (isBranchNode(node)) {
return this._getBranchNode(node, trieKey);
} else if (isKvNode(node)) {
return this._getKvNode(node, trieKey);
}
throw new Error('Invalid NodeType');
}
protected _getBranchNode (node: NodeBranch, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_getBranchNode', { node, trieKey }]);
if (trieKey.length === 0) {
return node[16];
}
const subNode = this._getNode(node[trieKey[0]]);
return this._get(subNode, trieKey.subarray(1));
}
protected _getKvNode (node: NodeKv, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_getKvNode', { node, trieKey }]);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
// l.debug(() => [{ currentKey, trieKey, nodeType }]);
if (nodeType === NodeType.LEAF) {
return keyEquals(trieKey, currentKey)
? node[1]
: null;
} else if (nodeType === NodeType.EXTENSION) {
if (keyStartsWith(trieKey, currentKey)) {
const subNode = this._getNode(node[1]);
return this._get(subNode, trieKey.subarray(currentKey ? currentKey.length : 0));
}
return null;
}
throw new Error('Unreachable');
}
protected _nodeToDbMapping (node: Node): NodeNotEmpty {
// l.debug(() => ['_nodeToDbMapping', { node }]);
if (isEmptyNode(node)) {
return [null, null];
}
const encoded = encodeNode(this.codec, node);
return (encoded.length < 32)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
? [node as any, null]
: [this.codec.hashing(encoded), encoded];
}
protected _normaliseBranchNode (node: NodeNotEmpty): Node {
// l.debug(() => ['_normaliseBranchNode', { node }]);
const mapped = node
.map((value, index): Normalized => ({ index, value }))
.filter(({ value }): boolean => !!value && value.length !== 0);
if (mapped.length >= 2) {
return node;
} else if (node[16]) {
return [computeLeafKey(new Uint8Array()), node[16]];
}
const [{ index, value }] = mapped;
const subNode = this._getNode(value);
if (isBranchNode(subNode)) {
return [encodeNibbles(new Uint8Array([index])), this._persistNode(subNode)];
} else if (isKvNode(subNode)) {
const subNibbles = decodeNibbles(subNode[0]);
const newKey = u8aConcat(new Uint8Array([index]), subNibbles);
return [encodeNibbles(newKey), subNode[1]];
}
throw new Error('Unreachable');
}
protected _persistNode (node: Node): NodeEncodedOrEmpty {
const [key, value] = this._nodeToDbMapping(node);
// l.debug(() => ['_persistNode', { node, key, value }]);
if (value) {
this.db.put(key as Uint8Array, value);
}
return key;
}
protected _put (node: Node, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_put', { node, trieKey, value }]);
if (isEmptyNode(node)) {
return [computeLeafKey(trieKey), value];
} else if (isKvNode(node)) {
return this._putKvNode(node, trieKey, value);
} else if (isBranchNode(node)) {
return this._putBranchNode(node, trieKey, value);
}
throw new Error('Unreachable');
}
protected _putBranchNode (node: NodeBranch, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_putBranchNode', { node, trieKey, value }]);
if (trieKey && trieKey.length) {
const subNode = this._getNode(node[trieKey[0]]);
const newNode = this._put(subNode, trieKey.subarray(1), value);
node[trieKey[0]] = this._persistNode(newNode);
} else {
node[node.length - 1] = value;
}
return node;
}
protected _putKvNode (node: NodeKv, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_putKvNode', { node, trieKey, value }]);
const currentKey = extractNodeKey(node);
const [commonPrefix, currentRemainder, trieRemainder] = consumeCommonPrefix(currentKey, trieKey);
const isExtension = isExtensionNode(node);
const isLeaf = isLeafNode(node);
let newNode: NodeNotEmpty;
// l.debug(() => ['_putKvNode', { currentKey, commonPrefix, currentRemainder, trieRemainder }]);
if (currentRemainder.length === 0 && trieRemainder.length === 0) {
if (isLeaf) {
return [node[0], value];
}
const subNode = this._getNode(node[1]);
newNode = this._put(subNode, trieRemainder, value);
} else if (currentRemainder.length === 0) {
if (isExtension) {
const subNode = this._getNode(node[1]);
newNode = this._put(subNode, trieRemainder, value);
} else {
const subPosition = trieRemainder[0];
const subKey = computeLeafKey(trieRemainder.subarray(1));
const subNode: NodeKv = [subKey, value];
newNode = BLANK_BRANCH.concat(node[1]) as NodeNotEmpty;
newNode[subPosition] = this._persistNode(subNode);
}
} else {
newNode = BLANK_BRANCH.concat(null) as NodeNotEmpty;
if (currentRemainder.length === 1 && isExtension) {
newNode[currentRemainder[0]] = node[1];
} else {
const computedKey = isExtension
? computeExtensionKey(currentRemainder.subarray(1))
: computeLeafKey(currentRemainder.subarray(1));
newNode[currentRemainder[0]] = this._persistNode([computedKey, node[1]]);
}
if (trieRemainder.length) {
newNode[trieRemainder[0]] = this._persistNode([computeLeafKey(trieRemainder.subarray(1)), value]);
} else {
newNode[16] = value;
}
}
// l.debug(() => ['newNode', newNode]);
if (commonPrefix.length) {
return [computeExtensionKey(commonPrefix), this._persistNode(newNode)];
}
return newNode;
}
protected _setRootNode (node: Node): void {
// l.debug(() => ['_setRootNode', { node }]);
if (isEmptyNode(node)) {
this.rootHash = this.constants.EMPTY_HASH;
} else {
const encoded = encodeNode(this.codec, node);
const rootHash = this.codec.hashing(encoded);
// l.debug(() => ['_setRootNode', { encoded, rootHash }]);
this.db.put(rootHash, encoded);
this.rootHash = rootHash;
}
}
}
-28
View File
@@ -1,28 +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 { Codec } from '@polkadot/trie-codec/types';
import { trieRoot } from '@polkadot/trie-hash';
export interface Constants {
EMPTY_NODE: Uint8Array;
EMPTY_HASH: Uint8Array;
EMPTY_HASH_STR: string;
EMPTY_U8A: Uint8Array;
}
export default function (codec: Codec): Constants {
const EMPTY_NODE = new Uint8Array();
const EMPTY_U8A = trieRoot([], codec);
const EMPTY_HASH = codec.hashing(EMPTY_U8A);
const EMPTY_HASH_STR = EMPTY_HASH.toString();
return {
EMPTY_NODE,
EMPTY_HASH,
EMPTY_HASH_STR,
EMPTY_U8A
};
}
-58
View File
@@ -1,58 +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 toU8a from '@polkadot/util/u8a/toU8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import ethereumCodec from './ethereumCodec';
import Trie from '.';
import getTests from '../../util-rlp/test/getTests';
// const trietest = getTests('TrieTests/trietest.json');
const trieanyorder = getTests('TrieTests/trieanyorder.json');
// FIXME These are not working, the trie-hash implementation is now substrate-specific
describe.skip('official tests', (): void => {
let trie: Trie;
beforeEach((): void => {
trie = new Trie(undefined, undefined, ethereumCodec);
});
// FIXME (maybe) These all have empty/null values, we don't allow those atm as a key nor value
// describe.skip('ordered tests', (): void => {
// trietest.forEach(({ name, input, root }) => {
// it(name, (): void => {
// input.map((input) =>
// trie.put(toU8a(input[0]), toU8a(input[1]))
// );
// expect(
// u8aToHex(trie.getRoot())
// ).toEqual(
// root
// );
// });
// });
// });
describe('unordered tests', (): void => {
trieanyorder.forEach(({ name, input, root }): void => {
const keys = Object.keys(input);
it(name, (): void => {
keys.forEach((key: string): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
trie.put(toU8a(key), toU8a(input[key as any] as string));
});
expect(
u8aToHex(trie.getRoot())
).toEqual(
root
);
});
});
});
});
-17
View File
@@ -1,17 +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 { Codec } from '@polkadot/trie-codec/types';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { decode, encode } from '@polkadot/util-rlp';
const codec: Codec = {
decode,
encode,
hashing: blake2AsU8a,
type: 'Ethereum'
};
export default codec;
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2017-2019 @polkadot/trie-hash 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 { alexander, driedDanta } from '@polkadot/chainspec';
import { hexToU8a, u8aToHex } from '@polkadot/util';
import Trie from '.';
describe('genesis roots', (): void => {
[alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }): void => {
it(`has the correct root for ${name}`, (): void => {
const trie = new Trie();
Object.keys(raw).forEach((key): void => {
trie.put(hexToU8a(key), hexToU8a(raw[key]));
});
expect(
u8aToHex(trie.getRoot())
).toEqual(genesisRoot);
});
});
});
-274
View File
@@ -1,274 +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 u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import ethereumCodec from './ethereumCodec';
import Trie from '.';
// FIXME These are not working, the trie-hash implementation is now substrate-specific
describe.skip('Ethereum', (): void => {
const createTrie = (): Trie =>
new Trie(undefined, undefined, ethereumCodec);
describe('simple save and retrieve', (): void => {
const trie = createTrie();
it('starts with a valid root', (): void => {
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, 192, 1, 98, 47, 181, 227, 99, 180, 33
])
);
});
it('save a value', (): void => {
trie.put(toU8a('test'), toU8a('one'));
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
43, 119, 232, 84, 123, 197, 94, 42, 149, 34, 124, 147, 159, 159, 157, 103, 149, 45, 225, 233, 112, 160, 23, 224, 145, 11, 229, 16, 176, 144, 175, 243
])
);
});
it('should get a value', (): void => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should update a value', (): void => {
trie.put(toU8a('test'), toU8a('two'));
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('two'));
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
127, 237, 74, 184, 190, 46, 103, 129, 65, 141, 13, 96, 61, 232, 146, 13, 56, 32, 59, 29, 246, 58, 175, 140, 72, 182, 196, 103, 230, 245, 229, 148
])
);
});
it('should delete a value', (): void => {
trie.del(toU8a('test'));
expect(
trie.get(toU8a('test'))
).toEqual(null);
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
86, 232, 31, 23, 27, 204, 85, 166, 255, 131, 69, 230, 146, 192, 248, 110, 91, 72, 224, 27, 153, 108, 173, 192, 1, 98, 47, 181, 227, 99, 180, 33
])
);
});
it('should recreate a value', (): void => {
trie.put(toU8a('test'), toU8a('one'));
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
43, 119, 232, 84, 123, 197, 94, 42, 149, 34, 124, 147, 159, 159, 157, 103, 149, 45, 225, 233, 112, 160, 23, 224, 145, 11, 229, 16, 176, 144, 175, 243
])
);
});
it('should get updated a value', (): void => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should create a branch here', (): void => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(
trie.getRoot()
).toEqual(
toU8a('0xde8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc')
);
});
it('should get a value that is in a branch', (): void => {
expect(
trie.get(toU8a('doge'))
).toEqual(toU8a('coin'));
});
it('should delete from a branch', (): void => {
trie.del(toU8a('doge'));
expect(
trie.get(toU8a('doge'))
).toEqual(null);
expect(
trie.getRoot()
).toEqual(
new Uint8Array([
43, 119, 232, 84, 123, 197, 94, 42, 149, 34, 124, 147, 159, 159, 157, 103, 149, 45, 225, 233, 112, 160, 23, 224, 145, 11, 229, 16, 176, 144, 175, 243
])
);
});
});
describe('storing longer values', (): void => {
const trie = createTrie();
const longString = 'this will be a really really really long value';
const longStringRoot = '0xb173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3';
it('should store a longer string', (): void => {
trie.put(toU8a('done'), toU8a(longString));
expect(
trie.getRoot()
).toEqual(new Uint8Array([
79, 170, 48, 228, 218, 25, 91, 13, 86, 114, 153, 98, 252, 127, 54, 124, 242, 163, 153, 215, 249, 196, 65, 209, 186, 130, 39, 6, 181, 246, 231, 111
]));
});
it('should retrieve a longer value (first pass)', (): void => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should store subsequent values', (): void => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(longStringRoot).toEqual(u8aToHex(trie.getRoot()));
});
it('should retrieve a longer value (second pass)', (): void => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should retrieve subsequent values', (): void => {
expect(trie.get(toU8a('doge'))).toEqual(toU8a('coin'));
});
it('should when being modified delete the old value', (): void => {
trie.put(toU8a('done'), toU8a('test'));
expect(
trie.getRoot()
).toEqual(new Uint8Array([
219, 23, 9, 241, 116, 187, 56, 113, 244, 253, 200, 19, 242, 27, 188, 158, 217, 68, 67, 249, 222, 154, 243, 190, 184, 56, 173, 54, 214, 42, 91, 206
]));
});
});
describe('testing Extentions and branches', (): void => {
const trie = createTrie();
it('should store a value', (): void => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should create extention to store this value', (): void => {
trie.put(toU8a('do'), toU8a('verb'));
expect(
toU8a('0xf803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9')
).toEqual(trie.getRoot());
});
it('should store this value under the extention ', (): void => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe.skip('testing Extentions and branches - reverse', (): void => {
const trie = createTrie();
it('should create extention to store this value', (): void => {
trie.put(toU8a('do'), toU8a('verb'));
const value = trie.get(toU8a('do'));
expect(value).toEqual(toU8a('verb'));
});
it('should store a value', (): void => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should store this value under the extention ', (): void => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe('testing deletions cases', (): void => {
const trie = createTrie();
it('should delete from a branch->branch-branch', (): void => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch'));
trie.del(new Uint8Array([12, 22, 22]));
const value = trie.get(new Uint8Array([12, 22, 22]));
expect(null).toEqual(value);
});
it('should delete from a branch->branch-extension', (): void => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch'));
trie.put(new Uint8Array([12, 33, 44]), toU8a('create the last branch'));
trie.del(new Uint8Array([12, 22, 22]));
const value = trie.get(new Uint8Array([12, 22, 22]));
expect(null).toEqual(value);
});
it('should delete from a extension->branch-extension', (): void => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch'));
trie.put(new Uint8Array([12, 33, 44]), toU8a('create the last branch'));
trie.del(new Uint8Array([11, 11, 11]));
const value = trie.get(new Uint8Array([11, 11, 11]));
expect(null).toEqual(value);
});
it('should delete from a extension->branch-branch', (): void => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch'));
trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch'));
trie.del(new Uint8Array([11, 11, 11]));
const value = trie.get(new Uint8Array([11, 11, 11]));
expect(null).toEqual(value);
});
});
});
-168
View File
@@ -1,168 +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 { TrieDb, Node, TrieEntry } from './types';
import MemoryDb from '@polkadot/db/Memory';
import { toNibbles } from '@polkadot/trie-codec/util';
import { isNull, logger, u8aToHex } from '@polkadot/util';
import Impl from './Impl';
import constants from './constants';
const l = logger('trie/db');
/**
* # @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 Trie extends Impl implements TrieDb {
public constructor (db: TxDb = new MemoryDb(), rootHash?: Uint8Array, codec?: Codec) {
super(db, rootHash, codec);
l.debug((): string => `Created with ${this.codec.type} codec, root ${u8aToHex(this.rootHash, 64)}`);
}
public transaction<T> (fn: () => T): T {
try {
this.createCheckpoint();
const result = this.db.transaction(fn);
if (result) {
this.commitCheckpoint();
} else {
this.revertCheckpoint();
}
return result;
} catch (error) {
this.revertCheckpoint();
throw error;
}
}
public open (): void {
this.db.open();
}
public close (): void {
this.db.close();
}
public empty (): void {
this.db.empty();
}
public drop (): void {
this.db.drop();
}
public maintain (fn: ProgressCb): void {
this.db.maintain(fn);
}
public rename (base: string, file: string): void {
this.db.rename(base, file);
}
public size (): number {
return this.db.size();
}
public del (key: Uint8Array): void {
// l.debug(() => ['del', { key }]);
this._setRootNode(
this._del(
this._getNode(this.rootHash),
toNibbles(key)
)
);
}
public get (key: Uint8Array): Uint8Array | null {
// l.debug(() => ['get', { key }]);
return this._get(
this._getNode(this.rootHash),
toNibbles(key)
);
}
public put (key: Uint8Array, value: Uint8Array): void {
// l.debug(() => ['put', { key, value }]);
this._setRootNode(
this._put(
this._getNode(this.rootHash),
toNibbles(key),
value
)
);
}
public getRoot (): Uint8Array {
const rootNode = this.getNode();
if (isNull(rootNode)) {
return constants(this.codec).EMPTY_U8A;
}
return this.rootHash;
}
public setRoot (rootHash: Uint8Array): void {
this.rootHash = rootHash;
// return this._setRootNode(rootNode);
}
public getEntry (hash?: Uint8Array): TrieEntry | null {
return this._entry(hash || this.rootHash);
}
public getNode (hash?: Uint8Array): Node {
return this._getNode(hash || this.rootHash);
}
public entries (): TrieEntry[] {
l.debug((): string => 'retrieving trie entries');
const start = Date.now();
const entries = this._entries(this.rootHash);
const elapsed = (Date.now() - start) / 1000;
l.debug((): string => `entries retrieved in ${elapsed.toFixed(2)}s, ${(entries.length / 1000).toFixed(2)}k keys`);
return entries;
}
public snapshot (dest: TrieDb, fn?: ProgressCb): number {
l.debug((): string => 'creating current state snapshot');
const start = Date.now();
const keys = this._snapshot(dest, fn, this.rootHash, 0, 0, 0);
const elapsed = (Date.now() - start) / 1000;
dest.setRoot(this.rootHash);
l.debug((): string => `snapshot created in ${elapsed.toFixed(2)}s, ${(keys / 1000).toFixed(2)}k keys`);
fn && fn({
isCompleted: true,
keys,
percent: 100
});
return keys;
}
}
-80
View File
@@ -1,80 +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 { trieRoot } from '@polkadot/trie-hash';
import { u8aToHex, u8aToU8a as toU8a } from '@polkadot/util';
import Trie from '.';
describe('snapshots', (): void => {
const values = [
{ k: toU8a('test'), v: toU8a('one') },
{ k: toU8a('one'), v: toU8a('testing') },
{ k: toU8a('two'), v: toU8a('testing with a much longer value here') },
{ k: toU8a('twzei'), v: toU8a('und Deutch') },
{ k: toU8a('do'), v: toU8a('do it') },
{ k: toU8a('dog'), v: toU8a('doggie') },
{ k: toU8a('dogge'), v: toU8a('bigger dog') },
{ k: toU8a('dodge'), v: toU8a('coin') }
];
let trie: Trie;
let back: Trie;
beforeEach((): void => {
trie = new Trie();
back = new Trie();
});
it('creates a snapshot of the (relevant) trie data', (): void => {
const root = trieRoot([values[0]]);
trie.put(values[0].k, values[0].v);
trie.put(values[0].k, toU8a('two'));
trie.del(values[0].k);
trie.put(values[0].k, values[0].v);
trie.put(toU8a('doge'), toU8a('coin'));
trie.del(toU8a('doge'));
trie.snapshot(back, (): void => {});
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));
expect(back.get(values[0].k)).toEqual(values[0].v);
});
it('creates a snapshot of the (relevant) data', (): void => {
const root = trieRoot(values);
values.forEach(({ k, v }): void => {
trie.put(k, v);
});
trie.snapshot(back, (): void => {});
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));
values.forEach(({ k, v }): void => {
expect(back.get(k)).toEqual(v);
});
});
it('retrieves entries, which can re-create', (): void => {
const root = trieRoot(values);
values.forEach(({ k, v }): void => {
trie.put(k, v);
});
const entries = trie.entries();
entries.forEach(([key, encoded, children]): void => {
back.db.put(key, encoded);
console.log(u8aToHex(key), ...children.map((child): string => `\n\t${u8aToHex(child)}`));
});
back.setRoot(root);
values.forEach(({ k, v }): void => {
expect(back.get(k)).toEqual(v);
});
});
});
-43
View File
@@ -1,43 +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 { u8aToHex } from '@polkadot/util';
import testdata, { TestData } from '../../trie-hash/test/data';
import Trie from '.';
describe('substrate tests', (): void => {
let trie: Trie;
const checkRoot = ({ root }: TestData): void => {
expect(
u8aToHex(trie.getRoot())
).toEqual(
u8aToHex(root)
);
};
const putValues = ({ input }: TestData): void => {
input.forEach(({ k, v }): void => {
trie.put(k, v);
});
};
beforeEach((): void => {
trie = new Trie();
});
Object.values(testdata).forEach((test): void => {
it(`hashes ${test.desc}`, (): void => {
putValues(test);
checkRoot(test);
});
});
// When we have a specific test failing and we want to debug it
// it('does extensionBranch', (): void => {
// putValues(testdata.extensionBranch);
// checkRoot(testdata.extensionBranch);
// });
});
-50
View File
@@ -1,50 +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';
export enum NodeType {
EMPTY = 0,
LEAF = 1,
EXTENSION = 2,
BRANCH = 3
}
export type NodeEmpty = null;
export type NodeEncoded = Uint8Array;
export type NodeEncodedOrEmpty = NodeEncoded | NodeEmpty;
export type NodeBranch = [
NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty,
NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty,
NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty,
NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty, NodeEncodedOrEmpty,
NodeEncodedOrEmpty
];
export type EncodedPath = Uint8Array | null;
export type NodeKv = [EncodedPath, NodeEncodedOrEmpty];
export type NodeNotEmpty = NodeKv | NodeBranch;
export type Node = NodeEmpty | NodeNotEmpty;
// root, encoded, childroots
export type TrieEntry = [Uint8Array, Uint8Array, Uint8Array[]];
export interface TrieDb extends TxDb {
readonly db: TxDb;
getRoot (): Uint8Array;
setRoot (rootHash: Uint8Array): void;
getEntry (root?: Uint8Array): TrieEntry | null;
getNode (hash?: Uint8Array): Node;
entries (): TrieEntry[];
snapshot (dest: TrieDb, fn?: ProgressCb): number;
}
-54
View File
@@ -1,54 +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 { Node, NodeBranch, NodeKv, NodeEmpty, NodeType } from '../types';
import { isNull } from '@polkadot/util';
import { getNodeType } from './node';
/**
* @name isEmptyNode
* @summary Returns true if node is NULL
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export function isEmptyNode (node: Node): node is NodeEmpty {
return isNull(node);
}
/**
* @name isKvNode
* @summary Returns true if node is not empty and contains a single key/value pair
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export function isKvNode (node: Node): node is NodeKv {
return !isEmptyNode(node) && node.length === 2;
}
/**
* @name isExtensionNode
* @summary Returns true if node is an Extension 2-item node
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export function isExtensionNode (node: Node): node is NodeKv {
return getNodeType(node) === NodeType.EXTENSION;
}
/**
* @name isLeafNode
* @summary Returns true if node is an Leaf 2-item node
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export function isLeafNode (node: Node): node is NodeKv {
return getNodeType(node) === NodeType.LEAF;
}
/**
* @name isBranchNode
* @summary Returns true if node is an Branch 17-item node
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export function isBranchNode (node: Node): node is NodeBranch {
return !isEmptyNode(node) && node.length === 17;
}
-64
View File
@@ -1,64 +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 { addNibblesTerminator, encodeNibbles } from '@polkadot/trie-codec/nibbles';
import { isNull } from '@polkadot/util';
import { EncodedPath } from '../types';
export function keyStartsWith (key: Uint8Array | null, partial: Uint8Array | null): boolean {
if (isNull(key) && isNull(partial)) {
return true;
} else if (isNull(key) || isNull(partial) || (key.length < partial.length)) {
return false;
}
for (let index = 0; index < partial.length; index++) {
if (key[index] !== partial[index]) {
return false;
}
}
return true;
}
export function keyEquals (key: Uint8Array | null, test: Uint8Array | null): boolean {
if (isNull(key) && isNull(test)) {
return true;
} else if (isNull(key) || isNull(test) || (key.length !== test.length)) {
return false;
}
return keyStartsWith(key, test);
}
export function computeExtensionKey (nibbles: Uint8Array): EncodedPath {
return encodeNibbles(nibbles);
}
export function computeLeafKey (nibbles: Uint8Array): EncodedPath {
return encodeNibbles(
addNibblesTerminator(nibbles)
);
}
export function getCommonPrefixLength (left: Uint8Array, right: Uint8Array): number {
for (let index = 0; index < left.length && index < right.length; index++) {
if (left[index] !== right[index]) {
return index;
}
}
return Math.min(left.length, right.length);
}
export function consumeCommonPrefix (left: Uint8Array, right: Uint8Array): [Uint8Array, Uint8Array, Uint8Array] {
const length = getCommonPrefixLength(left, right);
return [
left.subarray(0, length),
left.subarray(length),
right.subarray(length)
];
}
-48
View File
@@ -1,48 +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 { Codec } from '@polkadot/trie-codec/types';
import { Node, NodeType, NodeNotEmpty } from '../types';
import { decodeNibbles, isNibblesTerminated } from '@polkadot/trie-codec/nibbles';
import { isNull } from '@polkadot/util';
import { isBranchNode, isEmptyNode, isKvNode } from './is';
export function getNodeType (node: Node): NodeType {
if (isEmptyNode(node)) {
return NodeType.EMPTY;
} else if (isKvNode(node)) {
const [key] = node;
const nibbles = decodeNibbles(key);
return isNibblesTerminated(nibbles)
? NodeType.LEAF
: NodeType.EXTENSION;
} else if (isBranchNode(node)) {
return NodeType.BRANCH;
}
throw new Error('Unable to determine node type');
}
export function decodeNode (codec: Codec, encoded: Uint8Array | Node): Node {
if (isNull(encoded) || encoded.length === 0) {
return null;
} else if (Array.isArray(encoded)) {
return encoded;
}
const node = codec.decode(encoded) as NodeNotEmpty;
return node.map((value): Uint8Array | null =>
value && value.length
? value
: null
) as NodeNotEmpty;
}
export function encodeNode (codec: Codec, node: Node): Uint8Array {
return codec.encode(node);
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-21
View File
@@ -1,21 +0,0 @@
# @polkadot/trie-hash
Calculate ordered and unordered [Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree) from inputs.
## Usage
Installation -
```
yarn add @polkadot/trie-hash
```
Functions can be imported as follows:
```js
import { trieRoot } from '@polkadot/trie-hash';
```
## Utilities
[Utilities](SUMMARY.md)

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