Remove client-only packages (#503)

This commit is contained in:
Jaco Greeff
2020-01-15 12:27:12 +01:00
committed by GitHub
parent 0a8ab20744
commit 4ce452b40a
111 changed files with 7 additions and 6000 deletions

View File

@@ -1,3 +1,9 @@
# 2.0.0-beta.x
- Update schnorrkel to 0.8.5 (Full Substrate 2.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)
# 1.8.1
- Add cross-client encryption/decryption support (Thanks to https://github.com/hskang9)

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

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: [

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.

View File

@@ -1,7 +0,0 @@
# @polkadot/chainspec
Chainspecs for known chains
## Utilities
[Utilities](SUMMARY.md)

View File

@@ -1,31 +0,0 @@
{
"name": "@polkadot/chainspec",
"version": "2.0.0-beta.3",
"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.7.7",
"@polkadot/util": "^2.0.0-beta.3"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +0,0 @@
// Copyright 2017-2020 @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';

View File

@@ -1,20 +0,0 @@
// Copyright 2017-2020 @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[];
}

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.

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)

View File

@@ -1,33 +0,0 @@
{
"name": "@polkadot/db",
"version": "2.0.0-beta.3",
"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.7.7",
"@polkadot/trie-hash": "^2.0.0-beta.3",
"@polkadot/util": "^2.0.0-beta.3",
"lru_map": "^0.3.3"
}
}

View File

@@ -1,68 +0,0 @@
// Copyright 2017-2020 @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 {
constructor () {
super(new MemoryDb());
}
}

View File

@@ -1,63 +0,0 @@
// Copyright 2017-2020 @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);
});
});

View File

@@ -1,116 +0,0 @@
// Copyright 2017-2020 @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>;
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();
}
}
}

View File

@@ -1,27 +0,0 @@
// Copyright 2017-2020 @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());
});
});

View File

@@ -1,70 +0,0 @@
// Copyright 2017-2020 @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);
}
}

View File

@@ -1,93 +0,0 @@
// Copyright 2017-2020 @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);
});
});

View File

@@ -1,157 +0,0 @@
// Copyright 2017-2020 @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;
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;
}
}

View File

@@ -1,39 +0,0 @@
// Copyright 2017-2020 @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;
}

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.

View File

@@ -1,7 +0,0 @@
# @polkadot/trie-codec
Implementation of the Substrate-specific codec for a Trie
## Utilities
[Utilities](SUMMARY.md)

View File

@@ -1,31 +0,0 @@
{
"name": "@polkadot/trie-codec",
"version": "2.0.0-beta.3",
"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.7.7",
"@polkadot/util": "^2.0.0-beta.3"
}
}

View File

@@ -1,135 +0,0 @@
// Copyright 2017-2020 @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;
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');
}
}
}

View File

@@ -1,39 +0,0 @@
// Copyright 2017-2020 @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;

View File

@@ -1,74 +0,0 @@
// Copyright 2017-2020 @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
]);
});
});

View File

@@ -1,97 +0,0 @@
// Copyright 2017-2020 @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;
// }

View File

@@ -1,107 +0,0 @@
// Copyright 2017-2020 @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'
));
});
});

View File

@@ -1,100 +0,0 @@
// Copyright 2017-2020 @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;
// }

View File

@@ -1,7 +0,0 @@
// Copyright 2017-2020 @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;

View File

@@ -1,20 +0,0 @@
// Copyright 2017-2020 @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;

View File

@@ -1,79 +0,0 @@
// Copyright 2017-2020 @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)
);
}

View File

@@ -1,29 +0,0 @@
// Copyright 2017-2020 @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)
);
}

View File

@@ -1,9 +0,0 @@
// Copyright 2017-2020 @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]);
}

View File

@@ -1,9 +0,0 @@
// Copyright 2017-2020 @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);
}

View File

@@ -1,15 +0,0 @@
// Copyright 2017-2020 @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)
);
}

View File

@@ -1,14 +0,0 @@
// Copyright 2017-2020 @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)
);
}

View File

@@ -1,13 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,10 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,21 +0,0 @@
// Copyright 2017-2020 @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
};

