Allow blake2 & parity-codec in trie (#251)

* Start codec implementation

* Expose all constants

* NodeHeader encoding/decoding

* Encoding in NodeHeader

* Constants for Node types

* Moce codec to trie-codec

* Encode/decode in place (untested)

* WIP, tests starting to be put in place

* One passing test :)

* Another test bites the dust...

* One more test down...

* One more down

* Additional tests

* Formatting

* Long keys passing

* Trie tests

* Follow the script, no all-in-all encoder

* First simple trie test passing

* Another one down

* Extra checks remove (debug)

* 80% there with tests...

* One more, one left

* Trie tests passing

* ISC -> Apache-2.0

* Add compact util functions

* Tests to TypeScript

* Remove @polkadot/types deps, ethereum stub

* Bump

* Genesis tests with chainspecs

* Cleanup tests (ease of debugging)

* Substrate test passes, branch fails (again)

* Checks passing, tests passing

* Re-add Ethereum & snapshot tests (not passing atm)

* Re-add index test (also not 100%)

* Mid-way in generic trie-root

* Cleanup ethereumjs-testing definitions

* Update deps

* Less intrusive renames in trie-hash

* Self-review cleanups #1

* asNibbles -> toNibbles

* Cleanups

* Expand tests

* Cleanup imports

* Fix logger test (fly-by refactor)