View File

@@ -1,10 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,39 +0,0 @@
// Copyright 2017-2020 @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])
);
});
});

View File

@@ -1,29 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,34 +0,0 @@
// Copyright 2017-2020 @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);
}

View File

@@ -1,8 +0,0 @@
// Copyright 2017-2020 @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';

View File

@@ -1,15 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,29 +0,0 @@
// Copyright 2017-2020 @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])
);
});
});

View File

@@ -1,35 +0,0 @@
// Copyright 2017-2020 @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;
}

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.

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)

View File

@@ -1,40 +0,0 @@
{
"name": "@polkadot/trie-db",
"version": "2.0.0-beta.3",
"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.7.7",
"@polkadot/db": "^2.0.0-beta.3",
"@polkadot/trie-codec": "^2.0.0-beta.3",
"@polkadot/trie-hash": "^2.0.0-beta.3",
"@polkadot/util": "^2.0.0-beta.3",
"@polkadot/util-crypto": "^2.0.0-beta.3"
},
"devDependencies": {
"@polkadot/chainspec": "^2.0.0-beta.3",
"@polkadot/util-rlp": "^2.0.0-beta.3",
"ethereumjs-testing": "1.0.4"
}
}

View File

@@ -1,30 +0,0 @@
// Copyright 2017-2020 @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;
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;
}
}

View File

@@ -1,418 +0,0 @@
// Copyright 2017-2020 @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;
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;
}
}
}

View File

@@ -1,28 +0,0 @@
// Copyright 2017-2020 @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
};
}

View File

@@ -1,58 +0,0 @@
// Copyright 2017-2020 @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
);
});
});
});
});

View File

@@ -1,17 +0,0 @@
// Copyright 2017-2020 @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;

View File

@@ -1,24 +0,0 @@
// Copyright 2017-2020 @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);
});
});
});

View File

@@ -1,274 +0,0 @@
// Copyright 2017-2020 @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);
});
});
});

View File

@@ -1,168 +0,0 @@
// Copyright 2017-2020 @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 {
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;
}
}

View File

@@ -1,80 +0,0 @@
// Copyright 2017-2020 @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 => undefined);
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 => undefined);
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);
});
});
});

View File

@@ -1,43 +0,0 @@
// Copyright 2017-2020 @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);
// });
});

View File

@@ -1,50 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,54 +0,0 @@
// Copyright 2017-2020 @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;
}

View File

@@ -1,64 +0,0 @@
// Copyright 2017-2020 @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)
];
}

View File

@@ -1,48 +0,0 @@
// Copyright 2017-2020 @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);
}

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.

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)

View File

@@ -1,34 +0,0 @@
{
"name": "@polkadot/trie-hash",
"version": "2.0.0-beta.3",
"description": "Generates trie roots from key-value pairs",
"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-hash#readme",
"dependencies": {
"@babel/runtime": "^7.7.7",
"@polkadot/util": "^2.0.0-beta.3"
},
"devDependencies": {
"@polkadot/chainspec": "^2.0.0-beta.3"
}
}

View File

@@ -1,85 +0,0 @@
// Copyright 2017-2020 @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 { Codec } from '@polkadot/trie-codec/types';
import { sharedPrefixLength } from '@polkadot/trie-codec/util';
import { u8aConcat } from '@polkadot/util';
import { DEFAULT_CODEC, DEFAULT_STREAM } from './defaults';
const EMPTY = new Uint8Array();
// FIXME This is problematic, the stream implementation is Substrate-only as is the branch here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _buildTrie (input: [Uint8Array, Uint8Array][], cursor: number, codec: Codec, stream: any): Uint8Array {
if (input.length === 0) {
return stream.createEmpty();
}
const [firstKey, firstValue] = input[0];
if (input.length === 1) {
return stream.createLeaf(firstKey.subarray(cursor), firstValue);
}
const sharedNibbleCount = input.reduce((min, [key], index): number => {
return index === 0
? key.length
: Math.min(min, sharedPrefixLength(key, firstKey));
}, 0);
if (sharedNibbleCount > cursor) {
return u8aConcat(
stream.createExtension(firstKey.subarray(cursor, sharedNibbleCount)),
stream.createSubstream(
// eslint-disable-next-line @typescript-eslint/no-use-before-define
buildTrie(input, sharedNibbleCount, codec, stream)
)
);
}
const value = firstKey.length === cursor
? firstValue
: null;
const sharedNibbleCounts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const start = value ? 1 : 0;
let begin = start;
for (let index = 0; index < 16; index++) {
sharedNibbleCounts[index] = input
.filter((_, index): boolean => index >= begin)
.filter(([key]): boolean => key[cursor] === index)
.length;
begin += sharedNibbleCounts[index];
}
begin = start;
return u8aConcat(
stream.createBranch(value, sharedNibbleCounts.map((value): boolean => value > 0)),
...sharedNibbleCounts.map((count): Uint8Array => {
let result = EMPTY;
if (count > 0) {
result = stream.createSubstream(
// eslint-disable-next-line @typescript-eslint/no-use-before-define
buildTrie(input.slice(begin, begin + count), cursor + 1, codec, stream)
);
begin += count;
}
return result;
}),
stream.endBranch(value)
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function buildTrie (input: [Uint8Array, Uint8Array][], cursor = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array {
const trie = _buildTrie(input, cursor, codec, stream);
return trie;
}

View File

@@ -1,10 +0,0 @@
// Copyright 2017-2020 @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 DEFAULT_CODEC, { stream as DEFAULT_STREAM } from '@polkadot/trie-codec';
export {
DEFAULT_CODEC,
DEFAULT_STREAM
};

View File

@@ -1,27 +0,0 @@
// Copyright 2017-2020 @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 { TriePair } from './types';
import { alexander, driedDanta } from '@polkadot/chainspec';
import { hexToU8a, u8aToHex } from '@polkadot/util';
import trieRoot from './trieRoot';
describe('genesis roots', (): void => {
[alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }): void => {
it(`has the correct root for ${name}`, (): void => {
expect(
u8aToHex(
trieRoot(
Object.keys(raw).map((key): TriePair => ({
k: hexToU8a(key),
v: hexToU8a(raw[key])
}))
)
)
).toEqual(genesisRoot);
});
});
});

View File

@@ -1,10 +0,0 @@
// Copyright 2017-2020 @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.
/**
* @summary Utility methods to create [Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree)
*/
export { default as trieRoot } from './trieRoot';
export { default as trieRootOrdered } from './trieRootOrdered';

View File

@@ -1,20 +0,0 @@
// Copyright 2017-2020 @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 { u8aToHex } from '@polkadot/util';
import trieRoot from './trieRoot';
import testdata from '../test/data';
describe('trieRoot', (): void => {
Object.values(testdata).forEach(({ desc, input, root }): void => {
it(`hashes ${desc}`, (): void => {
expect(
u8aToHex(trieRoot(input))
).toEqual(
u8aToHex(root)
);
});
});
});

View File

@@ -1,33 +0,0 @@
// Copyright 2017-2020 @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 { Codec } from '@polkadot/trie-codec/types';
import { TriePair } from './types';
import { DEFAULT_CODEC } from './defaults';
import unhashedTrie from './unhashedTrie';
/**
* @name trieRoot
* @summary Creates a trie hash from the supplied pairs.
* @description
* From an `Array<{k: Uint8Array, v: Uint8Array}>` input, calculate the triehash and return the result as a `Uint8Array`.
* @example
* <BR>
*
* ```javascript
* import { stringToU8a } from '@polkadot/util';
* import { trieRoot } from '@polkadot/trie-hash';
*
* trieRoot([{
* k: stringToU8a('A'),
* v: stringToU8a('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
* }]); // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab
* ```
*/
export default function trieRoot (input: TriePair[], codec: Codec = DEFAULT_CODEC): Uint8Array {
return codec.hashing(
unhashedTrie(input, codec)
);
}

View File