* Update snapshot test
This commit is contained in:
Jaco Greeff
2018-11-22 14:29:34 +01:00
committed by GitHub
parent 5c5b7077cc
commit f82092e603
99 changed files with 2576 additions and 1096 deletions
+1 -1
View File
@@ -43,4 +43,4 @@ To get started -
## tutorials
Looking for tutorials to get started? Look at [examples](https://polkadot.js.org/api/examples/keyring/) for guides on how to use the API.
Looking for tutorials to get started? Look at [examples](https://polkadot.js.org/api/examples/keyring/) for guides on how to use the base utilities.
+4 -1
View File
@@ -2,15 +2,18 @@ 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-(db-old|db|hash)(.*)$': '<rootDir>/packages/trie-$1/src/$2',
'@polkadot/trie-(codec|db|hash)(.*)$': '<rootDir>/packages/trie-$1/src/$2',
'@polkadot/util-(crypto|rlp)(.*)$': '<rootDir>/packages/util-$1/src/$2',
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/db/build',
'<rootDir>/packages/chainspec/build',
'<rootDir>/packages/keyring/build',
'<rootDir>/packages/trie-codec/build',
'<rootDir>/packages/trie-db/build',
'<rootDir>/packages/trie-hash/build',
'<rootDir>/packages/util/build',
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "0.32.23"
"version": "0.33.0"
}
+201
View File
@@ -0,0 +1,201 @@
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.
+3
View File
@@ -0,0 +1,3 @@
# @polkadot/chainspec
Chainspecs for known chains
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@polkadot/chainspec",
"version": "0.33.0",
"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",
"engines": {
"node": ">=6.4"
},
"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.1.5",
"@polkadot/util": "^0.33.0"
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2017-2018 @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 Chainspec = {
bootNodes: Array<string>,
id: string,
genesis: {
raw: {
[index: string]: string
}
},
genesisRoot: string,
name: string,
properties: {
[index: string]: string
},
protocolId: null,
telemetryUrl: string,
};
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/db",
"version": "0.32.23",
"version": "0.33.0",
"description": "Implementation of a basic sync in-memory and on-disk databases with overlays",
"main": "index.js",
"keywords": [
@@ -29,8 +29,8 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/db#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/trie-hash": "^0.32.23",
"@polkadot/util": "^0.32.23",
"@polkadot/trie-hash": "^0.33.0",
"@polkadot/util": "^0.33.0",
"@types/mkdirp": "^0.5.2",
"@types/snappy": "^6.0.0",
"lru_map": "^0.3.3",
+2 -2
View File
@@ -10,7 +10,7 @@ import { LRUMap } from 'lru_map';
import mkdirp from 'mkdirp';
import path from 'path';
import snappy from 'snappy';
import asNibbles from '@polkadot/trie-hash/util/asNibbles';
import { toNibbles } from '@polkadot/trie-codec/util';
import { assert, bufferToU8a, isUndefined, logger, u8aToBuffer, u8aToHex } from '@polkadot/util/index';
import Compact from './Compact';
@@ -174,7 +174,7 @@ export default class FileFlatDb implements BaseDb {
return {
buffer,
nibbles: asNibbles(u8a)
nibbles: toNibbles(u8a)
};
}
+2 -2
View File
@@ -36,7 +36,7 @@ export default class MemoryDb implements BaseDb {
}
rename (base: string, file: string): void {
l.error('rename() is not implemented');
l.warn('rename() is not implemented');
}
maintain (fn: ProgressCb): void {
@@ -48,7 +48,7 @@ export default class MemoryDb implements BaseDb {
}
size (): number {
l.error('size() is not implemented');
l.warn('size() is not implemented');
return 0;
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "0.32.23",
"version": "0.33.0",
"description": "Keyring management",
"main": "index.js",
"engines": {
@@ -31,8 +31,8 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/util": "^0.32.23",
"@polkadot/util-crypto": "^0.32.23",
"@polkadot/util": "^0.33.0",
"@polkadot/util-crypto": "^0.33.0",
"@types/bs58": "^3.0.30",
"bs58": "^4.0.1"
}
+1 -1
View File
@@ -9,7 +9,7 @@ import { stringToU8a } from '@polkadot/util/index';
import Keyring from './index';
function padSeed (seed: string): Uint8Array {
return stringToU8a(seed.padEnd(32, ' '));
return stringToU8a(seed.padEnd(32));
}
const SEEDS: { [index: string ]: Uint8Array } = {
+201
View File
@@ -0,0 +1,201 @@
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.
+3
View File
@@ -0,0 +1,3 @@
# @polkadot/trie-codec
Implementation of the Substrate-specific codec for a Trie
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@polkadot/trie-codec",
"version": "0.33.0",
"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",
"engines": {
"node": ">=6.4"
},
"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.1.5",
"@polkadot/util": "^0.33.0"
}
}
+196
View File
@@ -0,0 +1,196 @@
// Copyright 2017-2018 @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_NULL, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF } 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 class Null {
}
export class BranchHeader extends Boolean {
}
export class NibbleHeader {
private _value: number;
constructor (input: number) {
this._value = input;
}
toNumber (): number {
return this._value;
}
}
export class ExtensionHeader extends NibbleHeader {
}
export class LeafHeader extends NibbleHeader {
}
export default class NodeHeader {
private _nodeType: NodeType;
private _value: Null | BranchHeader | ExtensionHeader | LeafHeader;
constructor (input?: null | Uint8Array | Array<null | Uint8Array>) {
const [nodeType, value] = Array.isArray(input)
? NodeHeader.decodeNodeHeaderArray(input)
: NodeHeader.decodeNodeHeaderU8a(input);
this._nodeType = nodeType;
this._value = value;
}
private static decodeNodeHeaderArray (input: Array<null | Uint8Array>): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] {
if (input.length === 0) {
return [
NODE_TYPE_NULL,
new Null()
];
} else if (input.length === 2) {
const nibbles = decodeNibbles(input[0]);
const isTerminated = isNibblesTerminated(nibbles);
if (isTerminated) {
return [
NODE_TYPE_LEAF,
new LeafHeader(nibbles.length - 1)
];
} else {
return [
NODE_TYPE_EXT,
new ExtensionHeader(nibbles.length)
];
}
} else if (input.length === 17) {
return [
NODE_TYPE_BRANCH,
new BranchHeader(!!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,
new Null()
];
} else if (firstByte === BRANCH_NODE_NO_VALUE) {
return [
NODE_TYPE_BRANCH,
new BranchHeader(false)
];
} else if (firstByte === BRANCH_NODE_WITH_VALUE) {
return [
NODE_TYPE_BRANCH,
new BranchHeader(true)
];
} else if (firstByte >= EXTENSION_NODE_OFFSET && firstByte <= EXTENSION_NODE_SMALL_MAX) {
return [
NODE_TYPE_EXT,
new ExtensionHeader(firstByte - EXTENSION_NODE_OFFSET)
];
} else if (firstByte === EXTENSION_NODE_BIG) {
return [
NODE_TYPE_EXT,
new ExtensionHeader(input[1] + EXTENSION_NODE_THRESHOLD)
];
} else if (firstByte >= LEAF_NODE_OFFSET && firstByte <= LEAF_NODE_SMALL_MAX) {
return [
NODE_TYPE_LEAF,
new LeafHeader(firstByte - LEAF_NODE_OFFSET)
];
} else if (firstByte === LEAF_NODE_BIG) {
return [
NODE_TYPE_LEAF,
new LeafHeader(input[1] + LEAF_NODE_THRESHOLD)
];
}
throw new Error('Unreachable');
}
get encodedLength (): number {
const nodeType = this.nodeType;
if (nodeType === NODE_TYPE_NULL || nodeType === NODE_TYPE_BRANCH) {
return 1;
} else if (nodeType === NODE_TYPE_EXT) {
const nibbleCount = (this.value as ExtensionHeader).toNumber();
return nibbleCount < EXTENSION_NODE_THRESHOLD
? 1
: 2;
} else if (nodeType === NODE_TYPE_LEAF) {
const nibbleCount = (this.value as LeafHeader).toNumber();
return nibbleCount < LEAF_NODE_THRESHOLD
? 1
: 2;
}
throw new Error('Unreachable');
}
get nodeType (): number {
return this._nodeType;
}
get value (): Null | BranchHeader | ExtensionHeader | LeafHeader {
return this._value;
}
toU8a (): Uint8Array {
const nodeType = this.nodeType;
if (nodeType === NODE_TYPE_NULL) {
return new Uint8Array([
EMPTY_TRIE
]);
} else if (nodeType === NODE_TYPE_BRANCH) {
return new Uint8Array([
(this.value as BranchHeader).valueOf() === true
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE
]);
} else if (nodeType === NODE_TYPE_EXT) {
const nibbleCount = (this.value as ExtensionHeader).toNumber();
if (nibbleCount < EXTENSION_NODE_THRESHOLD) {
return new Uint8Array([EXTENSION_NODE_OFFSET + nibbleCount]);
}
return new Uint8Array([
EXTENSION_NODE_BIG,
nibbleCount - EXTENSION_NODE_THRESHOLD
]);
} else if (nodeType === NODE_TYPE_LEAF) {
const nibbleCount = (this.value as LeafHeader).toNumber();
if (nibbleCount < LEAF_NODE_THRESHOLD) {
return new Uint8Array([LEAF_NODE_OFFSET + nibbleCount]);
}
return new Uint8Array([
LEAF_NODE_BIG,
nibbleCount - LEAF_NODE_THRESHOLD
]);
}
throw new Error('Unreachable');
}
}
+19
View File
@@ -0,0 +1,19 @@
// Copyright 2017-2018 @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 EMPTY_TRIE = 0;
export const LEAF_NODE_OFFSET = 1;
export const LEAF_NODE_BIG = 127;
export const EXTENSION_NODE_OFFSET = 128;
export const EXTENSION_NODE_BIG = 253;
export const BRANCH_NODE_NO_VALUE = 254;
export const BRANCH_NODE_WITH_VALUE = 255;
export const LEAF_NODE_THRESHOLD = LEAF_NODE_BIG - LEAF_NODE_OFFSET;
export const EXTENSION_NODE_THRESHOLD = EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET; // 125
export const LEAF_NODE_SMALL_MAX = LEAF_NODE_BIG - 1;
export const EXTENSION_NODE_SMALL_MAX = EXTENSION_NODE_BIG - 1;
export const NODE_TYPE_NULL = 0;
export const NODE_TYPE_BRANCH = 1;
export const NODE_TYPE_EXT = 2;
export const NODE_TYPE_LEAF = 3;
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2017-2018 @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/index';
import decode from './decode';
describe('decode', () => {
it('decodes a leaf', () => {
expect(
decode(Uint8Array.from([
0x05, 0x48, 0x19, 0x04, 0xfe
]))
).toEqual([
Uint8Array.from([0x20, 0x48, 0x19]),
Uint8Array.from([0xfe])
]);
});
it('decodes a branch', () => {
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', () => {
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
]);
});
});
+92
View File
@@ -0,0 +1,92 @@
// Copyright 2017-2018 @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/index';
import NodeHeader, { BranchHeader, NibbleHeader } from './NodeHeader';
import { NODE_TYPE_NULL, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF } from './constants';
import { addNibblesTerminator, encodeNibbles } from './nibbles';
import { toNibbles } from './util';
const l = logger('trie/codec');
l.noop();
function _decode (input: null | Uint8Array): Uint8Array | null | Array<null | Uint8Array | [Uint8Array, Uint8Array]> {
const header = new NodeHeader(input);
const nodeType = header.nodeType;
let offset = header.encodedLength;
if (!input || nodeType === NODE_TYPE_NULL) {
return input;
} else if (nodeType === NODE_TYPE_BRANCH) {
const branch = header.value as BranchHeader;
const bitmap = input[offset] + (input[offset + 1] * 256);
let value: null | Uint8Array = null;
offset += 2;
if (branch.valueOf() === true) {
const [length, bytes] = compactStripLength(input.subarray(offset));
value = bytes;
offset += length;
}
let cursor = 1;
return [
null, null, null, null,
null, null, null, null,
null, null, null, null,
null, null, null, null,
value
].map((value, index) => {
let result: null | Uint8Array | [Uint8Array, Uint8Array] = value;
if ((index < 16) && (bitmap & cursor)) {
const [length, bytes] = compactStripLength(input.subarray(offset));
result = bytes.length === 32
? bytes
: decode(bytes) as any;
offset += length;
}
cursor = cursor << 1;
return result;
});
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
const nibbleCount = (header.value as NibbleHeader).toNumber();
const nibbleLength = Math.floor((nibbleCount + 1) / 2);
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);
offset += nibbleData.length;
const [_, value] = compactStripLength(input.subarray(offset));
return [
encodeNibbles(
nodeType === NODE_TYPE_LEAF
? addNibblesTerminator(nibbles)
: nibbles
),
value
];
}
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;
}
+104
View File
@@ -0,0 +1,104 @@
// Copyright 2017-2018 @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/index';
import encode from './encode';
describe('encoding', () => {
it('encode a small sub-tree', () => {
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 ])
] as any)
).toEqual(Uint8Array.from([
255, 0, 4, 4, 160, 16, 2, 10, 4, 170
]));
});
it('encodes a sub-tree', () => {
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 ])
] 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)', () => {
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
] as any)
).toEqual(hexToU8a(
'0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000'
));
});
});
+100
View File
@@ -0,0 +1,100 @@
// Copyright 2017-2018 @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/index';
import NodeHeader from './NodeHeader';
import { NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL } from './constants';
import { extractKey } from './nibbles';
import { fromNibbles } from './util';
const EMPTY = new Uint8Array();
const BRANCH_VALUE_INDEX = 16;
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 | Array<null | Uint8Array>): Uint8Array {
if (!input) {
return EMPTY;
}
const encoded = encode(input);
// l.debug(() => ['encodeValue', { input, encoded }]);
return compactAddLength(encoded);
}
function _encode (input?: null | Uint8Array | Array<null | Uint8Array>): Uint8Array {
if (isU8a(input)) {
return input;
}
const header = new NodeHeader(input);
const nodeType = header.nodeType;
const u8aHeader = header.toU8a();
if (!input || nodeType === NODE_TYPE_NULL) {
return u8aHeader;
} else if (nodeType === NODE_TYPE_BRANCH) {
let valuesU8a = EMPTY;
let bitmap = 0;
input.reduce((cursor, value, index) => {
if ((index < BRANCH_VALUE_INDEX) && value) {
bitmap = bitmap | cursor;
valuesU8a = u8aConcat(
valuesU8a,
encodeValue(value)
);
}
return cursor << 1;
}, 1);
return u8aConcat(
u8aHeader,
new Uint8Array([(bitmap % 256), Math.floor(bitmap / 256)]),
encodeValue(input[BRANCH_VALUE_INDEX]),
valuesU8a
);
} else if (nodeType === NODE_TYPE_EXT || nodeType === NODE_TYPE_LEAF) {
const [key, value] = input;
return u8aConcat(
u8aHeader,
encodeKey(key),
encodeValue(value)
);
}
throw new Error('Unreachable');
}
export default function encode (input?: null | Uint8Array | Array<null | Uint8Array>): Uint8Array {
const encoded = _encode(input);
// l.debug(() => ['encode', { input, encoded }]);
return encoded;
}
+7
View File
@@ -0,0 +1,7 @@
// Copyright 2017-2018 @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/index';
export default hashing;
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2017-2018 @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;
@@ -2,10 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { NodeEncodedOrEmpty, NodeEncoded } from '../types';
import fromNibbles from '@polkadot/trie-hash/util/fromNibbles';
import toNibbles from '@polkadot/trie-hash/util/asNibbles';
import { fromNibbles, toNibbles } from './util';
const HP_FLAG_2 = 2;
const HP_FLAG_0 = 0;
@@ -15,6 +12,18 @@ 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 extractKey (key: null | Uint8Array): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
export function extractNodeKey ([key]: Array<null | Uint8Array>): Uint8Array {
return removeNibblesTerminator(
decodeNibbles(key)
);
}
export function isNibblesTerminated (nibbles: Uint8Array): boolean {
return nibbles[nibbles.length - 1] === NIBBLE_TERMINATOR;
}
@@ -40,7 +49,7 @@ export function removeNibblesTerminator (nibbles: Uint8Array): Uint8Array {
return nibbles;
}
export function decodeNibbles (value: NodeEncodedOrEmpty): Uint8Array {
export function decodeNibbles (value: null | Uint8Array): Uint8Array {
const nibblesWithFlag = toNibbles(value);
const [flag] = nibblesWithFlag;
@@ -53,7 +62,7 @@ export function decodeNibbles (value: NodeEncodedOrEmpty): Uint8Array {
: rawNibbles;
}
export function encodeNibbles (nibbles: Uint8Array): NodeEncoded {
export function encodeNibbles (nibbles: Uint8Array): Uint8Array {
const flag = isNibblesTerminated(nibbles)
? HP_FLAG_2
: HP_FLAG_0;
@@ -0,0 +1,32 @@
// Copyright 2017-2018 @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/index';
import { BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE } from '../constants';
import createValue from './createValue';
export default function createBranch (value: Uint8Array | null, hasChildren: Array<boolean>): Uint8Array {
let cursor = 1;
const bitmap = hasChildren.reduce((bitmap, value) => {
if (value) {
bitmap = bitmap | cursor;
}
cursor = cursor << 1;
return bitmap;
}, 0);
return u8aConcat(
Uint8Array.from([
value
? BRANCH_NODE_WITH_VALUE
: BRANCH_NODE_NO_VALUE,
(bitmap % 256),
Math.floor(bitmap / 256)
]),
createValue(value)
);
}
@@ -0,0 +1,9 @@
// Copyright 2017-2018 @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]);
}
@@ -0,0 +1,9 @@
// Copyright 2017-2018 @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);
}
@@ -0,0 +1,15 @@
// Copyright 2017-2018 @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/index';
import { fuseNibbles } from '../util';
import createValue from './createValue';
export default function createLeaf (key: Uint8Array, value: Uint8Array): Uint8Array {
return u8aConcat(
fuseNibbles(key, true),
createValue(value)
);
}
@@ -0,0 +1,14 @@
// Copyright 2017-2018 @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)
);
}
@@ -0,0 +1,13 @@
// Copyright 2017-2018 @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/index';
const NO_VALUE = new Uint8Array();
export default function createValue (value: null | Uint8Array): Uint8Array {
return value
? compactAddLength(value)
: NO_VALUE;
}
@@ -0,0 +1,9 @@
// Copyright 2017-2018 @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();
export default function encBranch (value: Uint8Array | null): Uint8Array {
return NO_VALUE;
}
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2017-2018 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import createBranch from './createBranch';
import createEmpty from './createEmpty';
import createExtension from './createExtension';
import createLeaf from './createLeaf';
import createSubstream from './createSubstream';
import createValue from './createValue';
import endBranch from './endBranch';
export default {
createBranch,
createEmpty,
createExtension,
createLeaf,
createSubstream,
createValue,
endBranch
};
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2018 @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 type Codec = {
decode: (input: null | Uint8Array) => Uint8Array | null | Array<null | Uint8Array | Array<null | Uint8Array>>,
encode: (input?: null | Uint8Array | Array<null | Uint8Array>) => Uint8Array
hashing: (input: Uint8Array) => Uint8Array,
type: string
};
@@ -1,4 +1,4 @@
// Copyright 2017-2018 @polkadot/trie-hash authors & contributors
// Copyright 2017-2018 @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.
@@ -29,9 +29,9 @@ describe('fromNibbles', () => {
it('converts an number of values (array)', () => {
expect(
fromNibbles(
[3, 1, 2, 3, 4, 5, 7, 8]
)
fromNibbles(Uint8Array.from([
3, 1, 2, 3, 4, 5, 7, 8
]))
).toEqual(
new Uint8Array([0x31, 0x23, 0x45, 0x78])
);
@@ -1,4 +1,4 @@
// Copyright 2017-2018 @polkadot/trie-hash authors & contributors
// Copyright 2017-2018 @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.
@@ -12,18 +12,18 @@
* <BR>
*
* ```javascript
* import { fromNibbles } from '@polkadot/trie-hash/util';
* import { fromNibbles } from '@polkadot/trie-codec/util';
*
* asNibbles(new Uint8Array([4, 1, 2, 0])); // => Uint8Array([0x41, 0x20]
* fromNibbles(new Uint8Array([4, 1, 2, 0])); // => Uint8Array([0x41, 0x20]
* ```
*/
export default function fromNibbles (nibbles: Uint8Array | Array<number>): Uint8Array {
const u8a = new Uint8Array(nibbles.length / 2);
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 * 2;
u8a[index] = (nibbles[nibIndex] << 4) + nibbles[nibIndex + 1];
u8a.set([(input[nibIndex] << 4) + input[nibIndex + 1]], index);
}
return u8a;
@@ -0,0 +1,34 @@
// Copyright 2017-2018 @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/index';
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: Array<Uint8Array> = [
Uint8Array.from([firstByteSmall + Math.min(nibbles.length, bigThreshold)])
];
const oddFlag = nibbles.length % 2;
if (nibbles.length >= bigThreshold) {
result.push(Uint8Array.from([nibbles.length - bigThreshold]));
}
if (oddFlag === 1) {
result.push(nibbles.subarray(0, 1));
}
result.push(fromNibbles(nibbles.subarray(oddFlag)));
return u8aConcat(...result);
}
+8
View File
@@ -0,0 +1,8 @@
// Copyright 2017-2018 @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';
@@ -0,0 +1,15 @@
// Copyright 2017-2018 @polkadot/trie-codec authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default function sharedPrefixLength (first: Uint8Array, second: Uint8Array): number {
const length = Math.min(first.length, second.length);
for (let index = 0; index < length; index++) {
if (first[index] !== second[index]) {
return index;
}
}
return length;
}
@@ -1,17 +1,17 @@
// Copyright 2017-2018 @polkadot/trie-hash authors & contributors
// Copyright 2017-2018 @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 asNibbles from './asNibbles';
import toNibbles from './toNibbles';
describe('asNibbles', () => {
describe('toNibbles', () => {
it('converts an array', () => {
expect(
asNibbles([
toNibbles(Uint8Array.from([
0x31, 0x23, 0x45
])
]))
).toEqual(
new Uint8Array([3, 1, 2, 3, 4, 5])
);
@@ -19,7 +19,7 @@ describe('asNibbles', () => {
it('converts a single', () => {
expect(
asNibbles(
toNibbles(
stringToU8a('A')
)
).toEqual(
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2017-2018 @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
* @signature toNibbles (input: Uint8Array): Uint8Array
* @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();
}
return input.reduce((nibbles, byte, index) => {
nibbles.set(
[byte >> 4, byte & 0b1111],
index * 2
);
return nibbles;
}, new Uint8Array(input.length * 2));
}
+2 -2
View File
@@ -2,7 +2,7 @@
A re-implementation of a Patricia Trie. Unlike other implementations, this allows for the specification of a hash function as well as encoder/decoder and operates in a sync fashion by default.
This is a JavaScript port of the [Python Ethereum Trie](https://github.com/ethereum/py-trie) with additions to support transactions (checkpoints) and multiple hashing (npot only Keccak, but also Blake2 as found in Polkadot).
This is a JavaScript port of the [Python Ethereum Trie](https://github.com/ethereum/py-trie) with additions to support transactions (checkpoints) and multiple codecs, by default only the Substrate codec.
## Usage
@@ -30,4 +30,4 @@ Below is a list of currently exposed methods published at the [Polkadot-JS Commo
- [is](https://polkadot.js.org/common/trie-db/modules/_util_is_.md)
- [key](https://polkadot.js.org/common/trie-db/modules/_util_key_.md)
- [nibbles](https://polkadot.js.org/common/trie-db/modules/_util_nibbles_.md)
- [node](https://polkadot.js.org/common/trie-db/modules/_util_node_.md)
- [node](https://polkadot.js.org/common/trie-db/modules/_util_node_.md)
+8 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/trie-db",
"version": "0.32.23",
"version": "0.33.0",
"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": [
@@ -29,13 +29,15 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-db#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/db": "^0.32.23",
"@polkadot/trie-hash": "^0.32.23",
"@polkadot/util": "^0.32.23",
"@polkadot/util-crypto": "^0.32.23",
"@polkadot/util-rlp": "^0.32.23"
"@polkadot/db": "^0.33.0",
"@polkadot/trie-codec": "^0.33.0",
"@polkadot/trie-hash": "^0.33.0",
"@polkadot/util": "^0.33.0",
"@polkadot/util-crypto": "^0.33.0"
},
"devDependencies": {
"@polkadot/chainspec": "^0.33.0",
"@polkadot/util-rlp": "^0.33.0",
"ethereumjs-testing": "1.0.4"
}
}
+21 -13
View File
@@ -2,19 +2,27 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { keccakAsU8a as hashing } from '@polkadot/util-crypto/index';
import trieRoot from '@polkadot/trie-hash/root';
import { Codec } from '@polkadot/trie-codec/types';
const EMPTY_NODE = new Uint8Array();
const EMPTY_U8A = trieRoot([]);
const EMPTY_U8A_STR = trieRoot([]);
const EMPTY_HASH = hashing(EMPTY_U8A);
const EMPTY_HASH_STR = EMPTY_HASH.toString();
import { trieRoot } from '@polkadot/trie-hash/index';
export {
EMPTY_NODE,
EMPTY_HASH,
EMPTY_HASH_STR,
EMPTY_U8A,
EMPTY_U8A_STR
export type Constants = {
EMPTY_NODE: Uint8Array,
EMPTY_HASH: Uint8Array,
EMPTY_HASH_STR: string,
EMPTY_U8A: Uint8Array
};
export default function (codec: Codec) {
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
};
}
@@ -5,47 +5,45 @@
import toU8a from '@polkadot/util/u8a/toU8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import ethereumCodec from './ethereumCodec';
import Trie from './index';
import getTests from '../../../test/getTests';
import getTests from '../../util-rlp/test/getTests';
const trietest = getTests('TrieTests/trietest.json');
// const trietest = getTests('TrieTests/trietest.json');
const trieanyorder = getTests('TrieTests/trieanyorder.json');
describe('official tests', () => {
let trie;
// FIXME These are not working, the trie-hash implementation is now substrate-specific
describe.skip('official tests', () => {
let trie: Trie;
beforeEach(() => {
trie = new Trie();
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', () => {
const testNames = Object.keys(trietest);
// describe.skip('ordered tests', () => {
// trietest.forEach(({ name, input, root }) => {
// it(name, () => {
// input.map((input) =>
// trie.put(toU8a(input[0]), toU8a(input[1]))
// );
trietest.forEach(({ name, input, root }) => {
it(name, () => {
input.map((input) =>
trie.put(toU8a(input[0]), toU8a(input[1]))
);
expect(
u8aToHex(trie.getRoot())
).toEqual(
root
);
});
});
});
// expect(
// u8aToHex(trie.getRoot())
// ).toEqual(
// root
// );
// });
// });
// });
describe('unordered tests', () => {
const testNames = Object.keys(trieanyorder);
trieanyorder.forEach(({ name, input, root }) => {
const keys = Object.keys(input);
it(name, () => {
keys.map((key) =>
trie.put(toU8a(key), toU8a(input[key]))
trie.put(toU8a(key), toU8a((input as any)[key]))
);
expect(
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2018 @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/index';
import { decode, encode } from '@polkadot/util-rlp/index';
const codec: Codec = {
decode,
encode,
hashing: blake2AsU8a,
type: 'Ethereum'
};
export default codec;
+26
View File
@@ -0,0 +1,26 @@
// Copyright 2017-2018 @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 bbqbirch from '@polkadot/chainspec/bbqbirch';
import { hexToU8a, u8aToHex } from '@polkadot/util/index';
import Trie from './index';
describe('genesis roots', () => {
[
bbqbirch
].forEach(({ genesis: { raw }, genesisRoot, name }) => {
it(`has the correct root for ${name}`, () => {
const trie = new Trie();
Object.keys(raw).forEach((key) => {
trie.put(hexToU8a(key), hexToU8a(raw[key]));
});
expect(
u8aToHex(trie.getRoot())
).toEqual(genesisRoot);
});
});
});
-266
View File
@@ -1,266 +0,0 @@
// Copyright 2017-2018 @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 Trie from './index';
describe('simple save and retrieve', () => {
const trie = new Trie();
it('starts with a valid root', () => {
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', () => {
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', () => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should update a value', () => {
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', () => {
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', () => {
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', () => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should create a branch here', () => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(
trie.getRoot()
).toEqual(
toU8a('0xde8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc')
);
});
it('should get a value that is in a branch', () => {
expect(
trie.get(toU8a('doge'))
).toEqual(toU8a('coin'));
});
it('should delete from a branch', () => {
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', () => {
const trie = new Trie();
const longString = 'this will be a really really really long value';
const longStringRoot = '0xb173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3';
it('should store a longer string', () => {
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)', () => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should store subsequent values', () => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(longStringRoot).toEqual(u8aToHex(trie.getRoot()));
});
it('should retrieve a longer value (second pass)', () => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should retrieve subsequent values', () => {
expect(trie.get(toU8a('doge'))).toEqual(toU8a('coin'));
});
it('should when being modified delete the old value', () => {
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', () => {
const trie = new Trie();
it('should store a value', () => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should create extention to store this value', () => {
trie.put(toU8a('do'), toU8a('verb'));
expect(
toU8a('0xf803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9')
).toEqual(trie.getRoot());
});
it('should store this value under the extention ', () => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe('testing Extentions and branches - reverse', () => {
const trie = new Trie();
it('should create extention to store this value', () => {
trie.put(toU8a('do'), toU8a('verb'));
const value = trie.get(toU8a('do'));
expect(value).toEqual(toU8a('verb'));
});
it('should store a value', () => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should store this value under the extention ', () => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe('testing deletions cases', () => {
const trie = new Trie();
it('should delete from a branch->branch-branch', () => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch'));
trie.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', () => {
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', () => {
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', () => {
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);
});
});
+274
View File
@@ -0,0 +1,274 @@
// Copyright 2017-2018 @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 './index';
// FIXME These are not working, the trie-hash implementation is now substrate-specific
describe.skip('Ethereum', () => {
const createTrie = () =>
new Trie(undefined, undefined, ethereumCodec);
describe('simple save and retrieve', () => {
const trie = createTrie();
it('starts with a valid root', () => {
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', () => {
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', () => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should update a value', () => {
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', () => {
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', () => {
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', () => {
expect(
trie.get(toU8a('test'))
).toEqual(toU8a('one'));
});
it('should create a branch here', () => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(
trie.getRoot()
).toEqual(
toU8a('0xde8a34a8c1d558682eae1528b47523a483dd8685d6db14b291451a66066bf0fc')
);
});
it('should get a value that is in a branch', () => {
expect(
trie.get(toU8a('doge'))
).toEqual(toU8a('coin'));
});
it('should delete from a branch', () => {
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', () => {
const trie = createTrie();
const longString = 'this will be a really really really long value';
const longStringRoot = '0xb173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3';
it('should store a longer string', () => {
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)', () => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should store subsequent values', () => {
trie.put(toU8a('doge'), toU8a('coin'));
expect(longStringRoot).toEqual(u8aToHex(trie.getRoot()));
});
it('should retrieve a longer value (second pass)', () => {
expect(
trie.get(toU8a('done'))
).toEqual(toU8a(longString));
});
it('should retrieve subsequent values', () => {
expect(trie.get(toU8a('doge'))).toEqual(toU8a('coin'));
});
it('should when being modified delete the old value', () => {
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', () => {
const trie = createTrie();
it('should store a value', () => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should create extention to store this value', () => {
trie.put(toU8a('do'), toU8a('verb'));
expect(
toU8a('0xf803dfcb7e8f1afd45e88eedb4699a7138d6c07b71243d9ae9bff720c99925f9')
).toEqual(trie.getRoot());
});
it('should store this value under the extention ', () => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe.skip('testing Extentions and branches - reverse', () => {
const trie = createTrie();
it('should create extention to store this value', () => {
trie.put(toU8a('do'), toU8a('verb'));
const value = trie.get(toU8a('do'));
expect(value).toEqual(toU8a('verb'));
});
it('should store a value', () => {
trie.put(toU8a('doge'), toU8a('coin'));
});
it('should store this value under the extention ', () => {
trie.put(toU8a('done'), toU8a('finished'));
expect(
'0x409cff4d820b394ed3fb1cd4497bdd19ffa68d30ae34157337a7043c94a3e8cb'
).toEqual(u8aToHex(trie.getRoot()));
});
});
describe('testing deletions cases', () => {
const trie = createTrie();
it('should delete from a branch->branch-branch', () => {
trie.put(new Uint8Array([11, 11, 11]), toU8a('first'));
trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch'));
trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch'));
trie.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', () => {
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', () => {
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', () => {
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);
});
});
});
+36 -27
View File
@@ -3,18 +3,19 @@
// 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, NodeBranch, NodeEncodedOrEmpty, NodeKv, NodeNotEmpty, NodeType } from './types';
import MemoryDb from '@polkadot/db/Memory';
import { isNull, logger , u8aConcat } from '@polkadot/util/index';
import { keccakAsU8a as hashing } from '@polkadot/util-crypto/index';
import toNibbles from '@polkadot/trie-hash/util/asNibbles';
import substrateCodec from '@polkadot/trie-codec/index';
import { decodeNibbles, encodeNibbles, extractNodeKey } from '@polkadot/trie-codec/nibbles';
import { toNibbles } from '@polkadot/trie-codec/util';
import { isNull, logger , u8aConcat, u8aToHex } from '@polkadot/util/index';
import { isBranchNode, isEmptyNode, isExtensionNode, isKvNode, isLeafNode } from './util/is';
import { extractKey, keyEquals, keyStartsWith, computeExtensionKey, computeLeafKey, consumeCommonPrefix } from './util/key';
import { decodeNibbles, encodeNibbles } from './util/nibbles';
import { keyEquals, keyStartsWith, computeExtensionKey, computeLeafKey, consumeCommonPrefix } from './util/key';
import { getNodeType, decodeNode, encodeNode } from './util/node';
import { EMPTY_HASH, EMPTY_U8A } from './constants';
import constants, { Constants } from './constants';
const l = logger('trie/db');
@@ -29,13 +30,19 @@ const l = logger('trie/db');
*/
export default class Trie implements TrieDb {
readonly db: TxDb;
private codec: Codec;
private constants: Constants;
private txRoot: Uint8Array;
private rootHash: Uint8Array;
constructor (db?: TxDb, rootHash: Uint8Array = EMPTY_HASH) {
this.db = db || new MemoryDb();
this.rootHash = rootHash;
this.txRoot = rootHash;
constructor (db: TxDb = new MemoryDb(), rootHash?: Uint8Array, codec: Codec = substrateCodec) {
this.db = db;
this.codec = codec;
this.constants = constants(codec);
this.rootHash = rootHash || this.constants.EMPTY_HASH;
this.txRoot = this.rootHash;
l.log(`Created with ${codec.type} codec, root ${u8aToHex(this.rootHash, 64)}`);
}
private createCheckpoint (): Uint8Array {
@@ -138,7 +145,7 @@ export default class Trie implements TrieDb {
const rootNode = this.getNode();
if (isNull(rootNode)) {
return EMPTY_U8A;
return constants(this.codec).EMPTY_U8A;
}
return this.rootHash;
@@ -188,7 +195,7 @@ export default class Trie implements TrieDb {
}
keys++;
dest.db.put(root, encodeNode(node));
dest.db.put(root, encodeNode(this.codec, node));
fn({ keys, percent });
node.forEach((u8a) => {
@@ -203,15 +210,15 @@ export default class Trie implements TrieDb {
}
private _getNode (hash: Uint8Array | null): Node {
if (!hash || hash.length === 0 || keyEquals(hash, EMPTY_HASH)) {
// l.debug(() => ['_getNode', { hash }]);
if (!hash || hash.length === 0 || keyEquals(hash, this.constants.EMPTY_HASH)) {
return null;
} else if (hash.length < 32) {
return decodeNode(hash);
return decodeNode(this.codec, hash);
}
return decodeNode(
this.db.get(hash)
);
return decodeNode(this.codec, this.db.get(hash));
}
private _del (node: Node, trieKey: Uint8Array): Node {
@@ -257,7 +264,7 @@ export default class Trie implements TrieDb {
private _delKvNode (node: NodeNotEmpty, trieKey: Uint8Array): Node {
// l.debug(() => ['_delKvNode', { node, trieKey }]);
const currentKey = extractKey(node);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
if (!keyStartsWith(trieKey, currentKey)) {
@@ -328,7 +335,7 @@ export default class Trie implements TrieDb {
private _getKvNode (node: NodeKv, trieKey: Uint8Array): NodeEncodedOrEmpty {
// l.debug(() => ['_getKvNode', { node, trieKey }]);
const currentKey = extractKey(node);
const currentKey = extractNodeKey(node);
const nodeType = getNodeType(node);
// l.debug(() => [{ currentKey, trieKey, nodeType }]);
@@ -362,7 +369,7 @@ export default class Trie implements TrieDb {
];
}
const encoded = encodeNode(node);
const encoded = encodeNode(this.codec, node);
if (encoded.length < 32) {
return [
@@ -374,7 +381,7 @@ export default class Trie implements TrieDb {
}
return [
hashing(encoded),
this.codec.hashing(encoded),
encoded
];
}
@@ -470,7 +477,7 @@ export default class Trie implements TrieDb {
private _putKvNode (node: NodeKv, trieKey: Uint8Array, value: Uint8Array): NodeNotEmpty {
// l.debug(() => ['_putKvNode', { node, trieKey, value }]);
const currentKey = extractKey(node);
const currentKey = extractNodeKey(node);
const [commonPrefix, currentRemainder, trieRemainder] = consumeCommonPrefix(currentKey, trieKey);
const isExtension = isExtensionNode(node);
const isLeaf = isLeafNode(node);
@@ -552,14 +559,16 @@ export default class Trie implements TrieDb {
// l.debug(() => ['_setRootNode', { node }]);
if (isEmptyNode(node)) {
this.rootHash = EMPTY_HASH;
this.rootHash = this.constants.EMPTY_HASH;
} else {
const encoded = encodeNode(node);
const newHash = hashing(encoded);
const encoded = encodeNode(this.codec, node);
const rootHash = this.codec.hashing(encoded);
this.db.put(newHash, encoded);
// l.debug(() => ['_setRootNode', { encoded, rootHash }]);
this.rootHash = newHash;
this.db.put(rootHash, encoded);
this.rootHash = rootHash;
}
}
}
-52
View File
@@ -1,52 +0,0 @@
// Copyright 2017-2018 @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 Trie from './index';
describe('snapshots', () => {
it('creates a snapshot of the (relevant) trie data', () => {
const root = 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]);
const trie = new Trie();
const back = new Trie();
trie.put(toU8a('test'), toU8a('one'));
trie.put(toU8a('test'), toU8a('two'));
trie.del(toU8a('test'));
trie.put(toU8a('test'), toU8a('one'));
trie.put(toU8a('doge'), toU8a('coin'));
trie.del(toU8a('doge'));
trie.snapshot(back, () => {});
expect(back.getRoot()).toEqual(root);
expect(trie.get(toU8a('test'))).toEqual(toU8a('one'));
});
it('creates a snapshot of the (relevant) data', () => {
const root = new Uint8Array([124, 157, 64, 253, 245, 26, 3, 63, 210, 140, 4, 56, 214, 180, 147, 0, 167, 60, 113, 206, 171, 136, 88, 84, 139, 142, 230, 40, 42, 113, 21, 242]);
const trie = new Trie();
const back = new Trie();
trie.put(toU8a('one'), toU8a('testing'));
trie.put(toU8a('two'), toU8a('testing with a much longer value here'));
trie.put(toU8a('twzei'), toU8a('und Deutch'));
trie.put(toU8a('do'), toU8a('do it'));
trie.put(toU8a('dog'), toU8a('doggie'));
trie.put(toU8a('dogge'), toU8a('bigger dog'));
trie.put(toU8a('dodge'), toU8a('coin'));
trie.snapshot(back, () => {});
expect(back.getRoot()).toEqual(root);
expect(back.get(toU8a('one'))).toEqual(toU8a('testing'));
expect(back.get(toU8a('two'))).toEqual(toU8a('testing with a much longer value here'));
expect(back.get(toU8a('twzei'))).toEqual(toU8a('und Deutch'));
expect(back.get(toU8a('do'))).toEqual(toU8a('do it'));
expect(back.get(toU8a('dog'))).toEqual(toU8a('doggie'));
expect(back.get(toU8a('dogge'))).toEqual(toU8a('bigger dog'));
expect(back.get(toU8a('dodge'))).toEqual(toU8a('coin'));
});
});
+60
View File
@@ -0,0 +1,60 @@
// Copyright 2017-2018 @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/index';
import { u8aToHex, u8aToU8a as toU8a } from '@polkadot/util/index';
import Trie from './index';
describe('snapshots', () => {
let trie: Trie;
let back: Trie;
beforeEach(() => {
trie = new Trie();
back = new Trie();
});
it('creates a snapshot of the (relevant) trie data', () => {
const values = [
{ k: toU8a('test'), v: toU8a('one') }
];
const root = trieRoot(values);
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 0);
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));
expect(trie.get(values[0].k)).toEqual(values[0].v);
});
it('creates a snapshot of the (relevant) data', () => {
const values = [
{ 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') }
];
const root = trieRoot(values);
values.forEach(({ k, v }) =>
trie.put(k, v)
);
trie.snapshot(back, () => void 0);
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));
values.forEach(({ k, v }) =>
expect(trie.get(k)).toEqual(v)
);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2017-2018 @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/index';
import testdata, { TestData } from '../../trie-hash/test/data';
import Trie from './index';
describe('substrate tests', () => {
let trie: Trie;
const checkRoot = ({ root }: TestData) =>
expect(
u8aToHex(trie.getRoot())
).toEqual(
u8aToHex(root)
);
const putValues = ({ input }: TestData) =>
input.forEach(({ k, v }) =>
trie.put(k, v)
);
beforeEach(() => {
trie = new Trie();
});
Object.values(testdata).forEach((test) => {
it(`hashes ${test.desc}`, () => {
putValues(test);
checkRoot(test);
});
});
// When we have a specific test failing and we want to debug it
// it('does extensionBranch', () => {
// putValues(testdata.extensionBranch);
// checkRoot(testdata.extensionBranch);
// });
});
+2 -16
View File
@@ -2,24 +2,10 @@
// 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/index';
import { EncodedPath, Node } from '../types';
import { isKvNode } from './is';
import { addNibblesTerminator, decodeNibbles, encodeNibbles, removeNibblesTerminator } from './nibbles';
export function extractKey (node: Node): Uint8Array {
if (!isKvNode(node)) {
throw new Error('Can only extract keys from KV branches');
}
const [prefixedKey] = node;
return removeNibblesTerminator(
decodeNibbles(prefixedKey)
);
}
import { EncodedPath } from '../types';
export function keyEquals (key: Uint8Array | null, test: Uint8Array | null): boolean {
if (isNull(key) && isNull(test)) {
+9 -11
View File
@@ -2,14 +2,13 @@
// 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/index';
import nodeDecode from '@polkadot/util-rlp/decode';
import nodeEncode from '@polkadot/util-rlp/encode';
import { isBranchNode, isEmptyNode, isKvNode } from './is';
import { decodeNibbles, isNibblesTerminated } from './nibbles';
export function getNodeType (node: Node): NodeType {
if (isEmptyNode(node)) {
@@ -28,23 +27,22 @@ export function getNodeType (node: Node): NodeType {
throw new Error(`Unable to determine node type`);
}
export function decodeNode (encoded: Uint8Array | Node): Node {
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 decoded = (nodeDecode(encoded) as NodeNotEmpty)
.map((value) =>
const node = codec.decode(encoded) as NodeNotEmpty;
return node.map((value) =>
value && value.length
? value
: null
);
return decoded as NodeNotEmpty;
) as NodeNotEmpty;
}
export function encodeNode (node: Node): Uint8Array {
return nodeEncode(node);
export function encodeNode (codec: Codec, node: Node): Uint8Array {
return codec.encode(node);
}
+3 -18
View File
@@ -1,6 +1,6 @@
# @polkadot/trie-hash
Calculate ordered and unordered [Ethereum Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree) from inputs.
Calculate ordered and unordered [Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree) from inputs.
## Usage
@@ -22,20 +22,5 @@ Below is a list of currently exposed methods published at the [Polkadot-JS Commo
- [trie-hash](https://polkadot.js.org/common/trie-hash/README.md)
- Functions
- Encode
- [encode](https://polkadot.js.org/common/trie-hash/modules/_encode_index_.md)
- [encodeAux](https://polkadot.js.org/common/trie-hash/modules/_encode_aux_.md)
- [encodeHexPrefix](https://polkadot.js.org/common/trie-hash/modules/_encode_hexprefix_.md)
- [encodePairs](https://polkadot.js.org/common/trie-hash/modules/_encode_pairs_.md)
- [encodeShared](https://polkadot.js.org/common/trie-hash/modules/_encode_shared_.md)
- [encodeSingle](https://polkadot.js.org/common/trie-hash/modules/_encode_single_.md)
- Trie Root
- [trieRoot](https://polkadot.js.org/common/trie-hash/modules/_root_.md)
- [trieRootOrdered](https://polkadot.js.org/common/trie-hash/modules/_rootordered_.md)
- Util
- [asNibbles](https://polkadot.js.org/common/trie-hash/modules/_util_asnibbles_.md)
- [fromNibbles](https://polkadot.js.org/common/trie-hash/modules/_util_fromnibbles_.md)
- [genRoot](https://polkadot.js.org/common/trie-hash/modules/_util_genroot_.md)
- [getSharedLength](https://polkadot.js.org/common/trie-hash/modules/_util_sharedlength_.md)
- [pairsUniq](https://polkadot.js.org/common/trie-hash/modules/_util_pairsuniq_.md)
- [sharedPrefixLength](https://polkadot.js.org/common/trie-hash/modules/_util_sharedprefixlength_.md)
- [trieRoot](https://polkadot.js.org/common/trie-hash/modules/_trieroot_.md)
- [trieRootOrdered](https://polkadot.js.org/common/trie-hash/modules/_trierootordered_.md)
+6 -5
View File
@@ -1,7 +1,7 @@
{
"name": "@polkadot/trie-hash",
"version": "0.32.23",
"description": "Creation of triehash values",
"version": "0.33.0",
"description": "Generates trie roots from key-value pairs",
"main": "index.js",
"keywords": [
"Polkadot"
@@ -29,8 +29,9 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-hash#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/util": "^0.32.23",
"@polkadot/util-crypto": "^0.32.23",
"@polkadot/util-rlp": "^0.32.23"
"@polkadot/util": "^0.33.0"
},
"devDependencies": {
"@polkadot/chainspec": "^0.33.0"
}
}
+81
View File
@@ -0,0 +1,81 @@
// Copyright 2017-2018 @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/index';
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
function _buildTrie (input: Array<[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) => {
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(
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) => index >= begin)
.filter(([key]) => key[cursor] === index)
.length;
begin += sharedNibbleCounts[index];
}
begin = start;
return u8aConcat(
stream.createBranch(value, sharedNibbleCounts.map((value) => value > 0)),
...sharedNibbleCounts.map((count) => {
let result = EMPTY;
if (count > 0) {
result = stream.createSubstream(
buildTrie(input.slice(begin, begin + count), cursor + 1, codec, stream)
);
begin += count;
}
return result;
}),
stream.endBranch(value)
);
}
export default function buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array {
const trie = _buildTrie(input, cursor, codec, stream);
return trie;
}
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2018 @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/index';
export {
DEFAULT_CODEC,
DEFAULT_STREAM
};
-21
View File
@@ -1,21 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import { keccakAsU8a } from '@polkadot/util-crypto/index';
import rlpEncode from '@polkadot/util-rlp/encode';
import encode from './index';
export default function encodeAux (pairs: Trie$Pairs, preLength: number): Uint8Array | any[] {
const encoded = encode(pairs, preLength);
const rlped = rlpEncode(encoded);
if (rlped.length <= 31) {
return encoded;
}
return keccakAsU8a(rlped);
}
@@ -1,73 +0,0 @@
// Copyright 2017-2018 @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 encodeHexPrefix from './hexPrefix';
describe('encodeHexPrefix', () => {
it('encodes [0, 0, 1, 2, 3, 4, 5], false', () => {
expect(
encodeHexPrefix(
[0, 0, 1, 2, 3, 4, 5],
false
)
).toEqual(
new Uint8Array([0x10, 0x01, 0x23, 0x45])
);
});
it('encodes [0, 1, 2, 3, 4, 5], false', () => {
expect(
encodeHexPrefix(
[0, 1, 2, 3, 4, 5],
false
)
).toEqual(
new Uint8Array([0x00, 0x01, 0x23, 0x45])
);
});
it('encodes [0, 1, 2, 3, 4, 5], true', () => {
expect(
encodeHexPrefix(
[0, 1, 2, 3, 4, 5],
true
)
).toEqual(
new Uint8Array([0x20, 0x01, 0x23, 0x45])
);
});
it('encodes [1, 2, 3, 4, 5], true', () => {
expect(
encodeHexPrefix(
[1, 2, 3, 4, 5],
true
)
).toEqual(
new Uint8Array([0x31, 0x23, 0x45])
);
});
it('encodes [1, 2, 3, 4], false', () => {
expect(
encodeHexPrefix(
[1, 2, 3, 4],
false
)
).toEqual(
new Uint8Array([0x00, 0x12, 0x34])
);
});
it('encodes [4, 1], true', () => {
expect(
encodeHexPrefix(
[4, 1],
true
)
).toEqual(
new Uint8Array([0x20, 0x41])
);
});
});
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @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 default function encodeHexPrefix (nibbles: Uint8Array | Array<number>, isLeaf: boolean): Uint8Array {
const bits = ((nibbles.length & 1) + (2 * (isLeaf ? 1 : 0))) << 4;
const result: Array<number> = [];
let offset = nibbles.length % 2;
result.push(bits + (offset ? nibbles[0] : 0));
while (offset < nibbles.length) {
result.push((nibbles[offset] << 4) + nibbles[offset + 1]);
offset += 2;
}
return new Uint8Array(result);
}
-60
View File
@@ -1,60 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import encodePairs from './pairs';
import encodeShared from './shared';
import encodeSingle from './single';
import sharedPrefixLength from '../util/sharedPrefixLength';
/**
* @name encode
* @signature encode (pairs: Trie$Pairs, preLength: number): Array<any>
* @summary Encodes Trie Pairs depending on a provided Prefix Length and the amount of pairs
* @description
* - `encode` is called and provided arguments including Trie Pairs and Prefix Length.
* - If the Trie Pairs have no length then return an empty array
* - If the Trie Pairs have a length of 1 then we call `encodeSingle` to return a single encoded array with two elements.
* The first element is a u8a calculated from calling `encodeHexPrefix` with arguments including
* a slice up to the Prefix Length of the pair's key (aka nibbles), and whether it's a leaf.
* The second element is the pair's value.
* - If the Trie Pairs have a length > 1 and we calculate that their Shared Prefix Length > Prefix Length
* then we return early with the results of calling `encodeShared` to return a single encoded array
* with two elements. The first element is a u8a calculated as previously with `encodeHexPrefix` and
* whereas second element is calculated from calling `encodeAux`, which recursively calls this function `encode`
* to obtain an encoded value, and then Recursive Length Prefix (RLP) encodes it. If the length of the RLP encoded u8a
* is less than 32 then return the RLP encoded value, otherwise return call the Keccak-256 hash function from [js-sha3](https://www.npmjs.com/package/js-sha3) library
* on the RLP encoded value and return the result.
* - If the Trie Pairs have a length > 1 and the calculated Share Prefix Length <= Prefix Length
* then we return the array result of calling `encodePairs` and push the pair's value onto the end of the array
* if the Prefix Length !== Pair's Key Length.
*
* @description Refer to [Merkle Patricia Trie specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization)
*/
export default function encode (pairs: Trie$Pairs, preLength: number): Array<any> {
if (pairs.length === 0) {
return [];
}
if (pairs.length === 1) {
return encodeSingle(pairs[0], preLength);
}
const sharedLength = sharedPrefixLength(pairs);
if (sharedLength > preLength) {
return encodeShared(pairs, preLength, sharedLength);
}
const result = encodePairs(pairs, preLength);
result.push(
preLength !== pairs[0].k.length
? ''
: pairs[0].v
);
return result;
}
-45
View File
@@ -1,45 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import encodeAux from './aux';
function calcLength (pairs: Trie$Pairs, preLength: number, index: number, start: number): number {
let length = 0;
for (let j = start; j < pairs.length; j++) {
if (pairs[j].k[preLength] === index) {
length++;
} else {
j = pairs.length;
}
}
return length;
}
export default function encodePairs (pairs: Trie$Pairs, preLength: number): Array<any> {
const result: Array<any> = [];
let start = preLength === pairs[0].k.length
? 1
: 0;
for (let index = 0; index < 16; index++) {
const length = calcLength(pairs, preLength, index, start);
result.push(
length === 0
? ''
: encodeAux(
pairs.slice(start, start + length),
preLength + 1
)
);
start += length;
}
return result;
}
-18
View File
@@ -1,18 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import encodeAux from './aux';
import encodeHexPrefix from './hexPrefix';
export default function encodeShared (pairs: Trie$Pairs, preLength: number, sharedLength: number): Array<any> {
return [
encodeHexPrefix(
pairs[0].k.slice(preLength, sharedLength),
false
),
encodeAux(pairs, sharedLength)
];
}
-17
View File
@@ -1,17 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pair } from '../types';
import encodeHexPrefix from './hexPrefix';
export default function encodeSingle (pair: Trie$Pair, preLength: number): Array<any> {
return [
encodeHexPrefix(
pair.k.slice(preLength),
true
),
pair.v
];
}
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2017-2018 @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 bbqbirch from '@polkadot/chainspec/bbqbirch';
import { hexToU8a, u8aToHex } from '@polkadot/util/index';
import trieRoot from './trieRoot';
describe('genesis roots', () => {
[
bbqbirch
].forEach(({ genesis: { raw }, genesisRoot, name }) => {
it(`has the correct root for ${name}`, () => {
expect(
u8aToHex(
trieRoot(
Object.keys(raw).map((key) => ({
k: hexToU8a(key),
v: hexToU8a(raw[key])
}))
)
)
).toEqual(genesisRoot);
});
});
});
+3 -3
View File
@@ -2,11 +2,11 @@
// 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 './root';
import trieRootOrdered from './rootOrdered';
import trieRoot from './trieRoot';
import trieRootOrdered from './trieRootOrdered';
/**
* @summary Utility methods to create [Ethereum Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree)
* @summary Utility methods to create [Trie hashes](https://github.com/ethereum/wiki/wiki/Patricia-Tree)
*/
export {
trieRoot,
-88
View File
@@ -1,88 +0,0 @@
// Copyright 2017-2018 @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 from '@polkadot/util/string/toU8a';
import hexToU8a from '@polkadot/util/hex/toU8a';
import { trieRoot } from './index';
describe('trieRoot', () => {
it('encodes empty k/v pairs', () => {
expect(
trieRoot([])
).toEqual(
hexToU8a(
'0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'
)
);
});
// https://github.com/paritytech/parity/blob/e95b09348386d01b71901365785c5fa3aa2f7a6d/util/triehash/src/lib.rs#L331
it('encodes a simple k/v pair', () => {
expect(
trieRoot([{
k: stringToU8a('A'),
v: stringToU8a('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
}])
).toEqual(
hexToU8a(
'0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab'
)
);
});
it('encodes two simple k/v pairs', () => {
expect(
trieRoot([
{ k: stringToU8a('A'), v: stringToU8a('aaaa') },
{ k: stringToU8a('B'), v: stringToU8a('bbbb') }
])
).toEqual(
hexToU8a(
'0x59262fe132edbc936eeeec3450ab442c81dcbc6168fb558c61e7a8cc883108e3'
)
);
});
// https://github.com/paritytech/parity/blob/e95b09348386d01b71901365785c5fa3aa2f7a6d/util/triehash/src/lib.rs#L73
it('encodes an array of k/v pairs', () => {
expect(
trieRoot([
{
k: stringToU8a('doe'),
v: stringToU8a('reindeer')
},
{
k: stringToU8a('dog'),
v: stringToU8a('puppy')
},
{
k: stringToU8a('dogglesworth'),
v: stringToU8a('cat')
}
])
).toEqual(
hexToU8a(
'0x8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3'
)
);
});
// https://github.com/paritytech/parity/blob/e95b09348386d01b71901365785c5fa3aa2f7a6d/util/triehash/src/lib.rs#L338
it('matches out-of-order k/v pairs', () => {
expect(
trieRoot([
{ k: new Uint8Array([0x01]), v: new Uint8Array([0x23]) },
{ k: new Uint8Array([0x81]), v: new Uint8Array([0x23]) },
{ k: new Uint8Array([0xf1]), v: new Uint8Array([0x23]) }
])
).toEqual(
trieRoot([
{ k: new Uint8Array([0x01]), v: new Uint8Array([0x23]) },
{ k: new Uint8Array([0xf1]), v: new Uint8Array([0x23]) },
{ k: new Uint8Array([0x81]), v: new Uint8Array([0x23]) }
])
);
});
});
@@ -1,23 +0,0 @@
// Copyright 2017-2018 @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 { hexToU8a, stringToU8a } from '@polkadot/util/index';
import { trieRootOrdered } from './index';
describe('trieRootOrdered', () => {
// https://github.com/paritytech/parity/blob/e95b09348386d01b71901365785c5fa3aa2f7a6d/util/triehash/src/lib.rs#L42
it('encodes a values', () => {
expect(
trieRootOrdered([
stringToU8a('doe'),
stringToU8a('reindeer')
])
).toEqual(
hexToU8a(
'0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3'
)
);
});
});
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2017-2018 @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/index';
import trieRoot from './trieRoot';
import testdata from '../test/data';
describe('trieRoot', () => {
Object.values(testdata).forEach(({ desc, input, root }) => {
it(`hashes ${desc}`, () => {
expect(
u8aToHex(trieRoot(input))
).toEqual(
u8aToHex(root)
);
});
});
});
@@ -2,11 +2,11 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Trie$Pairs } from './types';
import { Codec } from '@polkadot/trie-codec/types';
import { TriePair } from './types';
import asNibbles from './util/asNibbles';
import genRoot from './util/genRoot';
import pairsUniq from './util/pairsUniq';
import { DEFAULT_CODEC } from './defaults';
import unhashedTrie from './unhashedTrie';
/**
* @name trieRoot
@@ -27,11 +27,8 @@ import pairsUniq from './util/pairsUniq';
* }]); // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab
* ```
*/
export default function trieRoot (pairs: Trie$Pairs): Uint8Array {
return genRoot(
pairsUniq(pairs).map(({ k, v }) => ({
k: asNibbles(k),
v
}))
export default function trieRoot (input: Array<TriePair>, codec: Codec = DEFAULT_CODEC): Uint8Array {
return codec.hashing(
unhashedTrie(input, codec)
);
}
@@ -0,0 +1,20 @@
// Copyright 2017-2018 @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/index';
import { trieRootOrdered } from './index';
describe('trieRootOrdered', () => {
it('encodes values', () => {
expect(
u8aToHex(
trieRootOrdered([
stringToU8a('doe'),
stringToU8a('reindeer')
])
)
).toEqual('0xb9b1bb07e481f0393e15f32f34abd665f7a698786a7ec9feb31b2e8927ad5f86');
});
});
@@ -1,11 +1,13 @@
// Copyright 2017-2018 @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 rlpEncode from '@polkadot/util-rlp/encode';
import { Codec } from '@polkadot/trie-codec/types';
import asNibbles from './util/asNibbles';
import genRoot from './util/genRoot';
import pairsUniq from './util/pairsUniq';
import { compactToU8a } from '@polkadot/util/index';
import { DEFAULT_CODEC } from './defaults';
import trieRoot from './trieRoot';
/**
* @name trieRootOrdered
@@ -26,15 +28,12 @@ import pairsUniq from './util/pairsUniq';
* ]); // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3
* ```
*/
export default function trieRootOrdered (values: Array<Uint8Array>): Uint8Array {
return genRoot(
pairsUniq(
values.map((v, index) => ({
k: asNibbles(
rlpEncode(index)
),
v
}))
)
export default function trieRootOrdered (input: Array<Uint8Array>, codec: Codec = DEFAULT_CODEC): Uint8Array {
return trieRoot(
input.map((v, index) => ({
k: compactToU8a(index),
v
})),
codec
);
}
+1 -3
View File
@@ -2,9 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export type Trie$Pair = {
export type TriePair = {
k: Uint8Array,
v: Uint8Array
};
export type Trie$Pairs = Array<Trie$Pair>;
@@ -0,0 +1,20 @@
// Copyright 2017-2018 @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/index';
import unhashedTrie from './unhashedTrie';
import testdata from '../test/data';
describe('unhashedTrie', () => {
Object.values(testdata).forEach(({ desc, input, output }) => {
it(`encodes ${desc}`, () => {
expect(
u8aToHex(unhashedTrie(input))
).toEqual(
u8aToHex(output)
);
});
});
});
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2017-2018 @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/index';
import buildTrie from './buildTrie';
import { DEFAULT_CODEC } from './defaults';
export default function unhashedTrie (input: Array<TriePair>, codec: Codec = DEFAULT_CODEC): Uint8Array {
const map = input.reduce((result, pair) => {
result[u8aToHex(pair.k)] = pair;
return result;
}, ({} as { [index: string]: TriePair }));
const pairs = Object
.keys(map)
.sort()
.map((key) => map[key])
.map(({ k, v }) => ([toNibbles(k), v] as [Uint8Array, Uint8Array]));
return buildTrie(pairs, 0, codec);
}
View File
-34
View File
@@ -1,34 +0,0 @@
// Copyright 2017-2018 @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.
/**
* @name asNibbles
* @signature asNibbles (bytes: Uint8Array | Array<number>): Uint8Array
* @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 { asNibbles } from '@polkadot/trie-hash/util';
*
* asNibbles(new Uint8Array([0x41, 0x20]); // => Uint8Array([4, 1, 2, 0])
* ```
*/
export default function asNibbles (bytes: Uint8Array | Array<number> | null): Uint8Array {
if (bytes === null) {
return new Uint8Array();
}
// HACK TypeScript gets a little bit confused as to what to apply, hence casting here although the reduces function for both types does exactly the same
return (bytes as number[]).reduce((nibbles, byte, index) => {
nibbles.set(
[byte >> 4, byte & 0b1111],
index * 2
);
return nibbles;
}, new Uint8Array(bytes.length * 2));
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import { keccakAsU8a } from '@polkadot/util-crypto/index';
import rlpEncode from '@polkadot/util-rlp/encode';
import encode from '../encode';
/**
* @name genRoot
* @signature genRoot (pairs: Trie$Pairs): Uint8Array
* @summary Encodes supplied pairs into u8a output by calculating with RLP.
*/
export default function genRoot (pairs: Trie$Pairs): Uint8Array {
const encoded = encode(pairs, 0);
return keccakAsU8a(
rlpEncode(
encoded.length
? encoded
: new Uint8Array([])
)
);
}
@@ -1,44 +0,0 @@
// Copyright 2017-2018 @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 pairsUniq from './pairsUniq';
describe('pairsUniq', () => {
it('returns non-duplicated unchanged', () => {
expect(
pairsUniq([
{ k: new Uint8Array([0x1]), v: 'A' },
{ k: new Uint8Array([0x2]), v: 'B' }
])
).toEqual([
{ k: new Uint8Array([0x1]), v: 'A' },
{ k: new Uint8Array([0x2]), v: 'B' }
]);
});
it('removes duplicated pairs', () => {
expect(
pairsUniq([
{ k: new Uint8Array([0x1]), v: 'A' },
{ k: new Uint8Array([0x2]), v: 'B' },
{ k: new Uint8Array([0x1]), v: 'C' }
])
).toEqual([
{ k: new Uint8Array([0x1]), v: 'C' },
{ k: new Uint8Array([0x2]), v: 'B' }
]);
});
it('sorts pairs as returned', () => {
expect(
pairsUniq([
{ k: new Uint8Array([0x2]), v: 'B' },
{ k: new Uint8Array([0x1]), v: 'A' }
])
).toEqual([
{ k: new Uint8Array([0x1]), v: 'A' },
{ k: new Uint8Array([0x2]), v: 'B' }
]);
});
});
-29
View File
@@ -1,29 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pair, Trie$Pairs } from '../types';
import { u8aToHex } from '@polkadot/util/index';
type PairMap = {
[index: string]: Trie$Pair
};
/**
* @name pairsUniq
* @signature pairsUniq (pairs: Trie$Pairs): Trie$Pairs
* @summary Removes pairs with duplicate keys from the supplied pairs.
*/
export default function pairsUniq (pairs: Trie$Pairs): Trie$Pairs {
const map = pairs.reduce((result, pair) => {
result[u8aToHex(pair.k)] = pair;
return result;
}, ({} as PairMap));
return Object
.keys(map)
.sort()
.map((key) => map[key]);
}
@@ -1,23 +0,0 @@
// Copyright 2017-2018 @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.
/**
* @name getSharedLength
* @signature getSharedLength (a: Uint8Array, b: Uint8Array): number
* @summary Returns the highest shared index of two u8a's where the values in lesser indexes are the same.
* Given two u8a's, it first determines the u8a with the shortest length,
* then iterates through each u8a up to that length. If the value in both u8a's is
* the same for a certain index, it returns that index, otherwise it returns the shortest length.
*/
export default function getSharedLength (a: Uint8Array, b: Uint8Array): number {
const count = Math.min(a.length, b.length);
for (let index = 0; index < count; index++) {
if (a[index] !== b[index]) {
return index;
}
}
return count;
}
@@ -1,34 +0,0 @@
// Copyright 2017-2018 @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 sharedPrefixLength from './sharedPrefixLength';
describe('sharedPrefixLength', () => {
it('returns 0 where no matches found', () => {
expect(
sharedPrefixLength([
{ k: new Uint8Array([1, 2, 3, 4, 5, 6]) },
{ k: new Uint8Array([4, 2, 3, 4, 5, 6]) }
])
).toEqual(0);
});
it('returns min length where match found', () => {
expect(
sharedPrefixLength([
{ k: new Uint8Array([1, 2, 3, 3, 5]) },
{ k: new Uint8Array([1, 2, 3]) }
])
).toEqual(3);
});
it('returns max length where match found', () => {
expect(
sharedPrefixLength([
{ k: new Uint8Array([1, 2, 3, 4, 5, 6]) },
{ k: new Uint8Array([1, 2, 3, 4, 5, 6]) }
])
).toEqual(6);
});
});
@@ -1,24 +0,0 @@
// Copyright 2017-2018 @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 { Trie$Pairs } from '../types';
import getSharedLength from './sharedLength';
/**
* @name sharedPrefixLength
* @signature sharedPrefixLength (pairs: Trie$Pairs): number
*/
export default function sharedPrefixLength (pairs: Trie$Pairs): number {
return pairs.reduce((length, { k }, index) => {
if (index === 0) {
return k.length;
}
return Math.min(
getSharedLength(pairs[0].k, k),
length
);
}, 0);
}
+263
View File
@@ -0,0 +1,263 @@
// Copyright 2017-2018 @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/index';
export type TestData = {
desc: string,
input: Array<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;
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "0.32.23",
"version": "0.33.0",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -29,7 +29,7 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/util": "^0.32.23",
"@polkadot/util": "^0.33.0",
"@types/bip39": "^2.4.0",
"bip39": "^2.5.0",
"blakejs": "^1.1.0",
@@ -16,4 +16,10 @@ describe('naclDecrypt', () => {
message
);
});
it('returns null on invalid', () => {
expect(
naclDecrypt(new Uint8Array(), new Uint8Array(24), new Uint8Array(32))
).toEqual(null);
});
});
+1 -1
View File
@@ -20,5 +20,5 @@ import nacl from 'tweetnacl';
* ```
*/
export default function naclDecrypt (encrypted: Uint8Array, nonce: Uint8Array, secret: Uint8Array): Uint8Array | null {
return nacl.secretbox.open(encrypted, nonce, secret);
return nacl.secretbox.open(encrypted, nonce, secret) || null;
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-rlp",
"version": "0.32.23",
"version": "0.33.0",
"description": "RLP encoding and decoding",
"main": "index.js",
"keywords": [
@@ -28,10 +28,10 @@
"bugs": {
"url": "https://github.com/polkadot-js/common/issues"
},
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-hash#readme",
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-rlp#readme",
"dependencies": {
"@babel/runtime": "^7.1.5",
"@polkadot/util": "^0.32.23"
"@polkadot/util": "^0.33.0"
},
"devDependencies": {
"ethereumjs-testing": "1.0.4"
+1 -1
View File
@@ -6,7 +6,7 @@ import { hexToU8a, u8aToHex } from '@polkadot/util/index';
import { decode, encode } from './index';
import getTests from '../../../test/getTests';
import getTests from '../test/getTests';
const rlptests = getTests('RLPTests/rlptest.json');
+1 -1
View File
@@ -21,7 +21,7 @@ import internalDecode from './decode';
* decode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])); // => 'dog' as Uint8Array
* ```
*/
export default function decoder (input?: Uint8Array): Uint8Array | Array<any> {
export default function decoder (input?: null | Uint8Array): Uint8Array | Array<any> {
try {
if (!input || input.length === 0) {
return new Uint8Array([]);
+1 -1
View File
@@ -6,7 +6,7 @@ import { u8aToHex } from '@polkadot/util/index';
import { encode } from './index';
import getTests from '../../../test/getTests';
import getTests from '../test/getTests';
const rlptests = getTests('RLPTests/rlptest.json');
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "0.32.23",
"version": "0.33.0",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [
+1 -1
View File
@@ -107,7 +107,7 @@ function noop (...values: Logger$Data): void {
* ```
*/
export default function logger (_type: string): Logger {
const type = ` ${_type.toUpperCase()}:`.slice(-16);
const type = `${_type.toUpperCase()}:`.padStart(16);
let isDebug;
try {
+2 -1
View File
@@ -3,9 +3,10 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@polkadot/chainspec/*": [ "packages/chainspec/src/*" ],
"@polkadot/db/*": [ "packages/db/src/*" ],
"@polkadot/keyring/*": [ "packages/keyring/src/*" ],
"@polkadot/trie-db-old/*": [ "packages/trie-db-old/src/*" ],
"@polkadot/trie-codec/*": [ "packages/trie-codec/src/*" ],
"@polkadot/trie-db/*": [ "packages/trie-db/src/*" ],
"@polkadot/trie-hash/*": [ "packages/trie-hash/src/*" ],
"@polkadot/util-crypto/*": [ "packages/util-crypto/src/*" ],