@@ -1,20 +0,0 @@
// Copyright 2017-2020 @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 { stringToU8a, u8aToHex } from '@polkadot/util';
import { trieRootOrdered } from '.';
describe('trieRootOrdered', (): void => {
it('encodes values', (): void => {
expect(
u8aToHex(
trieRootOrdered([
stringToU8a('doe'),
stringToU8a('reindeer')
])
)
).toEqual('0xb9b1bb07e481f0393e15f32f34abd665f7a698786a7ec9feb31b2e8927ad5f86');
});
});

View File

@@ -1,39 +0,0 @@
// Copyright 2017-2020 @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 { Codec } from '@polkadot/trie-codec/types';
import { TriePair } from './types';
import { compactToU8a } from '@polkadot/util';
import { DEFAULT_CODEC } from './defaults';
import trieRoot from './trieRoot';
/**
* @name trieRootOrdered
* @summary Creates a trie hash from the supplied values.
* @description
* From an `Array<Uint8Array>` input, calculate the ordered triehash and return the result as a `Uint8Array`.
* @example
* <BR>
*
* ```javascript
* import { stringToU8a } from '@polkadot/util';
* import { trieRootOrdered } from '@polkadot/trie-hash';
*
* trieRootOrdered([
* stringToU8a('doe'),
* stringToU8a('reindeer')
* ]); // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3
* ```
*/
export default function trieRootOrdered (input: Uint8Array[], codec: Codec = DEFAULT_CODEC): Uint8Array {
return trieRoot(
input.map((v, index): TriePair => ({
k: compactToU8a(index),
v
})),
codec
);
}

View File

@@ -1,8 +0,0 @@
// Copyright 2017-2020 @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.
export interface TriePair {
k: Uint8Array;
v: Uint8Array;
}

View File

@@ -1,20 +0,0 @@
// Copyright 2017-2020 @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 { u8aToHex } from '@polkadot/util';
import unhashedTrie from './unhashedTrie';
import testdata from '../test/data';
describe('unhashedTrie', (): void => {
Object.values(testdata).forEach(({ desc, input, output }): void => {
it(`encodes ${desc}`, (): void => {
expect(
u8aToHex(unhashedTrie(input))
).toEqual(
u8aToHex(output)
);
});
});
});

View File

@@ -1,28 +0,0 @@
// Copyright 2017-2020 @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 { Codec } from '@polkadot/trie-codec/types';
import { TriePair } from './types';
import { toNibbles } from '@polkadot/trie-codec/util';
import { u8aToHex } from '@polkadot/util';
import buildTrie from './buildTrie';
import { DEFAULT_CODEC } from './defaults';
export default function unhashedTrie (input: TriePair[], codec: Codec = DEFAULT_CODEC): Uint8Array {
const map: { [index: string]: TriePair } = {};
input.forEach((pair): void => {
map[u8aToHex(pair.k)] = pair;
});
const pairs = Object
.keys(map)
.sort()
.map((key): TriePair => map[key])
.map(({ k, v }): [Uint8Array, Uint8Array] => ([toNibbles(k), v] as [Uint8Array, Uint8Array]));
return buildTrie(pairs, 0, codec);
}

View File

@@ -1,198 +0,0 @@
// Copyright 2017-2020 @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 { TriePair } from '../src/types';
import { hexToU8a, stringToU8a } from '@polkadot/util';
export interface TestData {
desc: string;
input: TriePair[];
output: Uint8Array;
root: Uint8Array;
}
const data: { [index: string]: TestData } = {
simpleBranch: {
desc: 'a branch',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0x10]) },
{ k: Uint8Array.from([0xba]), v: Uint8Array.from([0x11]) }
],
output: Uint8Array.from([
0xfe, 0x00, 0x0c, 0x10, 0x02, 0x0a, 0x04, 0x10, 0x10, 0x02, 0x0a, 0x04, 0x11
]),
root: hexToU8a('0x922fa0ab17d1f383b45047502151d09e9141a76ddf5b5e4f1af98c4afdd85864')
},
extensionBranch: {
desc: 'extension and branch',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0x10]) },
{ k: Uint8Array.from([0xab]), v: Uint8Array.from([0x11]) }
],
output: hexToU8a('0x810a2cfe000c0c0104100c010411'),
root: hexToU8a('0x3f6764bc812ca86b84cf88b2045828fd605c8abbe1e9c657ff87adb715c644bf')
},
extensionBranchValue: {
desc: 'extension and branch with value',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0xa0]) },
{ k: Uint8Array.from([0xaa, 0xaa]), v: Uint8Array.from([0xaa]) },
{ k: Uint8Array.from([0xaa, 0xbb]), v: Uint8Array.from([0xab]) }
],
output: Uint8Array.from([
0x82, 0xaa, 0x3c, 0xff, 0x00, 0x0c, 0x04, 0xa0, 0x10, 0x02, 0x0a, 0x04, 0xaa, 0x10, 0x02, 0x0b,
0x04, 0xab
]),
root: hexToU8a('0xc896ef26cd64107bd8bf33e9e0b0adbb29c54ac1bf8e9dc30153f13638095108')
},
midExtensionBranchValue: {
desc: 'medium extension and branch with value',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0xa0]) },
{ k: Uint8Array.from([0xaa, 0xaa]), v: Uint8Array.from([0xaa]) },
{ k: Uint8Array.from([0xaa, 0xbb]), v: Uint8Array.from([0xab]) },
{ k: Uint8Array.from([0xbb]), v: Uint8Array.from([0xb0]) }
],
output: 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
]),
root: hexToU8a('0xd8272dfbf69d087664637b9c1773e20d82b1476c1c480e84f13cafbec4c5c92a')
},
bigExtensionBranchValue: {
desc: 'bigger extension and branch with value',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0xa0]) },
{ k: Uint8Array.from([0xaa, 0xaa]), v: Uint8Array.from([0xaa]) },
{ k: Uint8Array.from([0xaa, 0xbb]), v: Uint8Array.from([0xab]) },
{ k: Uint8Array.from([0xbb]), v: Uint8Array.from([0xb0]) },
{ k: Uint8Array.from([0xbb, 0xbb]), v: Uint8Array.from([0xbb]) },
{ k: Uint8Array.from([0xbb, 0xcc]), v: Uint8Array.from([0xbc]) }
],
output: Uint8Array.from([
0xfe, 0x00, 0x0c, 0x48, 0x81, 0x0a, 0x3c, 0xff, 0x00, 0x0c, 0x04, 0xa0, 0x10, 0x02, 0x0a, 0x04,
0xaa, 0x10, 0x02, 0x0b, 0x04, 0xab, 0x48, 0x81, 0x0b, 0x3c, 0xff, 0x00, 0x18, 0x04, 0xb0, 0x10,
0x02, 0x0b, 0x04, 0xbb, 0x10, 0x02, 0x0c, 0x04, 0xbc
]),
root: hexToU8a('0x519056dadff78abc057f6de56706d7b0ed01654b059df3dd9cfc135ef246dd22')
},
longLeaf: {
desc: 'a single long leaf',
input: [
{
k: Uint8Array.from([0xaa]),
v: stringToU8a('ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC')
},
{
k: Uint8Array.from([0xba]),
v: Uint8Array.from([0x11])
}
],
output: Uint8Array.from([
0xfe, 0x00, 0x0c, 0x80, 0x0e, 0x26, 0xe9, 0x80, 0x0a, 0xc2, 0x7f, 0x56, 0x5c, 0x7e, 0x7c, 0xa7,
0x95, 0x16, 0x24, 0x78, 0x35, 0xea, 0x07, 0x6c, 0x5b, 0x62, 0x5f, 0x2d, 0x61, 0x00, 0x1a, 0x7b,
0xab, 0xad, 0xbf, 0x11, 0x10, 0x02, 0x0a, 0x04, 0x11
]),
root: hexToU8a('0x28530359d763dccdd0a6720aacdea9d03c4d93fa8b7c83e650ab159f1fa4675f')
},
twoLongLeaves: {
desc: 'two long leaves',
input: [
{
k: Uint8Array.from([0xaa]),
v: stringToU8a('ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC')
},
{
k: Uint8Array.from([0xba]),
v: stringToU8a('ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC')
}
],
output: Uint8Array.from([
0xfe, 0x00, 0x0c, 0x80, 0x0e, 0x26, 0xe9, 0x80, 0x0a, 0xc2, 0x7f, 0x56, 0x5c, 0x7e, 0x7c, 0xa7,
0x95, 0x16, 0x24, 0x78, 0x35, 0xea, 0x07, 0x6c, 0x5b, 0x62, 0x5f, 0x2d, 0x61, 0x00, 0x1a, 0x7b,
0xab, 0xad, 0xbf, 0x11, 0x80, 0x0e, 0x26, 0xe9, 0x80, 0x0a, 0xc2, 0x7f, 0x56, 0x5c, 0x7e, 0x7c,
0xa7, 0x95, 0x16, 0x24, 0x78, 0x35, 0xea, 0x07, 0x6c, 0x5b, 0x62, 0x5f, 0x2d, 0x61, 0x00, 0x1a,
0x7b, 0xab, 0xad, 0xbf, 0x11
]),
root: hexToU8a('0x413f72e84d4f48fba427592529cd048244bf816141f17d6b5947965765e67824')
},
empty: {
desc: 'empty into [0]',
input: [],
output: Uint8Array.from([0]),
root: hexToU8a('0x03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314')
},
singleValue: {
desc: 'a single tuple',
input: [
{ k: Uint8Array.from([0xaa]), v: Uint8Array.from([0xbb]) }
],
output: Uint8Array.from([
0x03, // leaf (0x01) with (+) key of 2 nibbles (0x02)
0xaa, // key data
1 << 2, // length of value in bytes as Compact
0xbb // value data
]),
root: hexToU8a('0xe778a32590ed4f3f39608b77af87fb59163a89bb9702f477375e1a574736d6f0')
},
singleValue2: {
desc: 'a single tuple (prepare for next)',
input: [
{ k: Uint8Array.from([0x48, 0x19]), v: Uint8Array.from([0xfe]) }
],
output: Uint8Array.from([
0x05, 0x48, 0x19, 0x04, 0xfe
]),
root: hexToU8a('0xfb05396ab039474785c95dcb40339f52a45ea5d5bc8c1f76d7e4308b90124357')
},
twoValues: {
desc: '2 disjointed tuple keys',
input: [
{ k: Uint8Array.from([0x48, 0x19]), v: Uint8Array.from([0xfe]) },
{ k: Uint8Array.from([0x13, 0x14]), v: Uint8Array.from([0xff]) }
],
output: Uint8Array.from([
0xfe, // branch, no value
0x12, // slots 1 & 4 are taken from 0-7
0x00, // no slots from 8-15
0x05 << 2, // first slot: LEAF, 5 bytes long.
0x04, // leaf with 3 nibbles
0x03, // first nibble
0x14, // second & third nibble
0x01 << 2, // 1 byte data
0xff, // value data
0x05 << 2, // second slot: LEAF, 5 bytes long.
0x04, // leaf with 3 nibbles
0x08, // first nibble
0x19, // second & third nibble
0x01 << 2, // 1 byte data
0xfe // data
]),
root: hexToU8a('0x72813a09bf563fdb6af1d8326329950499fc33c30f3534893381517dc54640b2')
},
substrate0: {
desc: 'substrate (paritial 0)',
input: [
{
k: hexToU8a('0x3a617574683a00000000'),
v: hexToU8a('0x82c39b31a2b79a90f8e66e7a77fdb85a4ed5517f2ae39f6a80565e8ecae85cf5')
},
{
k: hexToU8a('0x7935e46f94f24b82716c0142e2271de9'),
v: hexToU8a('0x0087000000000000')
},
{
k: hexToU8a('0x27b3872d47181b4a2dc15f0da43e7026'),
v: hexToU8a('0xe803000000000000')
}
],
output: hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
),
root: hexToU8a('0xd1d7c0207562afecdb7e8cf945a402b19d378cb337a10535b1c4241454be9e21')
}
};
export default data;

View File

@@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -1,22 +0,0 @@
# @polkadot/util-rlp
Utility methods for encoding and decoding [Ethereum RLP structures](https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP). This is port adapted from the original [EthereumJS RLP](https://github.com/ethereumjs/rlp/blob/0ce09db81fc303fcee593f7cc094ba44015f9b92.js) implementation to cater for `Uint8Array` outputs (instead of `Buffer`) in addition to typings.
## Usage
Installation -
```
yarn add @polkadot/util-rlp
```
Functions can be imported as follows:
```js
import { decode } from '@polkadot/util-rlp';
import { encode } from '@polkadot/util-rlp';
```
## Utilities
[Utilities](SUMMARY.md)

View File

@@ -1,36 +0,0 @@
{
"name": "@polkadot/util-rlp",
"version": "2.0.0-beta.3",
"description": "RLP encoding and decoding",
"main": "index.js",
"keywords": [
"Polkadot"
],
"author": "martin becze <mjbecze@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"contributors": [
"martin becze <mjbecze@gmail.com>"
],
"license": "MPL-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/util-rlp#readme",
"dependencies": {
"@babel/runtime": "^7.7.7",
"@polkadot/util": "^2.0.0-beta.3"
},
"devDependencies": {
"ethereumjs-testing": "1.0.4"
}
}

View File

@@ -1,43 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { hexToU8a, u8aToHex } from '@polkadot/util';
import { decode, encode } from '.';
import getTests from '../test/getTests';
const rlptests = getTests('RLPTests/rlptest.json');
describe('decode', (): void => {
it('returns empty list for undefined inputs', (): void => {
expect(
decode()
).toEqual(
new Uint8Array([])
);
});
it('returns empty list for empty inputs', (): void => {
expect(
decode(new Uint8Array())
).toEqual(
new Uint8Array([])
);
});
rlptests.forEach(({ name, output }): void => {
it(`passes official ${name}`, (): void => {
expect(
u8aToHex(
encode(
decode(
hexToU8a(output)
)
)
)
).toEqual(output);
});
});
});

View File

@@ -1,7 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import decoder from './decoder';
export default decoder;

View File

@@ -1,34 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
import { assert } from '@polkadot/util';
import decodeListLong from './listLong';
import decodeListShort from './listShort';
import decodeNumber from './number';
import decodeSingle from './single';
import decodeString from './string';
interface Decoder {
max: number;
fn: (decode: DecodeFunc, input: Uint8Array) => DecodeOutput;
}
const decoders: Decoder[] = [
{ max: 0x7f, fn: decodeSingle },
{ max: 0xb7, fn: decodeString },
{ max: 0xbf, fn: decodeNumber },
{ max: 0xf7, fn: decodeListShort },
{ max: 0xff, fn: decodeListLong }
];
export default function decode (input: Uint8Array): DecodeOutput {
const decoder = decoders.find(({ max }): boolean => input[0] <= max);
assert(decoder, 'Unable to find decoder for input type');
return decoder.fn(decode, input);
}

View File

@@ -1,39 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { assert, u8aToHex } from '@polkadot/util';
import internalDecode from './decode';
/**
* @name decoder
* @summary Decodes the input RLP.
* @description
* From an input, decode the RLP and return the result as a `Uint8Array` or `Array`.
* @example
* <BR>
*
* ```javascript
* import { decode } from '@polkadot/util-rlp';
*
* decode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])); // => 'dog' as Uint8Array
* ```
*/
export default function decoder (input?: null | Uint8Array): Uint8Array | Uint8Array[] {
try {
if (!input || input.length === 0) {
return new Uint8Array([]);
}
const { decoded, remainder } = internalDecode(input);
assert(remainder.length === 0, 'invalid remainder');
return decoded as Uint8Array;
} catch (error) {
console.error(`RLP failed on input ${u8aToHex(input)}`);
throw error;
}
}

View File

@@ -1,34 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
import { assert } from '@polkadot/util';
import safeParseInt from './safeParseInt';
export default function decodeListLong (decode: DecodeFunc, input: Uint8Array): DecodeOutput {
const llength = input[0] - 0xf6;
const length = safeParseInt(input.slice(1, llength));
const totalLength = llength + length;
const decoded: Uint8Array[] = [];
assert(totalLength <= input.length, 'invalid rlp: total length is larger than the data');
let innerRemainder = input.slice(llength, totalLength);
assert(innerRemainder.length > 0, 'invalid rlp, list has a invalid length');
while (innerRemainder.length) {
const d = decode(innerRemainder);
decoded.push(d.decoded as Uint8Array);
innerRemainder = d.remainder;
}
return {
decoded,
remainder: input.slice(totalLength)
};
}

View File

@@ -1,23 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
export default function decodeListShort (decode: DecodeFunc, input: Uint8Array): DecodeOutput {
const decoded: Uint8Array[] = [];
const length = input[0] - 0xbf;
let innerRemainder = input.slice(1, length);
while (innerRemainder.length) {
const d = decode(innerRemainder);
decoded.push(d.decoded as Uint8Array);
innerRemainder = d.remainder;
}
return {
decoded,
remainder: input.slice(length)
};
}

View File

@@ -1,22 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
import { assert } from '@polkadot/util';
import safeParseInt from './safeParseInt';
export default function decodeNumber (decode: DecodeFunc, input: Uint8Array): DecodeOutput {
const llength = input[0] - 0xb6;
const length = safeParseInt(input.slice(1, llength));
const decoded = input.slice(llength, length + llength);
assert(decoded.length === length, `invalid rlp, expected length ${length}, found ${decoded.length}`);
return {
decoded,
remainder: input.slice(length + llength)
};
}

View File

@@ -1,23 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import safeParseInt from './safeParseInt';
describe('safeParseInt', (): void => {
it('does not allow 0 in first position', (): void => {
expect(
(): number => safeParseInt(
new Uint8Array([0])
)
).toThrow(/invalid rlp, extra zeros found/);
});
it('converts a value to the correct number', (): void => {
expect(
safeParseInt(
new Uint8Array([0x12, 0x34, 0x56])
)
).toEqual(0x123456);
});
});

View File

@@ -1,11 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { assert } from '@polkadot/util';
export default function safeParseInt (input: Uint8Array): number {
assert(input[0] > 0, 'invalid rlp, extra zeros found');
return input.reduce((result, value): number => (result * 256) + value, 0);
}

View File

@@ -1,12 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
export default function decodeSingle (decode: DecodeFunc, input: Uint8Array): DecodeOutput {
return {
decoded: input.slice(0, 1),
remainder: input.slice(1)
};
}

View File

@@ -1,27 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { DecodeFunc, DecodeOutput } from './types';
import { assert } from '@polkadot/util';
export default function decodeString (decode: DecodeFunc, input: Uint8Array): DecodeOutput {
const firstByte = input[0];
const length = firstByte - 0x7f;
let decoded;
// set 0x80 null to 0
if (firstByte === 0x80) {
decoded = new Uint8Array([]);
} else {
decoded = input.slice(1, length);
}
assert(!(length === 2 && decoded[0] < 0x80), 'invalid rlp, byte must be less 0x80');
return {
decoded,
remainder: input.slice(length)
};
}

View File

@@ -1,10 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
export interface DecodeOutput {
decoded: Uint8Array | (Uint8Array | Uint8Array[])[];
remainder: Uint8Array;
}
export type DecodeFunc = (input: Uint8Array) => DecodeOutput;

View File

@@ -1,23 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import { u8aToHex } from '@polkadot/util';
import { encode } from '.';
import getTests from '../test/getTests';
const rlptests = getTests('RLPTests/rlptest.json');
describe('encode', (): void => {
rlptests.forEach(({ name, input, output }): void => {
it(`passes official ${name}`, (): void => {
expect(
u8aToHex(
encode(input)
)
).toEqual(output);
});
});
});

View File

@@ -1,7 +0,0 @@
// Copyright 2017-2020 @polkadot/util-rlp authors & contributors
// This software may be modified and distributed under the terms
// of the MPL-2.0 license. See the LICENSE file for details.
import encoder from './encoder';
export default encoder;

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